Last active
September 11, 2022 20:14
-
-
Save Ivannnnn/caa6c878e74d1c02cf7bd8845970e349 to your computer and use it in GitHub Desktop.
This file contains 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
async function connectToWindow(listener) { | |
const port = await new Promise((resolve) => { | |
const handleMessage = (e) => { | |
if (e.data.type === "__messaging_connect__") { | |
resolve(e.ports[0]); | |
self.removeEventListener("message", handleMessage); | |
} | |
}; | |
self.addEventListener("message", handleMessage); | |
}); | |
port.onmessage = (e) => listener(e.data); | |
return (...args) => port.postMessage(...args); | |
} | |
async function connectToWorker(listener) { | |
const { port1, port2 } = new MessageChannel(); | |
const { active: sw } = await navigator.serviceWorker.ready; | |
sw.postMessage({ type: "__messaging_connect__" }, [port2]); | |
port1.onmessage = (e) => listener(e.data); | |
return (...args) => port1.postMessage(...args); | |
} | |
/* USAGE: | |
const sendToWorker = await connectToWorker(function workerListener() { | |
}) | |
const sendToWindow = await connectToWindow(function windowListener() { | |
}) | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment