28

我不知道该怎么办。我尝试了来自不同来源的几个示例代码,我在不同的浏览器(从 Chrome 9 到 FF 4)中尝试了它们,但似乎仍然没有任何东西可以与“postMessage”功能一起使用。JS 控制台什么也没给我,没有一个错误,仍然没有发生任何事情:框架不想通信。完全没有。这甚至不是跨域的:两个框架都来自我的域。

这是上次尝试的示例代码:父框架:

<iframe src="IFRAME_URL"></iframe>
<script>
    window.addEventListener( "message",
      function (e) {
            if(e.origin !== 'DOMAIN'){ return; } 
            alert(e.data);
      },
      false);
</script>

子框架:

<html>
<head></head>
<body>
    <script>
        top.postMessage('hello', 'DOMAIN');
    </script>
</body>

非常感谢帮助,非常感谢

4

4 回答 4

21

你的第二个参数postMessage必须是一个像http://localhost

于 2011-06-20T13:46:58.697 回答
3

如果您不处理不同的来源,location.origin则作为targetOrigin输入将起作用。

top.postMessage('hello', location.origin);
于 2017-04-20T15:26:49.867 回答
3

您还可以将消息发送到任何窗口使用top.postMessage('hello', "*");

网页 1:

<iframe src="IFRAME_URL"></iframe>
<script>
window.addEventListener( "message",
  function (e) { 
        alert(e.data);
  },
  false);
</script>

html 2:

<html>
<head></head>
<body>
    <script>
        top.postMessage('hello', '*');
    </script>
</body>
于 2019-01-21T20:16:16.333 回答
1

我不确定安全问题,但通常,我只是像这样抓住父窗口位置:

var url = (window.location != window.parent.location) ? document.referrer: document.location;
top.postMessage('message', url);
于 2013-10-30T20:52:07.750 回答