How to detect Safari browser in JavaScript?

Detecting specific browser by JavaScript can be very useful to fix some browser-specific bugs or issues. There are some CSS tricks to achieve this, but specific browser can be also detected in other ways. In this article, we will focus on detecting Safari browser by JavaScript code.

How to detect Safari browser in JavaScript?

To detect Safari browser we can use below code snippet:

const isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);

The above regex is looking for “safari” string in navigator.userAgent but it also excludes “chrome” and “android” strings. Thanks to that it excluded Chrome, Edge and Android browsers that contain “safari” string in their names.

Why are all browsers on iPhone are recognized as Safari?

In fact, all browsers on iPhone (also on iPad) are just wrappers for Safari. Using the above code snippet in Chrome browser on iOS can be confusing because each browser will be detected as Safari.

How to test this code snipped in Chrome?

It is worth noticing, that Chrome’s built-in devices emulator, can emulate different iOS devices (for example iPhone XR or iPad Air). Emulator also changes navigator.userAgent value and thanks to that above piece of code can be tested in Chrome browser.

Leave a Reply

Your email address will not be published. Required fields are marked *