在动态创建的iframe中触发Javascript

Wac*_*ock 3 javascript iframe jquery google-chrome google-chrome-extension

我正在构建一个chrome扩展程序,只要用户点击我的Chrome扩展程序的按钮,我就可以使用Iframe弹出窗口.

在我的iFrame里面,我正在加载2个.js文件:来自chrome扩展的jQuery和"modal.js".执行检查我可以看到文件已加载(modal.js),但是我使用的是以下代码,但未触发:

  $('#frameID').ready(function(){
    $('#sbm-new-group').click(function(){
      console.log("hello");
     });
  });
Run Code Online (Sandbox Code Playgroud)

这不起作用,即使我尝试使用$(document).ready,也没有任何事情发生.我想知道是否还有使用iFrame中的javascript触发方法.

任何帮助都非常感谢.

Onu*_*rım 7

您应该访问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');
    });
});
Run Code Online (Sandbox Code Playgroud)

[编辑] 额外备注:

  • 要从所有者全局范围调用函数,请从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();
Run Code Online (Sandbox Code Playgroud)

这是展示这一个的另一个小提琴.