How to detect if code runs in browser in TypeScript?

778 Views Asked by At

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?

2

There are 2 best solutions below

5
MauricioRobayo On

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

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

console.log(is_browser)

1
Ahmed Lazhar On

This solution should always work however the global context is polluted

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