Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

302
Views
How to detect if code runs in browser in TypeScript?

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?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

This solution should always work however the global context is polluted

var is_browser = Object.getPrototypeOf(
  Object.getPrototypeOf(globalThis)
) !== Object.prototype
about 4 years ago · Juan Pablo Isaza Report

0

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

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

console.log(is_browser)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!