-
-
Save barrosfilipe/aebc2e75552e21b490c736dd191083cd 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 | |
| */ | |
| /** | |
| * Broadcast channel functionality | |
| */ | |
| 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) | |
| }) | |
| } | |
| /** | |
| * Create all windows | |
| */ | |
| 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 params = [ | |
| `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`, | |
| ] | |
| // set window parameters on load | |
| const win = window.open('', `window_${x}_${y}`, params.join(',')) | |
| win.addEventListener('load', () => { | |
| // setup broadcast channel | |
| init(win) | |
| // setup text | |
| win.document.body.innerHTML = 'Click to change color + Esc to close all' | |
| // setup window closing | |
| windows.push(win) | |
| // setup window close | |
| win.document.addEventListener('keydown', (event) => { | |
| if (event.key.toLowerCase().includes('esc')) { | |
| windows.forEach(win => { | |
| win.close() | |
| }) | |
| } | |
| }) | |
| }) | |
| } | |
| } | |
| } | |
| setup(5, 3) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
