pull down to refresh

In most modern browsers, you have the option to create a SharedWorker, a type of web worker that, as the name suggests, can be shared across multiple instances of the same page.
For example, imagine you have a Nostr client open in multiple tabs. Instead of each tab acting as a separate client, connecting to relays and listening for events independently, you can use a single shared worker that maintains the connection in the background and updates all tabs as needed.
The problem is that SharedWorker is not supported by every browser.
To work around this issue, I built sharedexecutor-js, a small library that wraps SharedWorker. When SharedWorker isn’t available, it emulates the same behavior by spawning standalone workers connected with a Broadcast Channel, one of the workers is elected as the master while the others proxy their calls through it, effectively acting as a browser-side RPC system (no server needed). If the master dies for any reason, another worker is automatically elected to take its place.
If you want to try it out, i made a small demo that lets you paint a canvas across iframes and tabs: https://rblb.it/sharedexecutor-js/ .
26 sats \ 1 reply \ @k00b 15h
I've come across the SharedWorker docs a few times, hoping to find a problem that needed them. Back in 2022 I was thinking of using them to store a clientside nostr relay that would act like a cache (I think this is what most browser clients do now).
How are you doing master election?
reply
105 sats \ 0 replies \ @rblb OP 13h
think this is what most browser clients do now
in my experience, current clients just spawn connections for each tab and they use some form of local storage for caching. Having a single shared worker that has one pool, one set of connections and persistent subscriptions would make them feel more like "normal" websites imo.
How are you doing master election?
very simple approach: each worker gets an id when it spawns, they periodically send heartbeat messages to each other via a BroadcastChannel. The active worker with lowest id becomes the master.
reply