Skip to content

Instantly share code, notes, and snippets.

@SwapnilSoni1999
Forked from davestewart/broadcast-channel.md
Created November 24, 2023 08:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SwapnilSoni1999/5ee33ee31a6bb5bcdc5455376fbc002d to your computer and use it in GitHub Desktop.
Save SwapnilSoni1999/5ee33ee31a6bb5bcdc5455376fbc002d to your computer and use it in GitHub Desktop.
Example of using BroadcastChannel to communicate with pages in the same domain
/**
* Instructions (updated to use BroadcastChannel)
*
* - open the JS console and run this code
* - if nothing happens, enable popups in the browser URL bar
* - wait for windows to load
* - click on any of the open windows to see them all change color
* - hit Esc to close all windows
*/
/**
* Setup broadcast channel on each window
*/
function init (win) {
// utility functions
const getColor = () => {
return '#' + Math.floor(Math.random() * Math.pow(255, 3)).toString(16)
}
const setColor = (color) => {
win.document.body.style.background = color
}
// set up channel
const bc = new BroadcastChannel('colors')
// receive events
bc.addEventListener('message', (event) => {
setColor(event.data)
})
// send events
win.document.addEventListener('mousedown', (event) => {
const color = getColor()
setColor(color)
bc.postMessage(color)
})
}
/**
* Setup window layout
*/
function setup (cx, cy) {
// screen bounds
const s = {
w: screen.availWidth,
h: screen.availHeight,
l: screen.availLeft,
t: screen.availTop,
}
// window layout
const w = Math.floor(s.w / cx)
const h = Math.floor(s.h / cy)
// create windows
const windows = []
for (let y = 0; y < cy; y++) {
for (let x = 0; x < cx; x++) {
// create window
const win = window.open('', `window_${x}_${y}`, [
`width=${w}`,
`height=${h - 60}`,
`left=${s.l + (w * x)}`,
`top=${s.t + (h * y)}`,
`scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no`,
].join(','))
// implement functionality on load
win.addEventListener('load', () => {
// setup broadcast channel
init(win)
// set window text
win.document.body.innerHTML = '<pre style="padding: .5rem; line-height: 1.7">Click: Change color<br>Esc: Close windows</pre>'
// setup window closing
windows.push(win)
win.document.addEventListener('keydown', (event) => {
if (event.key.toLowerCase().includes('esc')) {
windows.forEach(win => {
win.close()
})
}
})
})
}
}
}
// run code
setup(5, 3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment