61

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

2

13 Answers 13

52

For a more modern solution check out this answer quoted below:

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:
https://developer.mozilla.org/docs/Web/API/Web_Storage_API

5
  • For scope of key stored in localStorage vs sessionStorage
    – RBT
    Oct 25, 2017 at 2:12
  • You will have issues with browsers such as Edge, which in private mode do not share local storage between tabs. Jan 30, 2019 at 15:34
  • 1
    There are several other ways to share data between tabs: you can also use postMessage or BroadcastChannel. Jan 20, 2021 at 18:24
  • 1
    Page not found This question was removed from Stack Overflow for reasons of moderation.
    – kyxap
    Jul 2, 2023 at 1:39
  • The link of this answer is borken. Dec 10, 2023 at 20:41
21

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' )
2
  • 1
    I don't think this will work in situations where the user opens a page in a separate tab on their own. Sep 2, 2009 at 18:37
  • But in situations where the child window is only opened by clicking a button in the parent and made full-screen on a second monitor while the parent controls it... should work a charm.
    – Patrick
    Aug 30, 2019 at 20:02
9

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

5

See also another StackOverflow thread: 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.

3

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

1
  • 2
    Yes cookies are only bound to domains, therefore shared between tabs. However one must poll the cookie continuously, you can not listen to cookie changes.
    – sibidiba
    Feb 15, 2011 at 13:41
2

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

2

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

5
  • Yep, this method is known as "Comet". From the client side it's no different than simple AJAX polling (e.g. make an AJAX request, process the response and make another request). However the serverside is atypical compared to traditional AJAX. The server will not return right away after it done it's task. Instead it will keep that (for example PHP request) open and do a while()-like loop until there is new information (or when the timeout, i.e. 50 seconds is exceeded). Read more: en.wikipedia.org/wiki/Comet_(programming%29 . It is not real push technology, but as close as possible. Nov 22, 2011 at 18:19
  • 2
    Why not just use sockets? Jan 21, 2013 at 22:02
  • 3
    This doesn't come close to answering the question. Why was it accepted? The question was how to communicate between browser tabs; not between server and browser. Jun 20, 2013 at 14:57
  • 1
    Andrew they can communicate via the server. I.e. one tab sends a message, Comet response is received by other tab(s). There is no direct way for two tabs to communicate. Shared local storage and cookies as per other responses an option too. Aug 1, 2013 at 19:46
  • 1
    @Dodgyrabbit - cough caniuse.com/x-doc-messaging :)
    – broofa
    Sep 3, 2013 at 21:37
1

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.

2
  • you mean make an ajax call to the server to check is something has changed every less than a second? that's not the way..
    – vsync
    Apr 5, 2011 at 12:05
  • If you need things to happen live, this would indeed require making a ton of requests all the time. However this can be solved by making the server hold the request for a longer period of time until there is data (or until the timeout is exceeded). See also [Comet (wikipedia)](en.wikipedia.org/wiki/Comet_(programming%29) and my answer. This is also how EtherPad and Facebook Chat works. Nov 22, 2011 at 18:37
1

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.

0

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.

0

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.

1
  • 3
    Not true, the cookie can be polled just like an AJAX service. Sep 2, 2009 at 18:39
0

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)
 };
0

this creates an object on which you can set any properties, it will be set as a json string on the localStorage and then (if available) a BroadCast message will be sent, the other tab then loads the object from json and re-proxies it

let o_bc_o_localstorage = false; 
if("BroadcastChannel" in window){
    o_bc_o_localstorage = new BroadcastChannel('o_localstorage');
}
let f_o_localstorage_from_json_parse = function(){
    let o_localstorage = {}
    let s_o_localstorage = localStorage.getItem('o_localstorage');
    if(s_o_localstorage){
        o_localstorage = JSON.parse(s_o_localstorage)
    }
    return o_localstorage
}
let o_localstorage = f_o_localstorage_from_json_parse();
let f_update_localstorage = function(){
    if(o_bc_o_localstorage){
        o_bc_o_localstorage.postMessage('update')
    }
    localStorage.setItem('o_localstorage', JSON.stringify(o_localstorage))
}


let f_o_proxied_recursive = function(o, f_set, f_get){
    for(let s in o){
        if(typeof o[s] == 'object'){
            o[s] = f_o_proxied_recursive(o[s], f_set, f_get)
        }
    }
    o = new Proxy(o, {set: f_set, get: f_get});
    return o
}

let f_get = function(v_target, s_prop, v_receiver) {

    return Reflect.get(...arguments);
}

let f_set = function(v_target, s_prop, v_receiver) {
    console.log("setter called")
    if(typeof v_receiver == 'object'){
        
        v_receiver = f_o_proxied_recursive(v_receiver, f_set, f_get)
    }
    let o_res = Reflect.set(v_target, s_prop, v_receiver);
    f_update_localstorage()
    return o_res
}
let f_reproxy_o_localstorage = function(){
    o_localstorage = f_o_localstorage_from_json_parse()
    o_localstorage = f_o_proxied_recursive(o_localstorage, f_set, f_get)
}
if(o_bc_o_localstorage){
    o_bc_o_localstorage.onmessage = function(){
        console.log("reproxy")
        f_reproxy_o_localstorage()
    }
    f_reproxy_o_localstorage()
}
if(!o_bc_o_localstorage){
    let n_id = 0;
    let f_recursive = function(){
        n_id = window.requestAnimationFrame(f_recursive)
        f_reproxy_o_localstorage()
    }
    n_id = window.requestAnimationFrame(f_recursive)
}

//tab1 
o_localstorage.n = 420
o_localstorage.a = [1,2,3,4]
o_localstorage.o_s_o = {o_s_name_a_n:{a_1:[1,2,3], a_2:['a', 'b']}}
o_localstorage.o_s_o.o_s_name_a_n.a_1.push(420)
o_localstorage.o_s_o.o_s_name_a_n.a_2.push('fourtwenty')

//tab1 
o_localstorage.o1={o2:{o3:{n:4}}}
//tab2 
console.log(o_localstorage.o1.o2.o3.n) // 4
o_localstorage.o1.o2.o3.n = 5
//tab1 
console.log(o_localstorage.o1.o2.o3.n) // 5

Not the answer you're looking for? Browse other questions tagged or ask your own question.