PDA

View Full Version : Injecting javascript into iframe head


chatko
10-20-2009, 03:27 AM
Hi guys,

I'm trying to inject javascript into a dynamically created iframe's <head> element. My approach works in IE8, firefox 3+ and Chrome. It breaks IE7 with a "htmlfile: invalid argument." message. I use the following function:
(where, element is my iframe, url is the script url and mytype= "text/javascript"



function InjectScript(element, url, callback, myType){

var headID = element.doc.getElementsByTagName("head")[0];
if (!headID) { return; }

var script = document.createElement('script');
script.type = myType;
script.src = url;

if (script.readyState){ //IE
script.onreadystatechange = function(){
if (script.readyState == "loaded" ||
script.readyState == "complete"){
script.onreadystatechange = null;
callback();
}
};
} else {
script.onload = function ()
{ // FireFox
callback();
}
}

headID.appendChild(script);

}


In the microsoft debugger, I can see that the error occurs on "headID.appendChild(script);". Both the HeadID and script elements look good in the debugger. I can also alert their respective properties at runtime before the call to appendChild.

Any ideas why this fails in IE7 and whatI can do to fix?


Thanks,

Chris

glenngv
10-21-2009, 12:45 AM
IE7 doesn't like you directly manipulate the DOM of one page from another page. Can you move the InjectScript in the iframe page and then call it from the main page? Of course, you need to change the head reference to simply document.getElementsByTagName('head')[0];

glenngv
10-21-2009, 01:01 AM
Ok, I got it to work without moving the function in the iframe. You need to create the script element in the iframe window not in the main window.

If you are passing document.getElementById(iframeId) to the element parameter, you need the script to be like this.

var headID = element.contentWindow.document.getElementsByTagName("head")[0];
if (!headID) { return; }

var script = element.contentWindow.document.createElement('script');

If you are passing it as window.frames[iframeName], you need to do it this way.
var headID = element.document.getElementsByTagName("head")[0];
if (!headID) { return; }

var script = element.document.createElement('script');

chatko
10-21-2009, 02:20 AM
Your right, I actually came to the same conclusion today at work and its running great. Thanks again for your time and help.

Chris