Skip to content

Finalizer not invoked automatically with sharedworkers #673

@lauri865

Description

@lauri865

It doesn't seem like finalizer gets invoked for sharedworkers. I have the following worker, and the finalizer never gets invoked automatically.

declare const self: SharedWorkerGlobalScope;
import * as Comlink from "comlink";

export const api = {
  getToken: (token: string) => {
    return token;
  },
};

let id = 0;
self.addEventListener("connect", (event: MessageEvent): void => {
  id++;
  const tabId = id;
  console.log("tab connected", tabId);
  const port = event.ports[0];

  Comlink.expose(
    {
      ...api,
      [Comlink.finalizer]: () => {
        console.log("tab closed", tabId);
      },
    },
    port,
  );
});

It does work when I invoke it manually on beforeunload:

addEventListener("beforeunload", () => {
  instance[Comlink.releaseProxy]();
});

I also tried to wrap the port in weakRef myself before passing it to Comlink.expose, but no luck either. Was following this post: https://brightinventions.pl/blog/sharing-websocket-connections-between-browser-tabs-and-windows/

Environment:
MacOS 15
Chrome Version 130.0.6723.117 (Official Build) (arm64)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions