1

This question didn't receive any satisfactory answers, so I'm asking again.

I can get my iframe like this:

var iframe = document.getElementById('preview');
var win = iframe.contentWindow;
var doc = win.document;

And write some initial HTML to it like this:

doc.write('<!DOCTYPE html><html><head><link rel="stylesheet" type="text/css" href="reset.css"></head><body>blah blah</body></html>');

And that works great, but now I want to replace the entire thing with some new content. How can I do that?

To be clear, by "entire thing" I mean the <head> too. I need to link some external JS and CSS there.

Preferably, this would also include the <!DOCTYPE>, but it's non-essential at this point.

Community
  • 1
  • 1
mpen
  • 272,448
  • 266
  • 850
  • 1,236
  • @RobG: Actually, no. The two answers posted here are completely different than the ones posted there, and they actually work. Why did I expect something different? Because it's been half a year since that last question was posted and there's a new user base here, and because I can't effectively bump an old question. – mpen Oct 15 '11 at 23:33
  • @RobG: Also, Esailija posted some insightful tips that I didn't know and weren't present in the other answers either. – mpen Oct 15 '11 at 23:38
  • got your question confused with a very similar one posted about the same time. – RobG Oct 17 '11 at 12:10

2 Answers2

2

You could simply remove the old iframe node from the DOM and create a new one containing the new contents.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Yes, theoretically I could replace the entire iframe, but wouldn't it be more efficient to replace just the iframe's document? Is it possible to do that? – mpen Oct 15 '11 at 21:55
  • 1
    Setting `doc.documentElement.outerHTML` to something gives `message: "NO_MODIFICATION_ALLOWED_ERR: DOM Exception 7"`, so you can't replace the entire document but anything below `` element is possible (`` and ``) – Esailija Oct 15 '11 at 22:04
  • @Esailija: Good to know! With your help, I think I've got everything I need to know now! :) I believe this makes Darin's solution the most effective answer. – mpen Oct 15 '11 at 23:37
2

I believe using innerHTML should work:

doc.documentElement.innerHTML = "<script src='blah.js'></script><style></style>"
gereeter
  • 4,731
  • 1
  • 28
  • 28
  • Ah...that explains why my attempts weren't working. Have to do it on the `documentElement`! That seems to work, but I can't set the ` ` with this method, can I? Basically this replaces the *contents* of `` no? – mpen Oct 15 '11 at 21:54
  • 1
    the ` ` element itself isn't modifiable but the document has property `iframe.contentWindow.document.doctype` which has properties like `doc.doctype.systemId`. The properties are read-only so it is probably not recommended to try and change the doctype dynamically – Esailija Oct 15 '11 at 22:10