How to Use Service Workers to Communicate Across Browser Tabs

Share this article

How to Use Service Workers to Communicate Across Browser Tabs
This interview has been republished from Versioning, SitePoint’s daily subscription newsletter helping developers stay up-to-date and knowledgeable by offering curated links to the essentials in front-end, back-end, design and UX, news, business and more. Learn more and sign up here.
Sign up to Versioning Tim Evko Tim Evko is a front-end developer, managing a primarily React codebase, and team lead at ExecThread, a company focused on surfacing job openings to professionals. When not at ExecThread, he spends the rest of his time at a local gym, working on being a better competitive Crossfit Athlete.

Which tech idea or trend excites you the most at the moment?

Lately I’ve been fascinated with Service Worker technology, especially when used to help make sites load fast and become interactive quickly. I love performance and web-app-offline capability, and I think the community can benefit from the increased focus on building resilient, versatile, and fast applications. Service Workers are especially fun to work with because of how much you can do with them. I recently learned that you can use a Service Worker to communicate across tabs in a browser, allowing each individual tab to reload itself if the cache is stale. It’s not an easy technology to work with but I’m very glad that it’s around!

I don’t think I’ve heard of this before – could you go into more detail?

In a browser, Service Workers have control over all clients that are in the available scope, not just the current active tab. This means that when a Service Worker is communicating with a site in your browser, it’ll still be communicating with all tabs that are currently displaying that site. You can take advantage of this feature when using the postMessage API that comes with Service Worker. A detailed example of that can be found here. At ExecThread, we use this functionality to reload all tabs in case a Service Worker serves an old CSS file to a page with new markup on it.

Describe (or link to!) something cool you built, designed or produced recently. Why are you proud of it?

I recently set out to understand how virtual DOM algorithms worked, and in doing so built my very own component render-er: BadDom [github]. It’s 600 bytes and you can build your entire web app with it. I’m proud of it because It’s 600 bytes and you can build your entire web app with it. BadDOM is actually really simple, and that’s what I love about it. If you give it a node (a div on a page for example) and an ES6 template string, it will update the first div so that it matches the template string. Essentially it’s a DOM-diffing function that makes sure its target will look like the template string. Since it’s an ES6 template string however, you can add logic to your diffing. This means that you can call the diffing function whenever you update whatever state your logic is based off of, and your original DOM target will match the new state. The whole thing works by creating an invisible element with your template string, and comparing the target element (and it’s children) to find, remove, or modify all DOM nodes until the template string based element and the target element look the same. It’s efficient because it never updates an element that doesn’t need to be updated, thereby preventing the browser from ever having to do unnecessary work. If you have 100 nested elements and only one class name changes on one of them, BadDom will find the one and only change the class.

How did you build it?

Like most of my projects, I built this on CodePen. I like to focus on keeping things as simple as possible with as little build tools / setup as possible. That way it’s easiest for anyone to understand and contribute to regardless of the platforms or devices they’re using. CodePen is great because I don’t need to set up an IDE to work on Front End libraries. I could talk all day about CodePen, it’s community, and how much I’ve learned from others work on it, but instead I’ll just say that everyone should have a look for themselves. I like to write all of my JavaScript using the Module pattern, which I did here. The module pattern is a way to write JavaScript so that all code is inside of a self contained object. Methods inside of the object are stored as functions-as-properties, and configuration values can be stored as objects-as-properties. I like to use this pattern because of how easy it is to organize code (especially libraries). You can find more about the pattern here.

What’s the best tech thing you read recently, and why?

Resilient Web Design by Jeremy Keith
 – Jeremy is an excellent author, and this book is code written exactly as the book states code should be written.

What was the most funny or interesting off-topic link you’ve sent to a friend recently?

On the East Coast, US, it is somehow STILL winter. I sent this to my wife the other day: The is fine meme, but with snow This is fine, indeed! There’s this week’s Interviewsioning, thanks to Tim for sharing the tech he’s most passionate about.

Frequently Asked Questions (FAQs) about Using a Service Worker to Communicate Across Browser Tabs

What is a service worker and how does it function?

A service worker is a type of web worker. It’s a JavaScript file that can control the web page/site it is associated with, intercepting and modifying navigation and resource requests, and caching resources in a very granular fashion to complete offline experiences, or to boost performance.

How can I use a service worker to communicate across browser tabs?

To use a service worker to communicate across browser tabs, you need to register the service worker first. Once registered, you can use the postMessage API to send messages between the service worker and the page. The service worker can then broadcast these messages to all tabs under its control.

How can I handle service worker messages once for multiple tabs?

To handle service worker messages once for multiple tabs, you can use the clients.matchAll() method. This method gets all the clients under the control of the service worker and sends a message to each of them. This way, you can ensure that the message is handled once for each tab.

Can I use service workers for browser-to-browser communication without a server?

No, service workers cannot be used for browser-to-browser communication without a server. Service workers are designed to enable offline experiences and to boost performance by caching resources. They can communicate between the page and the service worker, and across tabs under the control of the service worker, but they cannot communicate directly between browsers.

What is the role of the postMessage API in service workers?

The postMessage API plays a crucial role in service workers. It allows you to send messages between the page and the service worker, and to broadcast messages to all tabs under the control of the service worker. This is how service workers can communicate across browser tabs.

How can I register a service worker?

To register a service worker, you need to use the navigator.serviceWorker.register() method. This method takes two arguments: the first is the path to the service worker file, and the second is an options object. Once the service worker is registered, it can control the page/site.

Can service workers improve the performance of my web page/site?

Yes, service workers can significantly improve the performance of your web page/site. By caching resources in a granular fashion, service workers can provide offline experiences, or boost performance by serving cached resources instead of making network requests.

How can I use service workers to provide offline experiences?

To provide offline experiences with service workers, you need to cache resources. When the service worker intercepts a navigation or resource request, it can respond with a cached resource instead of making a network request. This allows the page/site to function even when offline.

What is the clients.matchAll() method in service workers?

The clients.matchAll() method in service workers is a method that gets all the clients under the control of the service worker. This method is useful for broadcasting messages to all tabs under the control of the service worker.

Can I use service workers with WebRTC?

No, service workers cannot be used with WebRTC. Service workers are designed for offline experiences and performance enhancement, while WebRTC is designed for real-time communication between browsers. These two technologies serve different purposes and cannot be used together.

Adam RobertsAdam Roberts
View Author

Adam is SitePoint's head of newsletters, who mainly writes Versioning, a daily newsletter covering everything new and interesting in the world of web development. He has a beard and will talk to you about beer and Star Wars, if you let him.

Tim EvkoTim Evko
View Author

Tim Evko is a front end web developer from New York, with a passion for responsive web development, Sass, and JavaScript. He lives on coffee, CodePen demos and flannel shirts.

Service Workerssponsoredversioning
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week