Sending a message to all open windows/tabs using JavaScript [duplicate]

旧巷老猫 提交于 2019-11-27 13:34:08
Rafael

IMO this is not possible using the postMessage. How about using sessionStoragelocalStorage? Writing to it should generate a storage event that should be propagated to all windows sharing the same session storage.

I wrote a library to do just this: intercom.js (for the same reasons you outlined).

We're currently using it to broadcast notifications to all windows, so only one window needs to maintain a socket connection to the server. As some others suggested, it uses the localStorage API.

Usage is really simple:

var intercom = Intercom.getInstance();

$('a').on('click', function() {
     intercom.emit('notice', {message: 'Something just happened!');
});

To catch the message,

intercom.on('notice', function(notice) {
    console.log(notice.message);
});

The interface is designed to mimic socket.io.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!