【问题标题】:Why does my cross-domain postMessage only work when passing "*" as origin parameter?为什么我的跨域 postMessage 仅在将“*”作为原始参数传递时才有效?
【发布时间】:2013-05-29 17:21:39
【问题描述】:

我正在使用 2 个本地域,localhostdomain1,以使用来自两个域的 iFrame 测试 postMessaging 系统。

我可以正确识别各自的window 元素(在两个域上)以发送消息和接收回复。我的问题是,在我的 postMessage 中发送的第二个参数(我从中发送消息的 URL)未被相应其他域上的侦听器接受。仅当我声明发件人为 "*" 时,我的消息传递才有效。

这不起作用向外部域发送消息:

 // targetWindow = window of foreign domain
 targetWindow.postMessage({
    "foo": "bar"
  }, window.location.href);

这行得通:

 // targetWindow = window of foreign domain
 targetWindow.postMessage({
    "foo": "bar"
  }, "*");

回复发送域也是如此(使用window.top)。这不起作用:

 window.top.postMessage({
  "baz": "bam"
}, window.location.href.split("?")[0]);

虽然这样做:

window.top.postMessage({
  "baz": "bam"
}, "*");

问题:
为什么会这样?我想我必须提供 sending-url 作为第二个参数来启用身份验证。如果是这样,为什么我的事件没有触发?是我在 localhost/domain1 上工作的原因吗?

感谢您的帮助!

【问题讨论】:

  • 如果他们在不同的域上,你为什么会期望 window.location.href 在另一个域上匹配?
  • 它不应该匹配(我猜)。我认为第二个参数应该是发送 postMessage 的 URL,以便接收窗口可以验证发件人。如果我记录window.location.href...,它会正确返回http://domain1/foo/some/file.html,我想将它与postMessage一起传递,所以我可以验证它。但是这样做时, postMessage 永远不会在没有弹出任何错误的情况下发送。只有当我使用"*" 时它才有效。
  • 我以为您传递的是域,而不是路径...
  • 是吗? Mozilla's targetOrigin 说应该是一个URI,也就是……
  • @frequent 那么你应该阅读更多关于它的信息:developer.mozilla.org/en-US/docs/Web/API/…。第二个参数用于指定要将消息广播到的域/端口

标签: javascript url iframe cross-domain postmessage


【解决方案1】:

第二个婴儿车是targetOrigin,这是一个安全限制,可以阻止你的消息被拦截。它应该设置为消息发送到的窗口域,而不是消息来自的域。

这是一个使用 iframe 设置第二个字段的示例,它从 iFrame 中获取 src 值并将其分解为协议 + 域 + 端口。这是设置目标原点所需要的。

var target = iframe.src.split('/').slice(0,3).join('/');
iframe.contentWindow.postMessage('foo', target);

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 2022-10-26
    • 2023-03-23
    • 2018-09-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-31
    • 1970-01-01
    • 2023-02-24
    相关资源
    最近更新 更多