Alex's Slip-box

These are my org-mode notes in sort of Zettelkasten style

SharedWorker

: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)

# 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())

See also https://stackoverflow.com/a/11237259/5974855

# 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

# 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/

# Resources