如何使用 jQuery 将 JavaScript 代码添加到现有 iFrame 中?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18369410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add JavaScript code into existing iFrame using jQuery?
提问by Gandalf
I want to add a JavaScript snippet into an existing iFrame in the page using jQuery. I have the following code...
我想使用 jQuery 将 JavaScript 片段添加到页面中的现有 iFrame 中。我有以下代码...
Code:
代码:
content = "<script>" + js_code + "</script>";
$('#iframe_id').contents().find('body').append(content);
But somehow this is not working. I checked some of the existing/related answers, and it seems jQuery does not quite recognize the script tags as...script tags. The iFrame is in the same domain/same port/same host, so there is no issue about cross-site scripting etc. How can I fix this?
但不知何故,这是行不通的。我检查了一些现有/相关的答案,似乎 jQuery 并没有完全将脚本标签识别为...脚本标签。iFrame 在同一个域/同一个端口/同一个主机中,所以没有跨站点脚本等问题。我该如何解决这个问题?
回答by Juan Mendes
The problem is that the HTML parser gets confused if your script contains the closing script tag in it (</script>
) and it closes the script tag prematurely.
问题在于,如果您的脚本中包含结束脚本标记 ( </script>
) 并且过早地关闭脚本标记,则 HTML 解析器会感到困惑。
The solution is to escape the /
in "<\/script>"
. This works because strings in JavaScript, (and some other languages), any invalid escape sequencesare just ignored, so "\l"
is treated as "l"
, and "\/"
is treated as "/"
. The HTML parser, however, doesn't use a backslash to escape them so it doesn't get confused (credits to https://stackoverflow.com/users/405681/keaukraine).
解决方案是逃避/
in "<\/script>"
。这是有效的,因为 JavaScript 中的字符串(和一些其他语言),任何无效的转义序列都会被忽略,因此"\l"
被视为"l"
,并被"\/"
视为"/"
。但是,HTML 解析器不使用反斜杠来转义它们,因此不会混淆(归功于https://stackoverflow.com/users/405681/keaukraine)。
var scriptTag = "<script>alert(1)<\/script>";
$("#iframe").contents().find("body").append(scriptTag);
Original solution
原解决方案
Break up that closing tag so you don't mess up the HTML parser. The other solutions on this page work because they never have the string </script>
in their code
分解该结束标记,以免弄乱 HTML 解析器。此页面上的其他解决方案有效,因为它们</script>
的代码中从未包含字符串
var scriptTag = "<script>alert(1)<";
scriptTag += "/script>";
console.log(scriptTag);
$("#iframe").contents().find("body").append(scriptTag);
回答by Dan B
function putScriptInIframes(script, scriptId) {
var $iframes = $('iframe');
$iframes.each(function () {
var thisDoc = this.contentWindow.document;
if ( ! thisDoc.getElementById(scriptID)) {
var scriptObj = thisDoc.createElement("script");
scriptObj.type = "text/javascript";
scriptObj.id = scriptId;
scriptObj.innerHTML = script;
thisDoc.body.appendChild(scriptObj);
}
});
}
This was the simplest way I could make it work.
这是我可以让它工作的最简单的方法。
回答by Neil S
回答by Bruno Braga
You need to escape the /script
.
It apears.
你需要逃离/script
. 它出现。
Do like google analitcs for instance
例如,喜欢谷歌分析
$("#iframe").contents().find("body").append(decodeURI("**%3Cscript%3E** alert(2) **%3C/script%3E**"));
replace the script
and /script
with this escaped ones
用这个转义的替换script
和/script
Hope it helps.
希望能帮助到你。
回答by ced-b
As the iframe runs as it's own window
, you will have to also inject the import of the jquery.js file.
由于 iframe 以它自己的方式运行window
,您还必须注入 jquery.js 文件的导入。
<script type="text/javascript" src="/jquery/jquery-ui-1.9.1.custom.js"></script>
EDIT:So I played with this a bit more and here is what I came up with.
编辑:所以我玩了更多,这就是我想出的。
HTML
HTML
<iframe id="frame"></iframe>
JS
JS
$("#frame").attr(
"src", "data:text/html;charset=utf-8," +
"<html>" +
"<style>.red {color: red}</style>" +
"<div class=\"test\">Test</test>" +
"<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"><" + "/script>" +
"<script>$(function(){ $(\".test\").addClass(\"red\")});<" + "/script>" +
"</html>"
);
This works, see here http://jsfiddle.net/WsCxj/.
这有效,请参见此处http://jsfiddle.net/WsCxj/。
So there are several points:
所以有几点:
I am passing the entire content as one string. You have to prepend
data:text/html;charset=utf-8,
and then you can set your string as src of the iframe.I am adding the jquery.js file with an absolute path- This seems to be important, presumably because the frame has no path by itself as it's content is dynamically generated.
I split the script end tag like this
<" + "/script>
because at least firefox tries to end the actual script at this point. The cleaner approach would probably be to have the js as totally separate file.
我将整个内容作为一个字符串传递。您必须预先添加
data:text/html;charset=utf-8,
,然后才能将字符串设置为 iframe 的 src。我正在添加带有绝对路径的 jquery.js 文件- 这似乎很重要,大概是因为框架本身没有路径,因为它的内容是动态生成的。
我像这样拆分脚本结束标记,
<" + "/script>
因为至少 Firefox 会在此时尝试结束实际脚本。更简洁的方法可能是将 js 作为完全独立的文件。
回答by Luan Castro
You don't need add a tag script to execute javascript, you can do a function and apply iframe context...
您不需要添加标签脚本来执行 javascript,您可以执行一个函数并应用 iframe 上下文...
using eval
使用评估
function initFrame (code){
eval (code);
}
initFrame.apply ($('#iframe').contents(),[js_code]);
Without eval
没有评估
var initFrame = new Function(js_code);
initFrame.apply ($('#iframe').contents(),[]);
回答by Den Pat
This worked for me, paste following code in the page which is in an iframe, not the parent page:
这对我有用,将以下代码粘贴到 iframe 中的页面中,而不是父页面中:
window.myFunction = function(args) {
alert("script from iframe");
}
And now add following code to call above function:
现在添加以下代码来调用上面的函数:
var iframe = document.getElementById("iframeId");
iframe.contentWindow.myFunction(args);
回答by PiotrC
How about setting ajax refresh with js interval function to take any data stored in file/session etc. ?
如何使用js间隔函数设置ajax刷新以获取存储在文件/会话等中的任何数据?
It's surely not the most lightweight mode and it involves a tiny bit php, but can do the work.
它肯定不是最轻量级的模式,它涉及一点点 php,但可以完成这项工作。