html5 postMessage 不起作用

发布于 2024-12-28 17:56:08 字数 659 浏览 3 评论 0原文

即使我通过 postMessage 重复发送域消息,我的 window.addEventListener 函数也不会被触发。似乎根本没有收到任何回应。代码如下:

var myUrl = 'http://localhost:8085';
var newPopup = window.open( myUrl, '_blank', '' );

// Create listener
window.addEventListener('message',function(event) {

  if (event.origin !== 'http://localhost:8085') return;
    console.log('received response:  ',event.data);

},false);

// Setup messenging
setInterval(function(){
    var message = 'Hello!  The time is: ' + (new Date().getTime());
    console.log('blog.local:  sending message:  ' + message);
    newPopup.postMessage(message,'http://localhost:8085');  
},2000);

为什么侦听器不接收消息?

My window.addEventListener's function is not getting fired even when I repeatedly send the domain messages via postMessage. It's seems like it isn't receiving any response at all. Here is the code:

var myUrl = 'http://localhost:8085';
var newPopup = window.open( myUrl, '_blank', '' );

// Create listener
window.addEventListener('message',function(event) {

  if (event.origin !== 'http://localhost:8085') return;
    console.log('received response:  ',event.data);

},false);

// Setup messenging
setInterval(function(){
    var message = 'Hello!  The time is: ' + (new Date().getTime());
    console.log('blog.local:  sending message:  ' + message);
    newPopup.postMessage(message,'http://localhost:8085');  
},2000);

Why doesn't the listener ever pickup the messages?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

西瓜 2025-01-04 17:56:08

您在错误的窗口上注册了处理程序。尝试

newPopup.addEventListener('message',function(event) {
    ...

You are registering the handler on the wrong window. Try

newPopup.addEventListener('message',function(event) {
    ...
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文