Communicating Display Settings to Another Tab of the Same Site: Basics of BroadcastChannel

プログラミング・Web開発カテゴリを表すパンダのイラスト Programming / Web Development

About this articleThis article was created using an automated generation workflow leveraging generative AI.

Verification status: Checked HTML Standard, MDN, and educational code / Live browser operation is unverified.The transmission and reception conditions of BroadcastChannel, message duplication, the fact that the sender itself does not receive the message event, and the role of close() were confirmed using official documentation. Transmission between two channels was verified using Node.js BroadcastChannel, and consistency with JavaScript syntax, HTML elements, and the README was also inspected. We have not performed a live inspection of displaying GitHub Pages in a browser and interacting with screen changes across different tabs.

Communicating Display Settings to Another Tab of the Same Site: Basics of BroadcastChannel

If you keep a settings screen open in two tabs, changing the theme in one leaves the other displaying the old theme. By using the browser-standard BroadcastChannel API, pages meeting the same conditions can exchange small messages. Using a tutorial where light/dark strings are sent to change card colors, we will examine the differences between senders and receivers, the range of message delivery, and why values do not persist in tabs opened later. This is intended for JavaScript beginners who want to build settings synchronization or screen update notifications.

Live Demo: Trying BroadcastChannel across Two Tabs

First, try it with two tabs

  1. Open the live demo above, and then open the same page in another tab.

  2. Click "Run" on both pages. Once the card and "Waiting for message" appear, both are joined to a channel with the same name.

  3. Leave the input field on one side as its default value of dark and click "Send".

  4. The sender's card turns a darker color, and the other side also receives the message and turns dark.

  5. Change the input to light and send it again. Both return to a bright color.

  6. Close one tab and send from the remaining one. The sender's card changes, but there is no recipient.

The default value is dark. The tutorial ensures the values are accurately dark select a dark color scheme only when , and treat it as light otherwise. Therefore DARK , blank fields, and dark with surrounding whitespace will use a light color scheme. Please observe by changing this condition as well.

InputSender sideReceiver side
darkUpdate send button processing to dark colorReceive message event and update to dark color
lightUpdate to light colorReceive message event and update to light color
DARK– Blank, etc.light Update as light Update as

"Run" is the operation to join the channel, and "Send" is the operation to post the theme string. Even if you send before setting the second tab to wait for reception, past messages will not be saved. Be sure to launch both first before sending.

What is happening

The tutorial processing can be simplified as follows.

const channel = new BroadcastChannel('DailyCode53');
channel.onmessage = event => updatePreview(event.data);

function sendTheme(theme) {
  updatePreview(theme);       // 送信元自身の画面を更新
  channel.postMessage(theme); // ほかの参加者へ通知
}

// ページを片付けるとき
channel.close();

new BroadcastChannel(name) joins a named channel. When another tab or Worker from the same origin joins with the same name and calls postMessage() , a message event occurs on the receiving side. Data is transmitted via structured cloning. This tutorial sends a simple string.

In two tabs joined to a channel with the same name, messages posted in one are received by the other.

flowchart LR
  A["タブA(送信側)"] -->|"postMessage(theme)"| C["DailyCode53"]
  C -->|"messageイベント"| B["タブB(受信側)"]

The BroadcastChannel object used for transmission does not receive its own message event. Therefore, the tutorial updates its own card during the transmission process and then notifies the other party using postMessage(). The receiving tab updates its card in the onmessage process. The point to observe is that the sender and receiver change via different paths.

When you click "Run" in the tutorial again, the shared runner cleans up the previous process before starting a new one, and close() is called on the old channel. After closing, that object no longer receives new messages. Even when retrying the experiment within the page, you must close the channel you are finished with.

How far do messages reach?

The basic requirement isthe same origin. An origin is the combination of scheme, host, and port. Since the live demo's #live merely indicates the position within the page, two tabs opened to the same URL share the same origin. On the other hand, http and https, different hosts, and local versus public versions on different ports constitute different origins and do not receive messages from each other.

The HTML Standard restricts delivery targets to BroadcastChannels with the same storage key as the sender. In other words, even if you use the same URL, communication is not always guaranteed depending on the embedding context. Start by trying the method of opening the same public URL in normal top-level tabs.

Channel names are not secret keys. Any script that opens a channel with the same name under the same origin can participate. Do not use it in designs that transmit usernames, authentication tokens, personal information, or business secrets. BroadcastChannel is also not a storage location, authentication mechanism, or delivery confirmation system.

Separating "Notification" and "Storage" in Production

BroadcastChannel is well-suited for notifying tabs open to the same site about changes, such as "settings have changed" or "please reload the list." For example, using {type: 'theme-changed', value: 'dark'} to define small messages containing event types makes it easier for receivers to make decisions.

However, there is no feature to replay messages later when no receivers are present. To display initial values in new tabs as well, retrieve current values from the server or an appropriate storage area at startup, and then notify subsequent changes via BroadcastChannel. Notifications that could lead to business data inconsistencies require a separate design involving delivery confirmation and re-fetching.

You can use a channel with the same name across different page paths as long as the origin is the same. Define the channel name and message format within your application, and design it so that updates upon receipt do not repost the same message. The reception handler in this tutorial only updates the display and does not retransmit.

Troubleshooting

  • The other party's card does not change: Verify that both sides clicked "Execute" and sent the message after entering the waiting state for reception. Past posts are not stored.

  • The color scheme does not match: Verify whether the input value matches dark or light exactly. Anything else is treated as light.

  • Only one side does not receive messages: Verify that both were opened using the same public URL and origin, and that the channel name is DailyCode53. Mixing localhost and GitHub Pages will prevent messages from being delivered.

  • API unavailable / Execution error: Test on a top-level page in a current browser rather than an outdated browser or a restricted embedded view. Cross-browser visual verification has not been performed for this article.

  • Diagrams are not rendered: Diagrams load Mermaid from an external CDN. Even if network access is blocked, you can follow the process using the text explanations and the HTML diagram source.

Conclusion

BroadcastChannel is a standard API for delivering short notifications to browser contexts that meet the same conditions. The sender updates its own screen directly, and other participants update via the message event. Values sent before joining are not retained, and closing the channel stops that object from receiving messages.

While convenient for cross-tab settings or reload notifications, it is not a substitute for persistence, authentication, transmission of sensitive information, or reliable enterprise message delivery. Decide in advance what to send and how to recover if delivery fails.

Source

Document information

Article title
Communicating Display Settings to Another Tab of the Same Site: Basics of BroadcastChannel
Published
Updated
Source
https://papanda925.com/?p=19038&lang=en

License: Text and original figures for which this site holds the relevant rights are available under CC BY 4.0 , unless otherwise noted. This article may include content created or edited with generative AI. If code has a separate license notice or a linked GitHub repository license, that license takes precedence for the code. Quotations, third-party materials, images, and trademarks are excluded from this license. Usage policy

Copied title and URL