Home > OS >  How to detect if code runs in browser in TypeScript?
How to detect if code runs in browser in TypeScript?

Time:08-07

I'm rewriting ES5 JavaScript code into TypeScript and have code like this:

var is_browser = (function() {
    try {
        return this === window;
    } catch (e) {
        return false;
    }
})();

First thing is that I've got an error from TS that this is implicit of type any. But I don't think it matters much because the code will not work since TypeScript is using "use strict" for every file, so this will be undefined.

So what is the proper way to test if JavaScript code runs in the browser?

CodePudding user response:

If you are on the browser window should not be undefined:

var is_browser = typeof window !== 'undefined';

console.log(is_browser)

CodePudding user response:

This solution should always work however the global context is polluted

var is_browser = Object.getPrototypeOf(
  Object.getPrototypeOf(globalThis)
) !== Object.prototype
  • Related