Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 27, 2021 03:12 pm GMT

Share data between browser tabs

I recently came across the issue of sharing some data between different tabs of the same web application. Using OAuth to retrieve an external provider's API key, saving it and finally displaying it on our platform. The first solution implied reloading the entire page. But the user experience was heavily compromised. In a SPA point of vue, imagine being in /process/emailing/... and redirected to /process

While looking for a more suitable solution, I came across the Broadcast Channel API.

It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel.

Let's start by creating a broadcast channel:

const channel = new BroadcastChannel('oauth')

Here we specified the name oauth that will later be used in other parts of our app to listen on any message sent through this channel.

channel.postMessage(data)

Here we send a message and, we can pass any object we like. In our case, we just needed an indication to know a certain task was done so the content did not really matter, feel free to pass useful data according to your need.

The data sent can be any of those supported values:

  • All primitive types, excluding symbols
  • Arrays
  • Object literals
  • String, Date, RegExp objects
  • Blob, File, FileList objects
  • ArrayBuffer, ArrayBufferView objects
  • FormData objects
  • ImageData objects
  • Map and Set objects

Now we need to listen to the same channel in other parts of our app. To do so, we create a channel with the same name and use the onmessage event handler

const channel = new BroadcastChannel('oauth')channel.onmessage = (e) => {  // Business logic here  // data sent through the channel is available at e.data}

And that's it! We successfully sent data from a different window, tab or frame to another .

Finally, to make a channel stop receiving messages you can close it using:

channel.close()

You can achieve the same result using the SharedWorker API or even Local Storage but, personally I found this method the most intuitive. Do you know any other alternative ?


Original Link: https://dev.to/baedyl/share-data-between-browser-tabs-4hil

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To