【问题标题】:JS: Unable to get window.parent to use postMessageJS:无法让 window.parent 使用 postMessage
【发布时间】:2015-01-16 15:13:45
【问题描述】:

所以我一直在关注许多关于使用 window.postMessage() 在容器 window 及其 iframe 内容 window 之间进行通信的教程。

但是,我遇到了无法定位收件人的window 的问题,我可以调用postMessage(),或者更确切地说,我获得的对象是空的。这里有一些解释,大家可以看Github repo中的代码关注我。

我有两个项目,iframe-contentiframe-container,它们完全符合您的预期。这些项目中的每一个都需要以window 对象为目标才能调用window.postMessage()

在容器的情况下,运行这段代码

var childWindow = document.getElementById('iframeContent').contentWindow
console.log('childWindow: ', childWindow);

不会导致错误,但返回的window 对象没有任何属性。 See the code.

同样,在<iframe> 内容中执行此操作

var parentWindow = $window.parent;
console.log('parentWindow: ', parentWindow);

与关于容器的解释相同。 See the code.

查看我的意思是空的window 对象的屏幕截图:

在这两种情况下,调用postMessage() 函数都不会返回错误,但实际上会失败。

我可能忽略了什么?我应该调查什么?感谢任何指导,谢谢。

【问题讨论】:

  • document.getElementById('iframeContent').contentWindow.postMessage 返回什么(不调用括号!)?在 Firefox 中显示某些属性时,Chrome 中的 window 对象似乎始终为空。
  • @RainerRillke:我依靠您的评论并检查了 FF 和 Safari,但我忘了这样做。 FF 没问题,就像你说的,Saf 抱怨安全问题。也许提供有关另一个窗口的信息是不安全的事情,所以 Chrome 没有显示错误,但没有内容?我检查了postMessage 没有括号,它显示function () { [native code] }。我添加了一些日志记录,现在它工作正常。我一定误解了我的调试。谢谢!
  • 随意回答您自己的问题

标签: javascript angularjs iframe postmessage


【解决方案1】:

听起来您可能正在尝试访问跨域 iframe。确保使用正确的来源和事件侦听器设置 api。

https://developer.mozilla.org/en-US/docs/Web/API/Window.postMessage

记住 iframe 需要一个消息监听器

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

function receiveMessage(event)
{
  if (event.origin !== "http://example.org:8080")
    return;

  // ...
}

【讨论】:

猜你喜欢
  • 2012-01-08
  • 2018-12-29
  • 1970-01-01
  • 2020-11-29
  • 1970-01-01
  • 2012-07-04
  • 1970-01-01
  • 2014-09-02
  • 2016-08-20
相关资源
最近更新 更多