4

I am writing to an iframe via document.write then trying to overwrite the document on that same iframe. In FF this works properly. However, in chrome code from the initial document.write persists even after I overwrite it with a second document.write.

See this fiddle: http://jsfiddle.net/meQcC/

If you view it in FF as one would expect, the iframe is blank and you actually get a "function onLoad is not defined error" because in the line

doc.write("<html><head><script>;" +
      "<\/script></head><body onload='onLoad()'></body></html>");

There is obviously no onLoad function defined. However, if you view the same fiddle in chrome, the iframe will display a black rectangle, and there will be no error regarding the onLoad call, it will call the previously defined function as though it still exists!!!!

Is there any way to clear the document in chrome so that I can overwrite the contents of the iframe without old code somehow persisting? Is this a bug in chrome?

asutherland
  • 2,849
  • 4
  • 32
  • 50

2 Answers2

5

Yes, this is a bug in Chrome (or more precisely in WebKit). Per spec, it should be creating a new Window object and removing all global event listeners, and it's not doing that.

In particular, see http://www.whatwg.org/specs/web-apps/current-work/multipage/elements.html#dom-document-open step 14.

Boris Zbarsky
  • 34,758
  • 5
  • 52
  • 55
2

Deleting a <script> does not undefine any functions it defined.

If you want to achieve that you need to keep a list of all globals you create and delete them using delete window.WHATEVER;

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
  • is there any way to just clear/reset the window object? Any idea why the behavior is different in FF and in chrome? My understand was that it should completely reset the iframe but your answer makes a lot of sense. – asutherland Sep 14 '12 at 02:02
  • You can't delete certain properties using that operator. Check [Description section of MDN delete article](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete) for more information. – Leonid Vasilev Feb 06 '17 at 15:18
  • You miss the point. `document.write` calls `document.open`, which according to the spec says a new window object should be attached to the cleared document. See: https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-document-open – Gui Prá Oct 30 '17 at 21:13