What is the best way to share data between open tabs in a browser?
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.
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.
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 .
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 tolocalStorage
. This is quite handy for communication purposes.Reference:
http://dev.w3.org/html5/webstorage/
http://dev.w3.org/html5/webstorage/#the-storage-event
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' )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With