GoogleChromeLabs / comlink

Comlink makes WebWorkers enjoyable.
Apache License 2.0
11.3k stars 386 forks source link

Functions in SharedWorker called twice when exposing with port #622

Closed ImmaB closed 1 year ago

ImmaB commented 1 year ago

In the shared worker example an object is exposed by providing the port as second parameter. this results in functions beeing called twice:

// worker.ts
import { expose } from "comlink";
import { WorkerClass } from './worker'

const obj = new WorkerClass();
addEventListener('connect', (event: MessageEvent) => expose(obj, event.ports[0])); // functions beeing called twice
// addEventListener('connect', (event: MessageEvent) => expose(obj)); // functions working as expected

// worker-class.ts
export class WorkerClass {

    async func() {
        console.log('test');
    }
}

// test.ts
import { wrap } from "comlink";
import { WorkerClass } from './worker'

const sharedWorker = wrap<WorkerClass>(new SharedWorker(new URL('./worker', import.meta.url), { type: 'module', name: 'test' }).port);
sharedWorker.func()

// result
test
test
ImmaB commented 1 year ago

Nevermind. Appearently the issue was somewhere else. Unfortunally I haven't figured out yet what it was