When developing web applications, sometimes communication between different browser tabs is required. For example, you might need to make changes in one tab to be reflected in another tab, or you might need to send messages to other tabs when the user performs certain actions in one tab. In order to achieve such cross-tab communication, we can use the Broadcast Channel API provided by HTML5.
Implementation steps
First, we need to create two files: an HTML file and a JavaScript file.
HTML file:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <script type="text/javascript" src="./"></script> </head> <body> <button >Send a message</button> <script type="text/javascript"> var btn = ('btn'); = function() { sendMsg('test', 'hello'); } listenMsg(function(msg) { (msg); }) </script> </body> </html>
JavaScript File():
const channel = new BroadcastChannel('cross-tab-msg'); function sendMsg(type, msg) { ({type, msg}); } function listenMsg(callback) { ('message', e => { callback && callback(); }); }
In the HTML file, we created a button and added a click event handler to it. When the user clicks the button, we callsendMsg
The function sends a message. At the same time, we also calllistenMsg
Functions to listen for messages from other tabs and print them in the console.
In the JavaScript file, we create a name calledcross-tab-msg
The new Broadcast Channel and defines two functions:sendMsg
Used to send messages,listenMsg
Used to listen for messages. When a message is received,listenMsg
The function triggers the callback function and passes the received message to the callback function as a parameter.
How to use
To communicate between different tabs, simply load the same HTML and JavaScript files in those tabs. When you click the button to send a message in one tab, the listeners in other tabs will receive the message and perform the corresponding operation.
in conclusion
By using the Broadcast Channel API, we can easily implement cross-tab communication, making it easy to messaging and data sharing between different tabs. This provides more possibilities and flexibility for developing complex web applications.
Method supplement
<!-- --> <script> if(!('a')){ ('a',1) }else{ var sum = ('a') ('a', +sum + 1) } </script> <!-- --> <script> ('storage', (e) => (e)) </script>
('message', 'I am the value of sessionStorage'); // Trigger custom events to notify other tabsvar event = new Event('sessionStorageUpdated'); (event); ('storage', function(event) { if ( === 'message') { var message = ('message'); ('message:', message); } }); // Listen to custom events to detect updates to `sessionStorage`('sessionStorageUpdated', function() { var message = ('message'); ('message:', message); });
<!-- --> <body> <button class="pop">A new window pops up</button> <button class="button">Send data</button> <script> const pop = ('.pop'); const button = ('.button'); let index = 0; let opener = null; ('click', () => { opener = ( '', '123', 'height=600,width=600,top=20,resizeable=yes' ); }); ('click', () => { const data = { value: `moment ${index++}`, }; (data, '*'); }); </script> </body> <!-- --> <body> <div>postMessage </div> <script> ("message", (e) => { (); }); </script> </body>
<!-- --> <script> let index = 0; const worker = new SharedWorker(""); setInterval(() => { (`moment ${index++}`); }, 1000); </script> <!-- --> <script> const worker = new SharedWorker(""); (); setInterval(() => { ("php is the best language in the world"); }, 1000); = function (e) { if () { (); } }; </script>
Create a file and write the following code:
let data = ""; = (e) => { const port = [0]; = function (e) { if ( === "php is the best language in the world") { (data); data = ""; } else { data = ; } }; };
This is the article about JavaScript using Broadcast Channel to implement front-end cross-tab communication. This is the end of this article. For more related JavaScript Broadcast Channel cross-tab communication content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!