node.jsnpmwindow-object

How to access window in a node package


These days, many npm/node packages are not only used on node.js, but also on the web, using tools such as webpack or rollup.

I am creating a package that I would like to be used on the web. How do I access the global window object that the browser makes available?

Is there some package that will expose this object to me?


Solution

  • When running in a browser, the global variable window is present and you just use it. You don't have to do anything to make it present or usable if you are running the code in the appropriate environment. If running the code in node.js, then the window variable will not be present.

    If your code is designed only for one environment, then it is generally just up to the programmer to only attempt to use it in the appropriate environment and you would document what environment it requires.

    If you wanted to inform a developer that they were using it wrongly, you could do something like this in your top level code:

    if (typeof window !== "object" && typeof window.document !== "object") {
        // does not appear to be a browser environment
        throw new Error("This code is only meant to run in a browser environment");
    }
    

    A developer could bypass these checks either by defining both window and window.document in the global environment before loading your code or by editing this check out of your code, but at that point, they are on their own anyway.