SharedWorker
Table of Contents
:ID: D8401E83-5AB9-4736-AA4D-224A902DDEE5
# Key points
- Can be accessed from difference browsing contexts (windows/tabs iframes, workers) within the same origin (protocol, host and port)
- Inherits properties and methods (eg,
addEventListener()
) from EventTarget - Messages can be sent and received over the
port
property (ie,onmessage
,postMessage
) - The JS code running in SharedWorkers do not have access to cookies. They have their own scope (see self below)
# Debugging
# Chrome
Visit chrome://inspect/#workers
. A SharedWorker context will have its own
dev tools.
# Firefox
Visit about:debugging#/runtime/this-firefox
# self
The self
keyword in a SharedWorker context refers to the
SharedWorkerGlobalScope. There is no window
object here (ie, use
self.setInterval()
)
# Singletons
If you need to share a singleton class across browser contexts/windows (ie a
WebSocket connection or something that has some persistent state/connection),
attach it to the SharedWorkerGlobalScope
(ie self
) object and check if it
already exists before attempting to instantiate it again (ie when opening
another browser tab). If you just assign it to a const
, then you’ll end up
re-instantiating the thing.
// shared-worker.ts import SuperAwesomeThing from './SuperAwesomeThing'; // self is that SharedWorkerGlobalScope const swgs = self as any; swgs.onconnect = function(e: MessageEvent) { const port = e.ports[0]; if (!swgs.superAwesomeThing) { swgs.superAwesomeThing = new SuperAwesomeThing(); swgs.superAwesomeThing.init(); } };
# Webpack stuff
# For Webpack v4
Use worker-loader
- I could not get this to work consistently using a webpackChain rule. I had to use an inline loader.
- See also https://github.com/dynamind/minimal-vue-worker#webpack-loader-configuration
# For Webpack v5
You don’t need worker-loader. Webpack v5 has built-in support for workers. See also https://webpack.js.org/guides/web-workers/
# Vite
# Resources
- https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker
- https://github.com/mdn/simple-shared-worker This demonstrates using a shared worker to perform simply multiplication operations for two browsing contexts.