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.
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.
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:
Here is an example showing how to detect and display the user's browser name:
Click the "HTML" tab as we take a walkthrough.
Lines 10–11: In the function getBrowserName
, we store the navigator.userAgent
in a variable called browserInfo
.
Line 12: A variable named browser
is defined.
Lines 13–25: Then, we use the if-else conditions to check if the browserInfo
variable contains a string specific to a browser. In this example, the string method includes
is used to perform the check on the string, but indexOf
, regex match
, and other string methods can also be used. When the condition is true, the variable browser
is set to the respective browser name.
Line 26: The browser
name is returned from the getBrowserName
function.
Lines 29–33: The browser
name 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.
Here is an example of a strict check for Safari:
Line 1: A condition is used to detect if the navigator.userAgent
string 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
userAgent
property might not be reliable, because it is configurable and can be turned off by the user.