Skip to content

Instantly share code, notes, and snippets.

@BenLumenDigital
Created November 24, 2023 09:35
Show Gist options
  • Save BenLumenDigital/1548331a4d8c4839ec015c30a04e87a6 to your computer and use it in GitHub Desktop.
Save BenLumenDigital/1548331a4d8c4839ec015c30a04e87a6 to your computer and use it in GitHub Desktop.
Browser multi-window communication. Simple as it comes.
<html>
<body>
<div id="debug"></div>
</body>
<script>
// BroadcastChannel is a browser feature, it allows communication between windows
// Find out more here: https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API
const broadcastChannel = new BroadcastChannel("com.lumen.basketball");
// Create an Object to store Window properties
// We just store window size, position, and a unique ID
var thisWindow = {id: new Date().getTime(), top:0, left:0, width:0, height:0};
// An array to hold other Window Objects
var otherWindows = {};
// Called on every frame update
function update(){
// Update our Window Object incase our window has moved or changed size
thisWindow.top = window.screenY;
thisWindow.left = window.screenX;
thisWindow.width = window.innerWidth;
thisWindow.height = window.innerHeight;
// Broadcast our Window Object to anyone else who might be listening
broadcastChannel.postMessage(thisWindow);
// Ugly debug stuff...
var thisDebugString = thisWindow.id + ', ' + thisWindow.top + ', ' + thisWindow.left + ', ' + thisWindow.width + ', ' + thisWindow.height + '<br>';
for (var otherWindowId in otherWindows) {
const otherWindow = otherWindows[otherWindowId];
thisDebugString += otherWindow.id + ', ' + otherWindow.top + ', ' + otherWindow.left + ', ' + otherWindow.width + ', ' + otherWindow.height + '<br>';
}
document.getElementById('debug').innerHTML = thisDebugString;
requestAnimationFrame(update);
}
// We got a message from someone, update our Window Objects array
broadcastChannel.onmessage = (event) => {
const otherWindow = event.data;
otherWindows[otherWindow.id] = otherWindow;
};
// Kick off the loop
requestAnimationFrame(update);
</script>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment