0

I'm trying to pass a script into an iframe dynamically so it will run there (content in the example comes from the server) using this snippet:

content = '<script type="text/javascript">document.write("<a   href="http://www.example.com" target="_blank">bla</a>"");</script>';
el = document.getElementById('iframeName');
iframeDoc = el.contentWindow.document;

tempEl = iframeDoc.createElement('div');
tempEl.innerHTML = content;

It runs great on new browsers but when I try to run it on IE8 and lower, the innerHTML comes up null. I tried different approaches but the inner HTML is the only option i can think of that can run the script i'm passing in to tempEl. Any ideas on how to pass content into tempEl.innerHTML so it will run the script and also work on IE8-?

Yuval
  • 307
  • 3
  • 14
  • 2
    Judging by the syntax highlighting, I'd love to know how this "runs great on new browsers"... – Niet the Dark Absol Apr 16 '14 at 10:41
  • 1
    possible duplicate of [How to set HTML content into an iframe in IE8, IE9](http://stackoverflow.com/questions/16504816/how-to-set-html-content-into-an-iframe-in-ie8-ie9) – Vucko Apr 16 '14 at 10:43
  • Do you know if your iframeDoc reference is valid? Also, maybe try: iframeDoc.body.createElement('div'); – richb01 Apr 16 '14 at 10:52
  • I think I got it, I went by the question @Vucko pointed out and took off `tempEl` and added `iframeDoc.write(content);` – Yuval Apr 16 '14 at 11:01
  • @NiettheDarkAbsol noted, fixed syntax. – Yuval Apr 16 '14 at 11:06
  • @richb01 the iframeDoc reference is valid and I tried iframeDoc.body.createElement('div') , it didn't help. – Yuval Apr 16 '14 at 11:07
  • [SO: .InnerHTML Not working properly in Internet Explorer](http://stackoverflow.com/questions/5243756/innerhtml-not-working-properly-in-internet-explorer)..? An answer to this question states that scripts must be written to the `` of the document. – Mr. Polywhirl Apr 16 '14 at 11:11

2 Answers2

0

Have you tried injecting the script element into the head of the document?

I am not to sure about script tags, but you must inject link and style elements into the head of a document for it to be interpreted correctly by older IE browsers.

var script = document.createElement('script');
script.type = 'text/javascript';
script.rel = 'JavaScript';
script.innerHTML = 'document.write("<a href=\"http://www.example.com\" target=\"_blank\">bla</a>");';

var el = document.getElementById('iframeName');
iframeDoc = el.contentWindow.document;
iframeDoc.head.appendChild(script);
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
0

The solution I went with is:

el = document.getElementById('iframeName');
iframeDoc = el.contentWindow.document;
iframeDoc.write(content);

it's a lot shorter and is cross-browser (instead of using innerHTML).

Yuval
  • 307
  • 3
  • 14