javascript postMessage无效

Cys*_*ack 22 javascript iframe postmessage

我不知道该怎么办.我尝试了不同来源的几个示例代码,我在不同的浏览器中尝试过它们(从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>
Run Code Online (Sandbox Code Playgroud)

儿童框架:

<html>
<head></head>
<body>
    <script>
        top.postMessage('hello', 'DOMAIN');
    </script>
</body>
Run Code Online (Sandbox Code Playgroud)

非常感谢,非常感谢

Mic*_*Mic 15

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

  • 或者,参数可以是""*"`...我非常劝阻除了测试目的之外的任何事情. (4认同)

小智 5

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

网页1:

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

html 2:

<html>
<head></head>
<body>
    <script>
        top.postMessage('hello', '*');
    </script>
</body>
Run Code Online (Sandbox Code Playgroud)