|
| 1 | +<!doctype html> |
| 2 | +<html lang="en"> |
| 3 | +<head> |
| 4 | + <meta charset="utf-8" /> |
| 5 | + <title> |
| 6 | + Broadcast Channel API Frame |
| 7 | + </title> |
| 8 | + <link rel="stylesheet" type="text/css" href="./main.css" /> |
| 9 | +</head> |
| 10 | +<body class="frame-body"> |
| 11 | + |
| 12 | + <!-- |
| 13 | + I'll follow the mouse location within each frame. Or I'll move according to the |
| 14 | + Broadcast API messages sent from frame-to-frame. |
| 15 | + --> |
| 16 | + <mark class="laser"> |
| 17 | + <!-- Pew pew pew! --> |
| 18 | + </mark> |
| 19 | + |
| 20 | + <script type="text/javascript"> |
| 21 | + |
| 22 | + var laser = document.querySelector( ".laser" ); |
| 23 | + |
| 24 | + // Create a named channel that all the frames can bind-to for sending and |
| 25 | + // receiving messages. |
| 26 | + var channel = new BroadcastChannel( "pewpew" ); |
| 27 | + |
| 28 | + // As the mouse moves, broadcast {x,y} coordinates to other frames for mirroring. |
| 29 | + window.addEventListener( "mousemove", ( event ) => { |
| 30 | + |
| 31 | + // Note: the message is automatically serialized using the structured clone |
| 32 | + // algorithm. As such, we can pass complex messages (within reason) and not |
| 33 | + // have to worry about serializing the data. Winning! |
| 34 | + channel.postMessage({ |
| 35 | + type: "lasermove", |
| 36 | + clientX: event.clientX, |
| 37 | + clientY: event.clientY, |
| 38 | + }); |
| 39 | + |
| 40 | + // Note: a broadcast context subscriber will NOT RECIEVE ITS OWN messages. |
| 41 | + // As such, we don't have to worry about adding logic to ignore reflected |
| 42 | + // messages. But it means that we also have to update the laser position |
| 43 | + // locally to the broadcasting window. |
| 44 | + moveLaser( event.clientX, event.clientY ); |
| 45 | + |
| 46 | + }); |
| 47 | + |
| 48 | + // Listen for broadcast message events. |
| 49 | + channel.addEventListener( "message", ( event ) => { |
| 50 | + |
| 51 | + // The broadcast message data is transparently deserialized using structured |
| 52 | + // clone algorithm and is presented in its original format. That said, we |
| 53 | + // might receive any number of messages (even on a named channel). As such, |
| 54 | + // I'm including a differentiator (type) to focus on relevant messages. This |
| 55 | + // is merely a convention, not a requirement. |
| 56 | + if ( event.data.type === "lasermove" ) { |
| 57 | + |
| 58 | + moveLaser( event.data.clientX, event.data.clientY ); |
| 59 | + |
| 60 | + } |
| 61 | + |
| 62 | + }); |
| 63 | + |
| 64 | + // I move the laser point to the given location. |
| 65 | + function moveLaser( left, top ) { |
| 66 | + |
| 67 | + laser.style.left = `${ left }px`; |
| 68 | + laser.style.top = `${ top }px`; |
| 69 | + |
| 70 | + } |
| 71 | + |
| 72 | + </script> |
| 73 | + |
| 74 | +</body> |
| 75 | +</html> |
0 commit comments