使用postmessage报错,Failed to execute 'postMessage' on 'DOMWindow'

使用postMessage发送跨域消息,
window.postMessage('hello there!', location.protocol + '//a.b.com');

但是报了下面的错误:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://a.b.com') does not match the recipient window's origin ('http://c.e.com')

请问是什么原因?

阅读 26k
2 个回答

使用event.source作为回信对象
具体参见:https://developer.mozilla.org...

//当A页面postMessage被调用后,这个function被addEventListenner调用
function receiveMessage(event)
{
  // 我们能信任信息来源吗?
  if (event.origin !== "http://example.com:8080")
    return;

  // event.source 就当前弹出页的来源页面
  // event.data 是 "hello there!"

  // 假设你已经验证了所受到信息的origin (任何时候你都应该这样做), 一个很方便的方式就是把enent.source
  // 作为回信的对象,并且把event.origin作为targetOrigin
  event.source.postMessage("hi there yourself!  the secret response " +
                           "is: rheeeeet!",
                           event.origin);
}

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

otherWindow.postMessage(message, targetOrigin, [transfer]);
otherWindow:其他窗口的一个引用,比如iframe的contentWindow属性、执行window.open返回的窗口对象、或者是命名过或数值索引的window.frames。
otherWindow不能是当前窗口哦
参见MDN

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题