我目前正在构建一个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以绑定(bind).ready()处理程序。
这是一个demo 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文档的全局范围所有者全局范围中调用函数:
    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();
    

    这是another fiddle演示的。

    07-24 18:02
    查看更多