【问题标题】:How to access nested iframes?如何访问嵌套的 iframe?
【发布时间】:2021-01-22 12:00:52
【问题描述】:

我需要发送消息 (window.postmessage) 到 iframe。
如果我在父页面中有单个 iframe,目前它可以工作。但我想让它适用于嵌套的 iframe。
标准是:

  • 我可以在最后一个叶子 iframe 中添加侦听器代码。
  • 不知道 iframe 嵌套的长度。
  • 需要双向通信,从父级到子级也需要通过叶子 iframe 到父级。

我厌倦了第三方 iframe,请给我一些合适的解决方案。

【问题讨论】:

标签: javascript jquery html dom


【解决方案1】:

很老的问题,但是,我有一个类似的问题,我想出了一个解决方案。将来可能会对其他人有所帮助。

我们始终可以使用.parent.frames[i][j][k] 在两个方向嵌套iframe 中的postMessage 任何iframe

例如,如果您想在第三个iframe 中向第一个iframe 发布消息,您可以这样做:

window.frames[2][0].postMessage(msg, "*");

https://javascript.info/cross-window-communication查看更多信息

对于 iframe,我们可以使用以下方式访问父/子窗口:

  • window.frames – 嵌套窗口对象的集合,
  • window.parent、window.top 是对父窗口和顶层窗口的引用,
  • iframe.contentWindow 是标签内的窗口。

postMessage 接口允许窗口相互交谈,无论它们来自哪个来源。所以,这是绕开“同源”政策的一种方式。查看更多信息here

【讨论】:

  • 是的,@DavidBradshaw。 postMessage 是跨域通信的方式。在我上面的回答中从参考中添加一行。
  • 我的意思是像那样走帧 (frames[0][2])
  • 是的,索引/访问可以跨域工作,但是如果来源不同,可以用它做的事情是有限的
【解决方案2】:

您可以自己实现一个向上或向下传播事件的事件系统。

在所有 iframe 中添加类似的内容将向下传播事件。

//create a jquery object to use the bind/trigger event system
var vent = $({});

function trigger(event, args) {
    //trigger for the current iframe
    vent.trigger(event, args);

    //propagate down for all nested iframes
    $.each(getAllIframes(), function(i, iframe) {
        iframe.trigger(event, args);
    });
}

function bind(event, callback) {
    vent.bind(event, callback);
}

function getAllIframes() {
    return $("iframe").map(function(){
      return this.contentWindow;
    });
}

您可以以类似的方式实现事件冒泡,但必须具有某种绑定到所有子框架的初始化逻辑。

【讨论】:

  • 我猜你的方法对于获取同一页面中的所有帧很有用。我需要知道一个帧内的帧数。
猜你喜欢
  • 1970-01-01
  • 2021-01-24
  • 2010-10-29
  • 2019-09-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-10
相关资源
最近更新 更多