DEV Community

Send data between tabs with JavaScript

Dom (dcode) on July 16, 2020

Did you know you can send information between open browser tabs using JavaScript? Let's say your user is viewing your site with multiple tabs and ...
Collapse
 
khrisl33t profile image
kHRISl33t

I had to implement a similar thing before for a chat application where we stored the chat state in local storage. I went with the window.addEvenLister('storage') approach because I had to support IE 11 and Safari.

Hope BroadcastChannel will get more support on older browsers, it seems nice and simple. :)

Collapse
 
vitkarpov profile image
Viktor Karpov

I made a tiny cross-browser lib (github.com/vitkarpov/tabs-channel) for that. Works even on different domains.

Collapse
 
theonlybeardedbeast profile image
TheOnlyBeardedBeast

Better than listening to changes on local storage, nice article, thanks.

Collapse
 
theadin profile image
theadin

Sounds like this could be useful for communication between an iframe and its parent window too...

Collapse
 
dcodeyt profile image
Dom (dcode)

Yep! You can use it to communicate between those as well

Collapse
 
vyckes profile image
Kevin Pennekamp • Edited

The biggest issue is that it does not work with Safari (as you linked). Data sharing between tabs on mobile would not happen often, but on Safari MacOS this solution is a problem.

With some tricks you can use localStorage to achieve a similar effect.

Collapse
 
dcodeyt profile image
Dom (dcode)

It's probably best I add that to the post, cheers

Collapse
 
jcubic profile image
Jakub T. Jankiewicz • Edited

I've created an JS library that abstracts that away. It uses both broadcastChannel and localStorage. And it has an API for cross-domain communication as well sysend.js. It also works in IE 11, that has some issues (as always).

Collapse
 
naismith profile image
Chris Naismith

Hey Dom!

Great article, I wrote something similar last year that you may be interested in as well!

dev.to/naismith/cross-tab-communic...

Collapse
 
dcodeyt profile image
Dom (dcode)

Nice article - love the live previews

Collapse
 
mxldevs profile image
MxL Devs

Interesting feature. I suppose a standard messaging API across different contexts makes communication easier compared to trying to find a way to hack things together.