将外部js注入自己创建的iframe [英] injecting external js into self created iframe
问题描述
所以我试图将外部css和js注入自创的iframe以提供额外的安全层,因此没有跨域问题。
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.
这里是代码
<!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>
正在输入css文件但是没有js文件,有人能看出原因吗? console.log正在输出。
the css file is being inputted but neither of the js files are, can anyone see why? the console.log is outputting.
谢谢
推荐答案
我认为你必须从iframe的文档对象创建脚本元素。它应该以 contents [0]
的形式提供,您可以将其传递给insertScript。
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.
它如果您直接在头节点(而不是jQuery包装器)上使用 appendChild
,则有效:
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
这篇关于将外部js注入自己创建的iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!