javascript 如何进行跨域postMessage?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3332532/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 00:52:22  来源:igfitidea点击:

How can I do cross-domain postMessage?

javascripthtmlcross-domainpostmessage

提问by Scott Robinson

The documentation for postMessageimplies that cross-domain messaging is possible. However:

postMessage的文档暗示跨域消息传递是可能的。然而:

// When the popup has fully loaded, if not blocked by a popup blocker

That isn't a very clear note of howto actually do it.

这不是一个非常清楚的说明如何实际做到这一点。

Imagine two websites:

想象两个网站:

  1. [Parent] hosted on qc-a.nfshost.com
  2. [Child] hosted on qc-b.quadhome.com
  1. [父] 托管于 qc-a.nfshost.com
  2. [子] 托管于 qc-b.quadhome.com

In the parent:

在父级中:

document.addEventListener('message', function(e) {
  alert('Parent got (from ' + e.origin + '): ' + e.data);

  e.source.postMessage('Round-tripped!', 'http://qc-b.quadhome.com');
}, false);

function go() {
  var w = window.open('http://qc-b.quadhome.com', 'test');

  /* This doesn't work because same-origin policy prevents knowing when
     the opened window is ready. */

  w.postMessage('Vain attempt.', 'http://qc-b.quadhome.com');
}

And, in the child:

而且,在孩子身上:

document.addEventListener('message', function(e) {
  alert('Child got (from ' + e.origin + '): ' + e.data);
}, false);

window.opener.postMessage('Ready!', 'http://qc-a.nfshost.com');

All to no avail.

一切都无济于事。

Help?

帮助?

采纳答案by Anh-Kiet Ngo

Currently, I am seeing two issues. Slight error in the code and the timeout issue.

目前,我看到两个问题。代码中的轻微错误和超时问题。

1) The error I am seeing in your code is that you're using document.addEventListener. I think the right one is window.addEventListener. It is in the example on the postMessagepage.

1) 我在您的代码中看到的错误是您正在使用 document.addEventListener。我认为正确的是 window.addEventListener。它在postMessage页面上的示例中。

2) With the timeout, you can have the child window postMessage to the parent. The parent window will then know when the child is ready.

2) 超时后,您可以将子窗口 postMessage 发送给父窗口。然后父窗口将知道子窗口何时准备就绪。

回答by Ben Rowe

You're opening the window & posting the message after each other. There's no way the open document will be ready to accept the post message. Try delaying the postMessage call until the window has finished loading.

您正在打开窗口并依次发布消息。打开的文档无法准备好接受发布消息。尝试延迟 postMessage 调用,直到窗口完成加载。

A very simple way to test this is to wrap w.postMessage() in a setTimeout (for 10 seconds) and see if it can post it when the document is ready.

一个非常简单的测试方法是将 w.postMessage() 包装在 setTimeout 中(10 秒),看看它是否可以在文档准备好时发布它。