DEV Community

loading...
Cover image for How to detect the user's browser with JavaScript

How to detect the user's browser with JavaScript

coderslang profile image Coderslang: Become a Software Engineer Originally published at learn.coderslang.com on ・1 min read

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

Discussion (0)

pic
Editor guide