邮寄消息不起作用

Postmessage not working

我想将消息从一个域发送到另一个域。为此,我正在使用 postMessage。我有一个似乎不错的代码,但仍然无法发送消息。经历了各种相关post但是没有用

即使在同一个域上也无法正常工作。

如果有人能指出代码的问题,那将非常有帮助。谢谢

主页:

<html>
<head></head>
<body>
    <iframe src="http://localhost/sandbox/test/test2.html"></iframe>
    <script>
        window.addEventListener( "message",
          function (e) {
                if(e.origin !== 'http://localhost/sandbox/test/test2.html'){ return; } 
                alert(e.data);
          },
          false);
    </script>
</body>
</html>

iframe内容:

<html>
    <head></head>
    <body>
        <script>
            top.postMessage('hello', 'http://localhost/sandbox/test/test.html');
        </script>
    </body>
</html>

你应该做一些基本的调试来找出问题所在。

您的函数以 if 测试开始,但您似乎没有确定问题是 if 未被输入还是函数未被输入根本没有打电话。

在那里放一个 console.log() 语句来找出答案。

测试e.origin的值是多少。

您应该会发现它是 http://localhost(与您正在测试的内容不匹配)。 Origins 不包括路径段。

这就是您的测试失败的原因。