1

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?

David Callanan
  • 5,601
  • 7
  • 63
  • 105
  • 1
    If you're running the code in a browser, then window is JUST there as a global. You just reference it directly as in `window.onload = function() {...}`. If you are running the code in node.js, `window` is not present as it only exists in a browser environment. – jfriend00 Feb 09 '20 at 03:43
  • @jfriend00 Ah, I see, that makes sense. So I just use `window`, and it's up to the package user to ensure they are running it in the browser? – David Callanan Feb 09 '20 at 12:02
  • @jfriend00 Or is there a way of ensuring that the package is only installed and used in a browser environment? – David Callanan Feb 09 '20 at 12:06

1 Answers1

2

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.

jfriend00
  • 683,504
  • 96
  • 985
  • 979