基本上,我在页面中嵌入了一个iframe,该iframe有一些需要从父页面调用的JavaScript例程。

现在相反的是相当简单,因为你只需要调用parent.functionName(),但不幸的是,我需要的恰恰相反。

请注意,我的问题不是改变iframe的源URL,而是调用iframe中定义的函数。


当前回答

其中一些答案并没有解决CORS问题,或者没有明确地说明您将代码段放置在何处以使通信成为可能。

这里有一个具体的例子。假设我想点击父页面上的一个按钮,并让它在iframe中做一些事情。我是这么做的。

parent_frame.html

<button id='parent_page_button' onclick='call_button_inside_frame()'></button>

function call_button_inside_frame() {
   document.getElementById('my_iframe').contentWindow.postMessage('foo','*');
}

iframe_page.html

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event)
    {
      if(event) {
        click_button_inside_frame();
    }
}

function click_button_inside_frame() {
   document.getElementById('frame_button').click();
}

要走另一个方向(点击iframe内的按钮调用iframe外的方法),只需切换代码片段所在的位置,并更改如下:

document.getElementById('my_iframe').contentWindow.postMessage('foo','*');

:

window.parent.postMessage('foo','*')

其他回答

在IFRAME中,让你的函数对窗口对象是公共的:

window.myFunction = function(args) {
   doStuff();
}

从父页面访问,使用这个:

var iframe = document.getElementById("iframeId");
iframe.contentWindow.myFunction(args);

为了记录,我今天遇到了同样的问题,但这次页面嵌入在对象中,而不是iframe(因为它是XHTML 1.1文档)。下面是它如何处理对象:

document
  .getElementById('targetFrame')
  .contentDocument
  .defaultView
  .targetFunction();

(对不起,很难看的换行,不适合单行)

IFRAME应该在frames[]集合中。使用像这样的东西

frames['iframeid'].method();

我找到了一个很好的解决办法。

正如您所说,执行位于父文档中的代码相当容易。这是我代码的基础,做的正好相反。

当我的iframe加载时,我调用父文档上的一个函数,将一个引用作为参数传递给位于iframe文档中的一个局部函数。 父文档现在可以通过这个引用直接访问iframe的函数。

例子:

在父节点上:

function tunnel(fn) {
    fn();
}

在iframe中:

var myFunction = function() {
    alert("This work!");
}

parent.tunnel(myFunction);

当iframe加载时,它将调用parent.tunnel(YourFunctionReference),它将执行parameter中接收到的函数。

这很简单,不需要处理来自各种浏览器的所有非标准方法。

下面是Nitin Bansal的回答

为了更健壮:

function getIframeWindow(iframe_object) {
  var doc;

  if (iframe_object.contentWindow) {
    return iframe_object.contentWindow;
  }

  if (iframe_object.window) {
    return iframe_object.window;
  } 

  if (!doc && iframe_object.contentDocument) {
    doc = iframe_object.contentDocument;
  } 

  if (!doc && iframe_object.document) {
    doc = iframe_object.document;
  }

  if (doc && doc.defaultView) {
   return doc.defaultView;
  }

  if (doc && doc.parentWindow) {
    return doc.parentWindow;
  }

  return undefined;
}

and

...
var el = document.getElementById('targetFrame');

var frame_win = getIframeWindow(el);

if (frame_win) {
  frame_win.targetFunction();
  ...
}
...