[英]Triggering Javascript inside dynamically created iframe
我正在构建一个chrome扩展程序,只要用户点击我的Chrome扩展程序的按钮,我就可以使用Iframe弹出窗口。
在我的iFrame里面,我正在加载2个.js文件:来自chrome扩展的jQuery和“modal.js”。 执行检查我可以看到文件已加载(modal.js),但是我使用的是以下代码,但未触发:
$('#frameID').ready(function(){
$('#sbm-new-group').click(function(){
console.log("hello");
});
});
这不起作用,即使我尝试使用$(document).ready,也没有任何事情发生。 我想知道是否还有使用iFrame中的javascript触发方法。
任何帮助都非常感谢。
您应该访问iframe的document
以绑定.ready()
处理程序。
这是一个演示小提琴 。
注意: 如果您在同一个域中,则可以执行此操作。
var iframe = document.getElementById('frameID'),
iframeWin = iframe.contentWindow || iframe,
iframeDoc = iframe.contentDocument || iframeWin.document;
$(iframeDoc).ready(function (event) {
alert('iframe ready');
// now you can access any element in the iframe (if same domain)
$(iframeDoc).find('#sbm-new-group').on('click', function (event) {
alert('clicked');
});
});
[编辑] 额外备注:
要从所有者全局范围调用函数,请从iframe文档中调用:
parent.someMethod();
要从所有者文档中调用iframe全局范围中的函数,请执行以下操作:
iframeWin.someMethod();
要从所有者文档中执行iframe中的脚本:
// this is called from the iframe
window.hello = function () {
alert('hello from owner!');
};
// we'll write some scripts within the iframe that will be executed immediately
iframeDoc.open();
iframeDoc.write('\<script>alert("hello from iframe!");\<\/script>');
iframeDoc.write('\<script>parent.hello();\<\/script>');
iframeDoc.close();
这是展示这一个的另一个小提琴 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.