【问题标题】:Issue communication with postMessage from parent to child iFrame从父到子 iFrame 发出与 postMessage 的通信
【发布时间】:2017-04-20 20:11:29
【问题描述】:

我在从父窗口与子 iFrame 通信时遇到问题。但另一方面,一切都很完美。 以下是我获取 chil iFrame 对象以触发 postMessage 函数的方法:

var iFrame = document.getElementById('Frame').contentWindow;

当我在控制台中打印它时,我得到以下信息:

Window {parent: Window, opener: null, top: Window, length: 0, frames: Window…}

当我进行 postMessage 功能如下:

iFrame.postMessage("message", "http://contoso.com");

加载页面时显示错误:iFrame.postMessage 不是函数。 当我在控制台中执行 postMessage 时,我得到一个 undefined

我做错了什么?

【问题讨论】:

  • 您仍然需要控制这两个网站。你拥有contoso.com吗?
  • 您需要在contoso.com 上设置e.origin,您确定可以编辑该站点吗?上次我检查时,MS 仍然拥有它。
  • 我已将我的网站替换为 contoso.com,只是为了发帖。在子 iFrame 的事件侦听器中,e.origin 设置正确。我在操作事件对象之前添加了日志,但它从来没有达到这一点。
  • 也许这个答案可能会有所帮助。

标签: javascript iframe postmessage


【解决方案1】:

我无法使用 querySelector 方法来完成这项工作。

对我有用的是以下内容。我将这两个网页称为parent,上面有一个 iframe,src 称为 iframe 内的页面。

src页面上,我发了一条消息,以parent url为来源:

// src
window.parent.postMessage({
  type: "connect",
  url: window.location.href
}, "http://iframeparent.dev", );

然后在parent 页面中,我听听这个。它将有一个名为source 的属性,这是有问题的 iframe。此属性可以发布到

// parent
window.addEventListener("message", (event) => {
  // this is the magic connection:
  event.source; 
}, false);

所以你可以这样做:

// parent
let sources = [];

window.addEventListener("message", (event) => {
  sources.push(event.source);
}, false);

function something() {
  sources.forEach(source => {
    source.postMessage({some: "data"}, "http://iframesrc.dev")
  })
}

【讨论】:

    【解决方案2】:

    下面的代码也可以。

    $('#id')[0].contentWindow.postMessage("hello world",targetOrigin);

    jQuery 选择器和 document.getElementById 是有区别的。

    Document.getElementByID 返回 HTML DOM 对象。
    jQuery 选择器返回 jQuery 对象。

    欲了解更多信息,请查看以下链接。 document.getElementById vs jQuery $()

    【讨论】:

      【解决方案3】:

      试试这个

      var iFrame = document.getElementById('Frame');
      iFrame.contentWindow.postMessage("message", "http://contoso.com");
      

      我也有这个问题。我从这个网站找到了解决方案https://www.viget.com/articles/using-javascript-postmessage-to-talk-to-iframes

      【讨论】:

      • 错误:Failed to execute 'postMessage' on 'DOMWindow': The target origin provided does not match the recipient window's origin. 它可以从子元素到父元素,但不能反过来。
      • @temo 我能够让它跨域工作,请参阅下面的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-05-16
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2012-02-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多