Skip to content

Cannot be run in any Web Workers #122

@austintheriotgl

Description

@austintheriotgl

Hi! I noticed that this library wraps the initialization call like so:

}(typeof window !== 'undefined' ? window : global));

This works on the UI thread on the web, and I beileve this also works in Node due to the presence of the global keyword, but this code throws an error when trying to run in any type of Web Worker, because there is no window in the global scope.

One easy fix here could be to just use the globalThis keyword, as the intent for that keyword is to standardize access of the global scope across many different environments. Here's a little writeup from MDN:

Historically, accessing the global object has required different syntax in different JavaScript environments. On the web you can use window, self, or frames - but in Web Workers only self will work. In Node.js none of these work, and you must instead use global. The this keyword could be used inside functions running in non–strict mode, but this will be undefined in modules and inside functions running in strict mode. You can also use Function('return this')(), but environments that disable eval(), like CSP in browsers, prevent use of Function in this way.

The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in. To help you remember the name, just remember that in global scope the this value is globalThis.

In the browser, this just returns the Window object like so:

Image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions