简体   繁体   中英

Javascript - Passing a script to innerHTML on older browsers

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-?

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);

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM