views:

434

answers:

1

For my own purposes (cough lazy-loading an ad script), I am overwriting the document.write function in order to buffer the script's output, writing it to a div, and restoring the native document.write when I am done.

The pseudo-code looks something like this:

  • save off native code document.write
  • redefine document.write
  • eval and buffer output of script
  • when script is done, write buffer to
  • restore native document.write

The problem happens in the bolded step - one of the lines in the ad script creates an iframe, and calls

frame.document.write

Stepping through Firebug, I have verified that this document.write is the native JS code and not my overwritten version.

Is there a way to overwrite document.write for ALL windows and frames? This is a scoping issue, but I'm not sure how to force my document.write to prevail.

+4  A: 

Every window is a unique and precious snowflake, and as such is brought into this world with certain gifts from the Creator. Among those gifts are its own "window" and "document" objects, as fresh and pure as the crystal-clear primeval oceans at the Dawn of Time.

Similarly, all of the basic Javascript "classes" (Function, Array, RegExp, etc) are all "clean". That's why when you load a page into an iframe, if that page has its own local scripts that rely on (say) jQuery it has to import its own copy of the library.

Pointy
+1 for humor and making me laugh out loud after working on this for 14 hours straight ;)
Bilal Aslam
"jQuery it has to import its own copy of the library" -- how can I do this? I'd like to overwrite the document.write function when a new frame is created. Can I do this?
Bilal Aslam
Well, in your "child" page - the page that loads into the iframe - you just have a script tag for jquery in that page's "head" section. Really an iframe is almost exactly like a regular browser window. The main difference is that it can find it's "parent" and the parent can find its "child".
Pointy
Strictly speaking, the Javascript code in the child (iframe) document *could* use jQuery from the parent, but it would have to be coded like that - in other words, instead of "$('#foo').whatever()" it would have to be "window.parent.$('#foo')", and even then it wouldn't be "#foo" because it would have to explicitly navigate back down into the child. Not a fun way to do things.
Pointy