Last active
November 18, 2021 05:20
-
-
Save phatnguyenuit/33d6df2b9872afaaca529f5fbe6c5e2d to your computer and use it in GitHub Desktop.
Communication in JavaScript with BroadcastChannel
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>Tab 1</title> | |
| </head> | |
| <body> | |
| <button>Send broadcast message</button> | |
| <script> | |
| const button = document.querySelector("button"); | |
| const channel = new BroadcastChannel("fast-channel"); | |
| button.addEventListener("click", () => { | |
| channel.postMessage({ | |
| type: "hello world", | |
| payload: { | |
| hello: "world!", | |
| }, | |
| }); | |
| }); | |
| </script> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta http-equiv="X-UA-Compatible" content="IE=edge" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>Tab 2</title> | |
| </head> | |
| <body> | |
| <p>Receive broadcast message</p> | |
| <div id="events"></div> | |
| <script> | |
| const channel = new BroadcastChannel("fast-channel"); | |
| const events = document.getElementById("events"); | |
| channel.addEventListener("message", (event) => { | |
| console.log(event.data); | |
| events.innerHTML += ` | |
| <p>event data: ${JSON.stringify(event.data, null, 2)}</p> | |
| `; | |
| }); | |
| </script> | |
| </body> | |
| </html> |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
References: https://developer.mozilla.org/en-US/docs/Web/API/BroadcastChannel