Sling Academy
Home/JavaScript/Sharing State Between Tabs Using the Broadcast Channel API

Sharing State Between Tabs Using the Broadcast Channel API

Last updated: December 12, 2024

The Broadcast Channel API is a web technology that allows simple communication between different tabs, windows, iframes, or even separate windows of the same origin. This feature is particularly useful for scenarios such as syncing state across different client pages without the need for server interaction.

Introduction to the Broadcast Channel API

Each Broadcast Channel is identified by a string, which means that opening the same channel name in different browsing contexts enables them to communicate.

Let's begin with initializing a broadcast channel:

const channel = new BroadcastChannel('state-sync');

Once you have your channel, you can start sending messages by calling the postMessage method:

channel.postMessage({ key: 'theme', value: 'dark' });

All contexts sharing the same channel will receive messages via an event listener. Here’s how to set one up:

channel.onmessage = (event) => {
  console.log('Received', event.data);
  // Handle the received message
};

Practical Implementation

To demonstrate a practical use of the Broadcast Channel API, let's share user preferences between tabs. We'll create a simple example where two browser tabs can keep their theme preferences synchronized.

First, we create an HTML page with a light and dark theme toggle:


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Theme Sync</title>
</head>
<body>
  <h1>Broadcast Channel Example</h1>
  <button id="toggle-theme">Toggle Theme</button>
  <script src="main.js"></script>
</body>
</html>

Next, in main.js, we add logic to toggle the theme and broadcast this change:


document.getElementById('toggle-theme').onclick = () => {
  const newTheme = document.body.classList.toggle('dark-mode') ? 'dark' : 'light';
  channel.postMessage({ type: 'theme-change', theme: newTheme });
};

channel.onmessage = (event) => {
  if (event.data.type === 'theme-change') {
    document.body.classList.toggle('dark-mode', event.data.theme === 'dark');
  }
};

This example toggles a class on the body element to switch themes and broadcasts the change to all listening contexts.

Tips and Considerations

  • Broadcast Channel only works for browsing contexts from the same origin, enhancing security and privacy.
  • Ensure to close inactive channels using channel.close() to free up resources.
  • The Broadcast Channel API is suitable for small data updates as opposed to large payloads, which might benefit from a different data sharing mechanism.
  • Check browser compatibility, as this is a relatively modern feature supported in most modern browsers but not all versions.

Conclusion

The Broadcast Channel API is a powerful tool for anyone looking to manage state between tabs opened under the same origin. It simplifies inter-browsing context communication, improving user experiences without the complexity of external data storage or server communication. Future web applications will benefit greatly from real-time state synchronization thanks to such browser APIs.

Next Article: Coordinating Multiple Windows and Iframes via the Broadcast Channel

Previous Article: Real-Time Collaboration with Broadcast Channel API in JavaScript

Series: Web APIs – JavaScript Tutorials

JavaScript

You May Also Like

  • Handle Zoom and Scroll with the Visual Viewport API in JavaScript
  • Improve Security Posture Using JavaScript Trusted Types
  • Allow Seamless Device Switching Using JavaScript Remote Playback
  • Update Content Proactively with the JavaScript Push API
  • Simplify Tooltip and Dropdown Creation via JavaScript Popover API
  • Improve User Experience Through Performance Metrics in JavaScript
  • Coordinate Workers Using Channel Messaging in JavaScript
  • Exchange Data Between Iframes Using Channel Messaging in JavaScript
  • Manipulating Time Zones in JavaScript Without Libraries
  • Solving Simple Algebraic Equations Using JavaScript Math Functions
  • Emulating Traditional OOP Constructs with JavaScript Classes
  • Smoothing Out User Flows: Focus Management Techniques in JavaScript
  • Creating Dynamic Timers and Counters with JavaScript
  • Implement Old-School Data Fetching Using JavaScript XMLHttpRequest
  • Load Dynamic Content Without Reloading via XMLHttpRequest in JavaScript
  • Manage Error Handling and Timeouts Using XMLHttpRequest in JavaScript
  • Handle XML and JSON Responses via JavaScript XMLHttpRequest
  • Make AJAX Requests with XMLHttpRequest in JavaScript
  • Customize Subtitle Styling Using JavaScript WebVTT Integration