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
}
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
}
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
}
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
}
Top comments (0)