如何做跨域postMessage? [英] How can I do cross-domain postMessage?

查看:126
本文介绍了如何做跨域postMessage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

postMessage 的文档意味着可以使用跨域消息传递。但是:

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

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

这不是一个非常清楚的如何实现。

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

想象两个网站:


  1. [Parent]托管在 qc-a.nfshost .com

  2. [Child]托管在 qc-b.quadhome.com

  1. [Parent] hosted on qc-a.nfshost.com
  2. [Child] hosted on qc-b.quadhome.com

在父级中:

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');
}

并且,在子级:

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

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

全部无效。

推荐答案

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

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

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

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 postMessage page.

2)使用超时,可以将子窗口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.

这篇关于如何做跨域postMessage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆