1

There are a few cases where I need to solve a problem by pushing content into an iframe from the outside page. Most of the time this is not possible given the browser security around iframes, and I've had a lot of trouble getting stuff in there using data urls.

More recently I've discovered contentWindow:

var iframe = document.getElementById('myIframe');
iframe = (iframe.contentWindow) ? iframe.contentWindow : (iframe.contentDocument.document) ? iframe.contentDocument.document : iframe.contentDocument;
iframe.document.write('<body><script src="http://anything/you/want.js"></script><h1>Any html content or script tags</h1></body>');

...which can be used to dynamically push content into an iframe. It seems to work pretty well in all situations, so I'm just wondering if there's some major drawback of this method which I haven't seen yet, or is it not very widespread simply because it doesn't work in ie8? It seems too good to be true...

tripRev
  • 830
  • 3
  • 12
  • 27
  • 1
    What are you trying to do with IFrames? Unless your goal is to inject script into a page on another domain to scrape/read it, there is probably a better way of accomplishing what you want. There's aren't any inherent disadvantages to this as far as I know, but it's failure-prone and potentially a bad idea. – Hydrothermal Jun 29 '14 at 14:07
  • 1
    @Hydrothermal to cut a long story short, the 3rd party content going on the page has a script on it which uses document.write to write content in. If I don't isolate it down into an iframe, it writes over the whole page (document.write does this when injected after initial page load). – tripRev Jun 29 '14 at 14:13
  • 1
    Interesting. Have you considered overwriting the `document.write` method, as per [this answer](http://stackoverflow.com/a/5409584/2789699)? It's hacky, but I feel like it would be more controllable than injecting into an IFrame. – Hydrothermal Jun 29 '14 at 14:24
  • 1
    @Hydrothermal that's a good alternative, thanks. – tripRev Jun 29 '14 at 20:34

0 Answers0