Skip to content

Instantly share code, notes, and snippets.

@bellbind
Created Jun 5, 2020
Embed
What would you like to do?
[browser]SharedWorker example
<!doctype html>
<html>
<head>
<script type="module">
const worker = new SharedWorker("./worker.js");
worker.port.addEventListener("message", ev => {
document.body.textContent = `connected: ${ev.data}`;
});
worker.port.start(); // spawm connect event to a shared worker
</script>
</head>
<body></body>
</html>
// shared state for each script url
// - reset after all page closed (all ServiceWorker instance terminated)
let counter = 0;
this.addEventListener("connect", ev => {
counter++;
const port = ev.ports[0]; // port of each ServiceWorker instances
port.postMessage(counter);
});
@bellbind
Copy link
Author

bellbind commented Jun 5, 2020

demo: https://gist.githack.com/bellbind/839b32d5d6fb684eb3d2e10fcfc2201c/raw/index.html

(open multiple pages to check these counters)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment