An Interest In:
Web News this Week
- April 19, 2024
- April 18, 2024
- April 17, 2024
- April 16, 2024
- April 15, 2024
- April 14, 2024
- April 13, 2024
Send data between tabs with JavaScript
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 something happens one tab which you want to react to on the other tabs - you can do this using the Broadcast Channel API.
Before we start, I want to mention that this only works between browsing contexts on the same origin.
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. When subscribing to a channel, you're then able to post and receive messages from it.
Speaking of posting messages, let's do that right now:
channel.postMessage("Hey, how's it going mate? I'm from a different tab!");
We can send multiple different kinds of objects with the postMessage
method, for example:
// array channel.postMessage([5, 10, 15, 20]); // object channel.postMessage({ name: "Dom", age: 30 }); // blob channel.postMessage(new Blob(["sample text"], { type: "text/plain" }));
Receiving messages
Now, on the second tab, we can listen for and receive those messages. Open up a new tab (on the same origin, i.e. localhost
) and include this code:
// subscribe to the same channel, "my-channel" const channel = new BroadcastChannel("my-channel"); channel.addEventListener("message", e => { console.log(e.data); });
Once this code is included, open up both the tabs, then refresh the original one (the one doing the posting), and you should see the data appearing in the console.
It's that easy! You simply listen for the message
event and once you have it, access the data with the data
property.
Browser Support
To see browser support for the Broadcast Channel API, you may check out the Can I use... link here.
Video Tutorial
If you prefer a video version of the above tutorial, you can view it on my YouTube channel, dcode:
Original Link: https://dev.to/dcodeyt/send-data-between-tabs-with-javascript-2oa
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To