UNPKG

messageport-observable

Version:

This provides some magic wrappers for [MessagePort][1] objects and things that resemble them (windows/iframes, workers, etc.). The wrapped objects still have the same API as MessagePorts, but also have some additional features.

44 lines (36 loc) 1.01 kB
<!doctype html> <html> <head> <script src="messageport-observable.js"></script> </head> <body> <h1>In the iframe</h1> <script> const wrapWindow = MessagePortObservable.wrapWindow; const wrapPort = MessagePortObservable.wrapPort; const windowPort = wrapWindow(window); const parentPort = wrapWindow(window.parent); parentPort.postMessageWithReply('test').subscribe({ next(x) { console.log('next', x); } }); windowPort .filter(event => event.data instanceof Int32Array) .subscribe(event => { console.log('got array:', event.data); }); const sharedWorker = new SharedWorker('increment.js'); const swPort = wrapPort(sharedWorker.port); for (let i = 0; i < 10; i++) { const sub = swPort.postMessageWithReply('inc') .subscribe({ next(x) { console.log('increment ' + i + ' via iframe:', x.data); sub.unsubscribe(); } }); } </script> </body> </html>