Note that there are some explanatory texts on larger screens.

plurals
  1. POCopying an entire document into an iframe with javascript
    text
    copied!<p>It sounds wonky, but this is what I'm trying to do with javascript (this is all triggered by an event handler):</p> <ol> <li>Save the contents of a page (preferably the whole document or at least documentElement object) into a variable.</li> <li>Create an iframe and insert it into the body.</li> <li>Replace the document of the iframe with the saved document (so that the iframe now has the same content as the outer page).</li> <li>Change the outer page.</li> </ol> <p>Everything is dandy except the part about replacing the iframe's document. I've tried a bunch of different things, but all have problems (they are outlined below). I need event handlers, styles, links, etc to all work correctly when the page is in the iframe.</p> <p>And yes, I realize that I could just set the src of the iframe to the url of the current page, but I'd rather the page not have to load. If I can't come up with a solution, this is what I'll do.</p> <hr> <h3>Things that I've already tried:</h3> <pre><code>var html = iframe.contentWindow.document.importNode(document.documentElement, true); iframe.contentWindow.documentElement = html; </code></pre> <p>I get an error message ("setting a property that only has a getter").</p> <pre><code>var html = iframe.contentWindow.document.importNode(document.documentElement, true); var idoc = iframe.contentWindow.document; while(idoc.firstChild) idoc.removeChild(idoc.firstChild); // remove all children (firefox automatically creates an html element for iframes with no src) idoc.appendChild(html); // insert a new documentElement </code></pre> <p>This seems to work, but doesn't re-render the styles, and event handlers don't work. Interestingly, links don't work either, and they aren't even styled with the browser's default styles. Maybe this is because the DOCTYPE isn't copied to the iframe?</p> <pre><code>iframe.contentWindow.document.documentElement.innerHTML = document.documentElement.innerHTML; </code></pre> <p>This has the same behavior as the removeChild/appendChild method.</p> <hr> <p>It seems like if I could just get the browser to re-render the styles and re-register the event handlers then I'd be golden, but I'm not sure if this is even possible.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload