javascripthtmlcross-window-scripting

Sending a message to all open windows/tabs using JavaScript


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.)


Solution

  • Assuming you don't need to broadcast a message to other websites (just your own), BroadcastChannel is made for this purpose.

    const channel = new BroadcastChannel('myChannel');
    channel.postMessage('myMessage');
    channel.addEventListener('message', m => {
        console.log('Received message from other document', m);
    });