Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: sharing data between tabs

Tags:

javascript

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

like image 550
alexey Avatar asked Sep 02 '09 08:09

alexey


People also ask

How do I pass data between two tabs?

Sending Data To send something to another tab, we need to first create a new BroadcastChannel instance. This is super easy, and looks like this: const channel = new BroadcastChannel("my-channel"); Notice how we passed in my-channel - this is the name of the channel which we are subscribing to.

Can local storage be shared between tabs?

The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.

Is sessionStorage a tab?

Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window. Duplicating a tab copies the tab's sessionStorage into the new tab. Closing a tab/window ends the session and clears objects in sessionStorage .


2 Answers

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/
http://dev.w3.org/html5/webstorage/#the-storage-event

like image 132
brillout Avatar answered Sep 22 '22 19:09

brillout


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' ) 
like image 44
Stephen Sorensen Avatar answered Sep 21 '22 19:09

Stephen Sorensen