How can I create JS event listeners that survive a document.write?
Asked Answered
M

4

4

I'm attaching an event listener to the window object. Then later in the script, document.write is being used. (I know, it's evil. I have no choice in the matter.) The problem is, the document.write wipes out my listeners. Is is possible to avoid that?

Here's a fiddle that illustrates the problem: http://jsfiddle.net/Fuhzu/

Myrt answered 29/12, 2011 at 20:9 Comment(2)
No choice? Can't use div id=me me.innerHTML = "hah"? Or hah = document.createElement(span) me.appendChild(hah)?Ewe
No -- I have to work with some other existing code. It's possible that that could someday be changed, but not immediately.Myrt
K
3

That is not possible. document.write unloads the current document, and creates a new one.

A demo to confirm: http://jsfiddle.net/Gk3cX/

window.test = document; //Cache document
document.write('<button onclick="alert(window.test===document)">CLick</button>');
// Clicking shows false! The document has changed!

Your only choice for overwriting the current document without unloading is innerHTML:

document.body.innerHTML = "Overwritten document's content, kept events.";
Katabatic answered 29/12, 2011 at 20:14 Comment(0)
M
2

The work-around I've found is to simply re-attach the listeners after the document.write.

Update: Doh! That works in Chrome, but FF throws an error:

attempt to run compile-and-go script on a cleared scope

http://jsfiddle.net/NYyKH/

Maybe if I unattach the handler before document.writing....

Update 2: nope: http://jsfiddle.net/sprugman/KzNbX/1/

Myrt answered 29/12, 2011 at 21:13 Comment(0)
D
0

How about replacing document.write with your own function, that way it won't destroy the page.

Something like this:

document.write = function(str){
    document.body.innerHTML = str;
};

Or if you don't want to erase the whole page:

document.write = function(str){
    document.body.innerHTML += str;
};

DEMO: http://jsfiddle.net/Fuhzu/1/

Daryn answered 29/12, 2011 at 21:22 Comment(3)
Easier said than done when your script is part of an ad chain which calls more scripts which may or may not have document.write in them.Myrt
@sprugman: What if you declare this at the top of your page, before those scripts are ran?Daryn
I don't have control of the page. I'm creating a script that other people embed in their pages, and there are many, many possible embedding situations, so overwriting document.write could easily break something without my knowing it.Myrt
G
0

i haven't tried this with document.write, but maybe it helps: http://api.jquery.com/live/

Attach an event handler for all elements which match the current selector, now and in the future

Gypsy answered 29/12, 2011 at 22:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.