injecting external js into self created iframe

2019-03-03 08:38发布

问题:

So i am trying to inject and external css and js into a self created iframe to provide an extra security layer, there therefore is no cross domain issues.

here is the code

<!doctype html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>

<script>
$(function(){

var contents = $('iframe').contents();

styleTag = $('<link href="http://mylink.com/styles.css" media="all" rel="stylesheet" type="text/css" />').appendTo(contents.find('head'));

insertScript('https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js');
insertScript('https://myserver.com/myfile.js');

});

var insertScript = function(src){
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = src;
$('iframe').contents().find('head').append(script);
console.log("add script");
}

</script>

<div class="output">
<iframe></iframe>
</div>

the css file is being inputted but neither of the js files are, can anyone see why? the console.log is outputting.

thanks

回答1:

I think you have to create the script element from the iframe's document object. It should be available as contents[0], which you can pass to insertScript.

It works if you use appendChild directly on your head node (not the jQuery wrapper):

$('iframe').contents().find('head')[0].appendChild(script);

http://jsbin.com/enidiv/1/edit



回答2:

As long as the iframe domain, protocol, and port matches you can add scripts. Otherwise, it is treated as an unsafe attempt to access a different url.