javascript postMessage 不起作用

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6411762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 21:37:29  来源:igfitidea点击:

javascript postMessage not working

javascriptiframepostmessage

提问by Cystack

I don't know what to do. I tried several sample codes from different sources, I tried them in different browsers (from Chrome 9 to FF 4), and still nothing seems to be working with the "postMessage" function. JS console is giving me nothing, not a single error, still nothing is happening : the frames don't want to communicate. At all. And this isn't even cross-domain : both frames are from my domain.

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

Here is a sample code from the last try : Parent frame :

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

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

Child frame :

子框架:

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

Help much appreciated, thanks a lot

非常感谢帮助,非常感谢

采纳答案by Mic

The second parameter of your postMessagemust be an url like http://localhost

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

回答by James Lawruk

If you are not dealing with different origins, entering location.originas the targetOriginwill work.

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

top.postMessage('hello', location.origin);

回答by user10946822

you can also send the message to any window use top.postMessage('hello', "*");

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

Html 1:

文本 1:

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

html 2:

html 2:

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

回答by Phil LaNasa

I'm not sure of the security concerns, but typically, I just grab the parent window location like this:

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

var url = (window.location != window.parent.location) ? document.referrer: document.location;
top.postMessage('message', url);