在动态创建的iframe中触发JavaScript

3
我正在构建一个Chrome扩展程序,其中我已成功使用Iframe制作了一个弹出窗口,当用户单击我的Chrome扩展程序的按钮时,该窗口会出现。
在我的Iframe中,我加载了2个.js文件:jQuery和来自Chrome扩展程序的“modal.js”。 检查后我可以看到文件已被加载(modal.js),但是我使用下面的代码时却没有触发:
  $('#frameID').ready(function(){
    $('#sbm-new-group').click(function(){
      console.log("hello");
     });
  });

这并没有起作用,即使我尝试使用$(document).ready,也没有任何反应。我想知道是否有办法通过iFrame内部的JavaScript来触发该方法。

非常感谢您的帮助。


没有足够的信息来诊断问题。#sbm-modal是什么? - Xan
我已经编辑过了,这是iFrame的ID。 - Waclock
你是在使用内容脚本注入到浏览器页面本身中,还是在使用标准的Chrome browser_action:default_popup定义? - Abe Hendlish
2
请记住,<iframe> 包含了自己独立的 #document 和 _Window_,要访问其中的内容,您需要通过 ifrm.contentWindow 等方式进行访问。 - Paul S.
也许这可以帮助:https://dev59.com/hHVC5IYBdhLWcg3wtzkQ - source.rar
显示剩余6条评论
1个回答

7

要绑定.ready()处理程序,您需要访问iframe的document
这里有一个演示fiddle

注意:如果您在同一域上,则可以实现此操作。

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文档中调用一个位于owner全局范围内的函数:

    parent.someMethod();

  • owner文档中调用一个位于iframe全局范围内的函数:

    iframeWin.someMethod();

  • owner文档中执行在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();

这里有另一个演示此功能的fiddle(JSFiddle)


1
警告:当请求来自另一个域时,您无法执行此操作。 - mattdlockyer
问题:我如何触发类似于$(document).keyup事件的东西? - Waclock
你可以按照示例中展示的方式进行操作:$(iframeDoc).on('keyup', function (event) { console.log(event.keyCode); }); - Onur Yıldırım
这是最“干净”的方法吗?我试图避免使用$(iframeDoc).find...来绑定事件,认为可能有更清晰的方法。 - Waclock
从所有者文档中,如果你想要 (a) 知道 iframe 文档何时准备好了;(b) 从所有者文档操作 iframe DOM;-- 这就是做法。我在答案中添加了一些额外的注释,关于执行脚本/调用函数。 - Onur Yıldırım

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接