How to find the user’s browser name using JavaScript
There are times we need to know the user's browser in order to display some specific features, such as ApplePay in the Safari browser.
What is a user browser?
A user browser is a software application that lets users access web pages on the internet. It is commonly used to access information online. Examples of browsers include Google Chrome, Safari, Firefox, Microsoft Edge, Opera, and Internet Explorer.
Steps in detecting a user's browser
To detect a user browser, we can make use of the global window object available in the browser. The window object contains a navigator object which can be accessed with or without referencing the window, because it can stand alone and is globally accessible. The userAgent property in the navigator object is a long string that contains information about the operating system and browser.
Here is the result of the userAgent string on our browser:
Coding example
Here is an example showing how to detect and display the user's browser name:
Code explanation
Click the "HTML" tab as we take a walkthrough.
Lines 10–11: In the function
getBrowserName, we store thenavigator.userAgentin a variable calledbrowserInfo.Line 12: A variable named
browseris defined.Lines 13–25: Then, we use the if-else conditions to check if the
browserInfovariable contains a string specific to a browser. In this example, the string methodincludesis used to perform the check on the string, butindexOf,regex match, and other string methods can also be used. When the condition is true, the variablebrowseris set to the respective browser name.Line 26: The
browsername is returned from thegetBrowserNamefunction.Lines 29–33: The
browsername is set in HTML and displays the information on the webpage (as shown in the output tab).
Some browsers such as Google Chrome, Microsoft Edge, and Opera also display another browser name in their userAgent string. For example, Google Chrome shows Safari, Microsoft Edge shows both Google Chrome and Safari, and Opera shows Google Chrome. Hence, a strict check needs to be done for these browsers. If the if-else statements are used, they need to be well ordered, as shown above, to avoid getting wrong results.
Coding example
Here is an example of a strict check for Safari:
Code explanation
Line 1: A condition is used to detect if the
navigator.userAgentstring does not include Google Chrome, but includes Safari.Line 2: If the condition above is true, print
Browser is Safari.Line 4: If the condition above is false, print
Browser is not Safari.
Note: It is advised to use a feature-driven detection approach based on the browser capability, since the
userAgentproperty might not be reliable, because it is configurable and can be turned off by the user.