JavaScript: sharing data between tabs

Javascript

Javascript Problem Overview


What is the best way to share data between open tabs in a browser?

Javascript Solutions


Solution 1 - Javascript

For a more modern solution check out https://stackoverflow.com/a/12514384/270274

Quote: > I'm sticking to the shared local data solution mentioned in the question using localStorage. It seems to be the best solution in terms of reliability, efficiency, and browser compatibility. > > localStorage is implemented in all modern browsers. > > The storage event fires when other tabs makes changes to localStorage. This is quite handy for communication purposes. > > Reference:
> http://dev.w3.org/html5/webstorage/<br> > http://dev.w3.org/html5/webstorage/#the-storage-event

Solution 2 - Javascript

If the first tab opens the second tab automagically, you can do something like this:

First tab:

//open the first tab
var child_window = window.open( ...params... );

Second tab:

// get reference to first tab
var parent_window = window.opener;

Then, you can call functions and do all sorts of stuff between tabs:

// copy var from child window
var var_from_child = child_window.some_var;

// call function in child window
child_window.do_something( 'with', 'these', 'params' )

// copy var from parent window
var var_from_parent = parent_window.some_var;

// call function in child window
parent_window.do_something( 'with', 'these', 'params' )

Solution 3 - Javascript

See also another StackOverflow thread: https://stackoverflow.com/questions/4079280/javascript-communication-between-browser-tabs-windows.

In my opinion there are two good methods. One may suit you better depending on what you need.

If any of these are true...

  • you can't store information server side,
  • you can't make many http requests,
  • you want to store only a little bit of information[1],
  • you want to be pure javascript / client side,
  • you only need it to work between tabs/windows in the same browser.

-> Then use cookies (setCookie for sending, getCookie/setTimeout for receiving). A good library that does this is http://theprivateland.com/bncconnector/index.htm

If any of these are true...

  • you want to store information server side
  • you want to store a lot of information or store it in a related matter (i.e. tables or multi-dimensional arrays[2])
  • you also need it to across different browsers (not just between tabs/windows in the same browser) or even different computers/users.

-> Then use Comet (long-held HTTP request allows a web server to basically push data to a browser) for receiving data. And short POST requests to send data.

Etherpad and Facebook Chat currently use the Comet technique.


[1] When using localStorage more data can be stored obviously, but since you'd fallback on cookies one can't rely on this yet. Unless you application is for modern browsers only in which case this is just fine.

[2] Complicated data can be stored in cookies as well (JSON encoded), but this is not very clean (and needs fallback methods for browsers without JSON.stringify/JSON.parse) and can fail in scenarios involving concurrency. It's not possible to update one property of a JSON cookie value. You have to parse it, change one property and overwrite the value. This means another edit could be undone theoretically. Again, when using localStorage this is less of a problem.

Solution 4 - Javascript

The only way I can think of: constant ajax communication with the server to report any user action on the other tabs.

Solution 5 - Javascript

How about to use a cookie to store data in one tab and poll it in another tab? i dont know yet if a cookie is shared between tabs but just an idea now ...

Solution 6 - Javascript

I just took a look at how Facebook Chat does it and they keep a request to the server open for a little less then a minute. If data comes back to the server, the server then sends back the message to each open request. If no data comes back in a minute, it re-requests and continues to do this (for how long, I am not sure).

Solution 7 - Javascript

The BroadcastChannel standard allows doing this. see MDN BroadcastChannel

// Connection to a broadcast channel
const bc = new BroadcastChannel('test_channel');

// Example of sending of a very simple message
bc.postMessage('This is a test message.');

// A handler that only logs the event to the console:
bc.onmessage = function (ev) { console.log(ev); }

// Disconnect the channel
bc.close();

enter image description here

Solution 8 - Javascript

Given that these tabs are open with the same site in them, you might consider building an ajax script that reports user actions to server and couple it with another ajax script that reads that reports and reflects them in current window.

Solution 9 - Javascript

You could use AJAX (as everyone else is suggesting) or cookies if the data is small. See http://www.quirksmode.org/js/cookies.html for fun with cookies.

Solution 10 - Javascript

One way to do this is to not let the chat window be dependent on the tabs. Load the tabs as seperate AJAX components that when reloads doesn't affect the chat component.

Solution 11 - Javascript

Depending on the requirements you can also use cookies/sessions. However, this means the data will only be accessible on the first page load of each tab.

If you already have two tabs open, changing something in one will not change the other unless you use some AJAX.

Solution 12 - Javascript

This can be done using BroadcastChannel API in javascript. Let's say you have opened two different pages in a different tab and want to update the first page when the user changes some values in the second page you can do that like below.

First page

const ticketUpdateChannel = new BroadcastChannel('ticketUpdate');
ticketUpdateChannel.onmessage = function(e) {
     console.log('ticket updated')
 };

Second page

const ticketUpdateChannel = new BroadcastChannel('ticketUpdate');
ticketUpdateChannel.postMessage();

Now when you can postMessage it will trigger the onmessage on the first page.

Also, you can pass data like the below.

const ticketUpdateChannel = new BroadcastChannel('ticketUpdate');
ticketUpdateChannel.postMessage({message:'Updated'});


const ticketUpdateChannel = new BroadcastChannel('ticketUpdate');
ticketUpdateChannel.onmessage = function(e) {
     console.log('ticket updated',e.data)
 };

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionalexeyView Question on Stackoverflow
Solution 1 - JavascriptbrilloutView Answer on Stackoverflow
Solution 2 - JavascriptStephen SorensenView Answer on Stackoverflow
Solution 3 - JavascriptTimo TijhofView Answer on Stackoverflow
Solution 4 - JavascriptAlsciendeView Answer on Stackoverflow
Solution 5 - JavascriptChrisView Answer on Stackoverflow
Solution 6 - JavascriptBrianView Answer on Stackoverflow
Solution 7 - JavascriptObaida AlhassanView Answer on Stackoverflow
Solution 8 - Javascriptn1313View Answer on Stackoverflow
Solution 9 - JavascriptJustin JohnsonView Answer on Stackoverflow
Solution 10 - JavascriptRandellView Answer on Stackoverflow
Solution 11 - JavascriptDisgruntledGoatView Answer on Stackoverflow
Solution 12 - JavascriptIshan FernandoView Answer on Stackoverflow