GoogleChromeLabs / GoogleChromeLabs/comlink

Finalizer not invoked automatically with sharedworkers

Open
#673 3 comments 0 reactions 0 assignees View on GitHub
Dominant language
TypeScript
Stars
12.8k
Forks
435
PR merge metrics
No merged PRs in 30d

Description

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

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

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.