javascript - 如何将 PostMessage 发送到我网站上的实际文档,而不仅仅是弹出窗口

标签 javascript html postmessage

所以,我有一些用于 postMessage 的代码,它显然工作正常,只是不是我想要的方式: 在发送端:

<!DOCTYPE html>
<html>
<body>
<head>
<title>Posting.html</title>
</head>
<button onclick = "reset()">RESET</button>
<script>
// create popup window
var targetOrigin = 'http://www.examplemsg.com';
var myPopup = window.open("http://www.examplemsg.com/destination.html", 'myWindow');

// periodical message sender
var matrix = setInterval(function(){
   var message = 'Hello! The time is: ' + (new Date().getTime());
   console.log('blog local: sending message: ' + message);

   myPopup.postMessage(message, targetOrigin); // send the message & target URI
 }, 6000);

function reset() { clearInterval(matrix);}

// listen to holla back
window.addEventListener('message', function(event){ 

if(event.origin !== 'http://www.examplemsg.com';) return;
console.log('received response: '+event.data);
}, false);
<script></body></html>

在接收端,/destination.html...

<!DOCTYPE html>
<html>
<body>
<head>
<title>Receiving end</title>
</head>
<script>
window.addEventListener('message',function(event) {
console.log('message received: '+event.data);
event.source.postMessage('holla back youngin!',event.origin);
}, false);
</script>
</body>
</html>

当我使用其他浏览器(例如 Google Chrome)加载/destination.html 时,然后查看 Chrome 的控制台 (CTRL-Shift-I),它是空白的。这让我觉得我只是将消息发送到弹出窗口本身,而不是我网站上的实际文档。当我用 iframe 尝试这个时,发生了类似的事情。我该如何更改?

最佳答案

您的代码无法正确执行,您在这一行有语法错误:

if(event.origin !== 'http://www.examplemsg.com';) return;

在 destination.html 中你也有语法问题: 看一看:

<body>
<head>
<title>Receiving end</title>
</head>
<script>

删除多余的分号,按预期格式化您的 html 文档,再试一次您的示例 将按预期工作

关于javascript - 如何将 PostMessage 发送到我网站上的实际文档,而不仅仅是弹出窗口,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20789023/

相关文章:

javascript - 为什么 Opera 12 中后台脚本和注入(inject)脚本之间无法发布消息?

javascript - IE9中的数据问题addEventListener

javascript - postMessage 或 addEventListener 不起作用

javascript - javascript中的正则表达式替换函数

javascript - 如何在 jQuery 中通过现有类添加类

javascript - 根据类设置元素宽度

javascript - (Jquery) 单击 div 使用 css 转换扩展

javascript - Ajax 就绪状态 3 (Chrome/IE)

javaScript - ES6 中的多重继承,

html - 在IE上隐藏滚动条(保留边框)