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

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

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


当前回答

如果你想从另一个函数生成的iframe中调用父节点上的JavaScript函数,例如shadowbox或lightbox。

你应该尝试使用窗口对象和调用父函数:

window.parent.targetFunction();

其他回答

这里有一些需要注意的怪癖。

HTMLIFrameElement.contentWindow is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the window object. You can also try HTMLIFrameElement.contentDocument.defaultView, which a couple of older browsers allow but IE doesn't. Even so, the standard doesn't explicitly say that you get the window object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care. window.frames['name'] returning the window is the oldest and hence most reliable interface. But you then have to use a name="..." attribute to be able to get a frame by name, which is slightly ugly/deprecated/transitional. (id="..." would be better but IE doesn't like that.) window.frames[number] is also very reliable, but knowing the right index is the trick. You can get away with this eg. if you know you only have the one iframe on the page. It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its window.parent script when it has finished loaded and is ready to be called back. By passing one of its own objects (eg. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with.

其中一些答案并没有解决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','*')

使用following调用父页中帧的函数

parent.document.getElementById('frameid').contentWindow.somefunction()

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

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

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

如果你想从另一个函数生成的iframe中调用父节点上的JavaScript函数,例如shadowbox或lightbox。

你应该尝试使用窗口对象和调用父函数:

window.parent.targetFunction();