Communication between tabs or windows

Tomas M :

I was searching for a way how to communicate between multiple tabs or windows in a browser (on the same domain, not CORS) without leaving traces. There were several solutions:

  1. using window object
  2. postMessage
  3. cookies
  4. localStorage

The first is probably the worst solution - you need to open a window from your current window and then you can communicate only as long as you keep the windows open. If you reload the page in any of the windows, you most likely lost the communication.

Second approach, using postMessage, probably enables cross-origin communication, but suffers the same problem as the first approach. You need to maintain a window object.

Third way, using cookies, store some data in the browser, which can effectively look like sending a message to all windows on the same domain, but the problem is that you can never know if all tabs read the "message" already or not before cleaning up. You have to implement some sort of timeout to read the cookie periodically. Furthermore you are limited by maximum cookie length, which is 4KB.

Fourth solution, using localStorage, seemed to overcome the limitations of cookies, and it can be even listen-to using events. How to use it is described in the accepted answer.

Edit 2018: the accepted answer still works, but there is a newer solution for modern browsers, to use BroadcastChannel. See the other answer for a simple example describing how to easily transmit message between tabs by using BroadcastChannel.

Tomas M :

Edit 2018: You may better use BroadcastChannel for this purpose, see other answers below. Yet if you still prefer to use localstorage for communication between tabs, do it this way:

In order to get notified when a tab sends a message to other tabs, you simply need to bind on 'storage' event. In all tabs, do this:

$(window).on('storage', message_receive);

The function message_receive will be called every time you set any value of localStorage in any other tab. The event listener contains also the data newly set to localStorage, so you don't even need to parse localStorage object itself. This is very handy because you can reset the value just right after it was set, to effectively clean up any traces. Here are functions for messaging:

// use local storage for messaging. Set message in local storage and clear it right away
// This is a safe way how to communicate with other tabs while not leaving any traces
//
function message_broadcast(message)
{
    localStorage.setItem('message',JSON.stringify(message));
    localStorage.removeItem('message');
}


// receive message
//
function message_receive(ev)
{
    if (ev.originalEvent.key!='message') return; // ignore other keys
    var message=JSON.parse(ev.originalEvent.newValue);
    if (!message) return; // ignore empty msg or msg reset

    // here you act on messages.
    // you can send objects like { 'command': 'doit', 'data': 'abcd' }
    if (message.command == 'doit') alert(message.data);

    // etc.
}

So now once your tabs bind on the onstorage event, and you have these two functions implemented, you can simply broadcast a message to other tabs calling, for example:

message_broadcast({'command':'reset'})

Remember that sending the exact same message twice will be propagated only once, so if you need to repeat messages, add some unique identifier to them, like

message_broadcast({'command':'reset', 'uid': (new Date).getTime()+Math.random()})

Also remember that the current tab which broadcasts the message doesn't actually receive it, only other tabs or windows on the same domain.

You may ask what happens if the user loads a different webpage or closes his tab just after the setItem() call before the removeItem(). Well, from my own testing the browser puts unloading on hold until the entire function message_broadcast() is finished. I tested to put inthere some very long for() cycle and it still waited for the cycle to finish before closing. If the user kills the tab just inbetween, then the browser won't have enough time to save the message to disk, thus this approach seems to me like safe way how to send messages without any traces. Comments welcome.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Communication between tabs or windows

Javascript; communication between tabs/windows with same origin

Javascript communication between browser tabs/windows

What is the fastest communication between tabs in Google Chrome?

WPF: Communication between windows on MVVM

Redux communication between browser tabs makes ping-pong effect (multiway communication)

Switching between windows or tabs doesn't finish

Communication between Windows Host and Linux Docker Container

communication between 2 browser windows in electron

Communication between UI and Core on windows machine

Electron application ipc communication between two windows

Communication between two browser windows: popup and parent

two windows installs, no communication between them?

Communication channel between a windows app and UWP app

TCP communication between Windows 10 and Windows IOT core

How to switch only between editor windows (not tabs) in split mode

Angular 2+ Interaction between separate windows/tabs

Difference between Windows Task Manager's Processes and Details tabs

Communication between an Azure web application and a windows form app on Azure VM

Shell extension windows : best communication between ContextMenu and IconOverlay?

Communication between node.js and WCF service hosted in a windows service

Communication between Ubuntu on WSL2 and Windows is spotty after startup

Continuous communication between parent and child subprocess in Python (Windows)?

SOAP Communication between PHP client and windows service results in NullReferenceException

Communication between ASP.NET frontend and Windows Service backend?

What is the best way for communication between Powershell script and Windows service?

Difference between $('#tabs a') and $('#tabs').find('a')

Spacing between tabs TabPageIndicator

Switch between tabs in tabpane