Skip to content

Instantly share code, notes, and snippets.

@abdellatifLabr
Forked from davestewart/broadcast-channel.md
Created November 25, 2023 10:49
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save abdellatifLabr/c617236c9cdce6d6eabdeffccdb27a57 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
*
* My stuff:
*
* - https://davestewart.co.uk
* - https://controlspace.app
*/
/**
* Helper class to get / set colors
*/
const Color = {
get () {
return '#' + Math.floor(Math.random() * Math.pow(255, 3)).toString(16).padStart(6, 0)
},
set (win, color) {
win.document.body.style.background = color
win.document.body.style.color = 'black'
},
}
/**
* Setup broadcast channel on each window
*/
function initWindow (win) {
// set up channel
const bc = new BroadcastChannel('colors')
// send channel events
const exec = async () => {
const color = Color.get()
await bc.postMessage(color)
win.document.querySelector('pre').innerHTML += `<div style="color:${color}">${color}<div>`
}
// wire up user interaction
win.addEventListener('focus', exec)
win.addEventListener('mousedown', exec)
// receive channel events + utilize data
bc.addEventListener('message', (event) => {
Color.set(win, event.data)
})
}
/**
* Setup window layout
*/
function setup (cx = 6, cy = 3, gap = 30) {
// screen bounds
const s = {
w: screen.availWidth,
h: screen.availHeight,
l: screen.availLeft,
t: screen.availTop,
}
// window layout
const gx = (cx + 1) * gap
const gy = (cy + 1) * gap
const w = Math.floor((s.w - gx) / cx)
const h = Math.floor((s.h - gy) / 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) + (gap * x) + gap}`,
`top=${s.t + (h * y) + (gap * y) + gap}`,
`scrollbars=no,resizable=no,status=no,location=no,toolbar=no,menubar=no`,
].join(','))
// implement functionality on load
win.addEventListener('load', () => {
// setup broadcast channel
initWindow(win)
// set window text
win.document.body.innerHTML = '<pre style="padding: .5rem; line-height: 1.7; user-select: none">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()
})
}
})
})
}
}
}
// create windows
setup()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment