DEV Community

loading...
Cover image for Syncing tabs via service worker

Syncing tabs via service worker

jhamadhav profile image Madhav Jha ・2 min read

Introduction

The idea of having to sync different tabs within the same browser is not something new and there are tons of different ways in which it can be done, there is no right way to do it; it will always depend on the situation and task at hand.

Here's a brilliant video on the very topic by Google Chrome developers on YouTube.

In this post we will achieve this by using Service workers in the browser, it is not yet 100% supported in all browsers but its support is increasing day by day in modern browsers.

Demonstrating tabSync

Let's make a simple project to achieve the mentioned syncing in our projects.
Get the demo here and the complete code in my GitHub repo.

This is the final version once we implement tabSync :
tabSync demo

Setting up the project

We will be making a simple clicker button and increment its counter value on each click by 1, and via tab sync we will be able to see the same effect on different tabs.
Check the clicker markup and code from the Hex clicker GitHub repo.

Now we have a simple counter-click page ready.

Sending the increment value to service worker

From the above repo it is clear what the hex button does, once the button is clicked it increments the global variable num value by one and assign it to the counter.
But since we want this value to be the same across all tabs we will send the num variable value to the service worker via the following function below.

Receiving and broadcasting the received data via service worker

Now that we sent the incremented num value to the service worker we will have to receive it in the worker and then send the same value to all the tabs(same tabs) in the browser.

The event listener for that in worker is as follows:

Updating the increment value in tabs

Now that we have sent the incremented value across the tab now we need to receive the same in all the tabs and then display it via the counter as follows.:

And with that we have all our tabs(of hex-clicker) in sync with each other.

Final words

This was a very simplified way of using service worker to keep tabs in sync. To get started and know more on the topic check the links and resources given in the above post.
For any and all questions regarding this comment down below.
All helpful suggestion are welcome :)

Discussion (0)

Forem Open with the Forem app