问题
This question already has an answer here:
- Communication between tabs or windows 9 answers
I hear HTML5 has window.postMessage()
, but it seems to require having a handle on the window (or tab, throughout this question) you're posting the message to. What if I want to broadcast to all open windows? Is this possible?
(What I'm trying to do is warn other windows without any server round-trips when a user does something in one window that affects the others, so that they can update their content. However, while some windows may be opened from existing ones--allowing me to intercept and store references to them--some fresh windows may be opened manually by the user and then a bookmark selected or URL typed in. In this case there doesn't seem to be a way to intercept and store references.)
回答1:
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.
回答2:
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.
回答3:
I recommend to use https://github.com/studentIvan/dueljs Brief look: http://dueljs.studentivan.ru and docs: https://dueljs.readthedocs.org/en/latest/
来源:https://stackoverflow.com/questions/1100336/sending-a-message-to-all-open-windows-tabs-using-javascript