DEV Community

Cover image for How to detect the user's browser with JavaScript
Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer

Posted on • Originally published at learn.coderslang.com on

How to detect the user's browser with JavaScript

You can check which browser the user is running using plain JavaScript.

To detect the user browser, you need to analyze the property userAgent of the object navigator.

If you want to do something specific, for example, provide a polifill for a regular expression when the browser is Safari, you do this:

if (navigator.userAgent.includes('Safari')) {
  // the user is running Safari
  // do something useful
}
Enter fullscreen mode Exit fullscreen mode

On the other hand, if you want to do something for all browsers but Chrome, you check if the userAgent doesn’t include your search string:

if (!navigator.userAgent.includes('Chrome')) {
  // the user is NOT running Chrome
}
Enter fullscreen mode Exit fullscreen mode

Using indexOf and toLowerCase

As an alternative to includes you can also use the indexOf method. If it returns -1, this means that the search string wasn’t found.

if (navigator.userAgent.indexOf('Chrome') < 0) {
  // the user is NOT running Chrome
}
Enter fullscreen mode Exit fullscreen mode

If you’re not sure how exactly the user browser is spelled, you can try using the toLowerCase function on the navigator.userAgent.

if (navigator.userAgent.toLowerCase().indexOf('chrome') < 0) {
  // the user is NOT running Chrome
}
Enter fullscreen mode Exit fullscreen mode

Learn Full Stack JavaScript

Top comments (0)