How can I load <script> in an iframe?

I have logic to add to my iframe from parent

it works:

$('#iframe').load(function() { $(this).contents().find('#target').append('this text has been inserted into the iframe by jquery'); }); 

is not

 $('#iframe').load(function() { $(this).contents().find('body').append('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>'); }); 

.Lf

The problem is that the inserted script tags are not executing properly. Half of javascript becomes visible in html since the first script tag was suddenly terminated.

+7
javascript jquery iframe
source share
3 answers

Perhaps the error is related to your string, never create a string in javascript with the literal </script> .

 $('#iframe').load(function() { $(this).contents().find('body').append('<scr' + 'ipt type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></scr' + 'ipt>'); }); 
+9
source share

I am a little surprised that does not work. [Edit: Don't be surprised anymore, see mtrovo's answer .] ... but here's what I do, which is basically non-jQuery for your comment below, but still pretty concise:

 var rawframe = document.getElementById('theframe'); var framedoc = rawframe.contentDocument; if (!framedoc && rawframe.contentWindow) { framedoc = rawframe.contentWindow.document; } var script = doc.createElement('script'); script.type = "text/javascript"; script.src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"; framedoc.body.appendChild(script); 

Off topic: I really didn't provide an iframe (or anything else) iframe id. It just looks like it is causing problems (IE has problems with the namespace, and although I don't know that the names and tag identifiers are confused, I would not be completely shocked). Instead, I used a frame.

+7
source share

Warning: loading the script this way will make the scripts work in the context of the main window ie: If you use a window from somescript.js, it will NOT be an iframe window!

 $('#iframe').load(function() { $(this).contents().find('body').append('<scr' + 'ipt type="text/javascript" src="somescript.js"></scr' + 'ipt>'); }); 

To use an iframe context, insert the script as follows:

 function insertScript(doc, target, src, callback) { var s = doc.createElement("script"); s.type = "text/javascript"; if(callback) { if (s.readyState){ //IE s.onreadystatechange = function(){ if (s.readyState == "loaded" || s.readyState == "complete"){ s.onreadystatechange = null; callback(); } }; } else { //Others s.onload = function(){ callback(); }; } } s.src = src; target.appendChild(s); } var elFrame = document.getElementById('#iframe'); $(elFrame).load(function(){ var context = this.contentDocument; var frameHead = context.getElementsByTagName('head').item(0); insertScript(context, frameHead, '/js/somescript.js'); } 
+4
source share

All Articles