Skip to content

Instantly share code, notes, and snippets.

@bellbind
Created June 5, 2020 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bellbind/839b32d5d6fb684eb3d2e10fcfc2201c to your computer and use it in GitHub Desktop.
Save bellbind/839b32d5d6fb684eb3d2e10fcfc2201c to your computer and use it in GitHub Desktop.
[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