GoogleChromeLabs / comlink

Comlink makes WebWorkers enjoyable.
Apache License 2.0
11k stars 382 forks source link

Replace `self` with `globalThis` for use in Worklets #617

Closed mwszekely closed 1 year ago

mwszekely commented 1 year ago

This is to fix runtime errors that occur when Comlink is used in a Worklet because self doesn't exist there.

I ran into a problem suddenly using Comlink in an AudioWorklet getting runtime errors on line 425 because it's looking for the existence of a property on the self object -- since self isn't available in Worklets I just replaced it with globalThis and it resolved the issue.

(The suddenness of it was just an unrelated tree-shaking issue -- if expose is optimized out by whatever bundler you're using then the Worklet never inspects self, and never crashes. It's possible that this issue could suddenly affect others if they change how they use Comlink in their projects, even without calling expose) I completely misunderstood the timing and presumably need to get some sleep 🙃

benjamind commented 1 year ago

Nice work thank you I believe this should also fix #616. I'll get a nodejs test written for this tomorrow and get a patch release out.

Kasthooriraja commented 11 months ago

Replacing **self** with **globalThis** creates problems in older versions.

var getGlobal = function () { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } throw new Error('unable to locate global object'); };

Selecting the available global object using the above function will resolve this issue.