-
-
Save MrZhouZh/a8a6d248f6908cefcf7ad28d32971891 to your computer and use it in GitHub Desktop.
Example of using BroadcastChannel to communicate with pages in the same domain
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
/** | |
* 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('click', (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