How to check if the browser is Safari programmatically?

In this article, we review how you can check if the browser is Safari programmatically. We will look at:
isSafari function
navigator.userAgent
isSafari function
I found the following code in the snapdom/src/utils/helpers.js
export function isSafari() {
return /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
}
This function uses a regular expression to determine if the browser is Safari and uses the navigator.userAgent API.
navigator.userAgent
The Navigator.userAgent
read-only property returns the user agent string for the current browser.
This is a test I ran to see this function in action in my Google chrome’s browser.
I found an interesting point in the MDN docs:
Browser identification based on detecting the user agent string is unreliable and is not recommended, as the user agent string is user configurable. For example:
In Firefox, you can change the preference
general.useragent.override
inabout:config
. Some Firefox extensions do that; however, this only changes the HTTP header that gets sent and that is returned bynavigator.userAgent
. There might be other methods that utilize JavaScript code to identify the browser.Opera 6+ allows users to set the browser identification string via a menu.
Learn more about navigator.userAgent.
About me:
Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.
Email: ramu.narasinga@gmail.com
Want to learn from open-source? Solve challenges inspired by open-source projects.
References:
Subscribe to my newsletter
Read articles from Ramu Narasinga directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ramu Narasinga
Ramu Narasinga
I study large open-source projects and create content about their codebase architecture and best practices, sharing it through articles, videos.