Skip to content

Instantly share code, notes, and snippets.

@phatnguyenuit
Last active November 18, 2021 05:20
Show Gist options
  • Select an option

  • Save phatnguyenuit/33d6df2b9872afaaca529f5fbe6c5e2d to your computer and use it in GitHub Desktop.

Select an option

Save phatnguyenuit/33d6df2b9872afaaca529f5fbe6c5e2d to your computer and use it in GitHub Desktop.
Communication in JavaScript with BroadcastChannel
<!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>
<!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>
@phatnguyenuit
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment