How to Detect Browser in JavaScript

Today, websites and applications need to be personalized according to user’s web browser. Therefore, many web developers need to determine which web browsers their users are using so they can customize the web pages accordingly. You can easily find out user browser in JavaScript. In fact, there are several ways to do this. In this article, we will learn how to detect browser in JavaScript.

When to Detect Browser

There are several reasons why you may need to detect browser in JavaScript:

  1. Browser-Specific Objects – If your website or application needs to use browser-specific objects for storage and other purposes, then you need to determine the browser your users are using. For example, Chrome browsers employ global chrome object which is absent in other web browsers.
  2. Browser-Specific Features – If you need to make use of a specific feature present in one web browser then you need to find out if your users are using that browser.
  3. Customization – Sometimes you may need to turn on/off certain features on your web pages depending on the client web browsers. Also, you may need to display browser-specific instructions and information for your users.
  4. Different APIs – Different web browsers may require you to implement a certain feature in different ways, due to differences in their APIs. So you need to find client web browser.

How to Detect Browser in JavaScript

There are several ways to detect web browser in JavaScript. Let us look at the most common ones.

1. Using User-Agent

All web browsers contain navigator object that contains information about web browsers. It contains many useful attributes that describes various aspects of user’s web browser. It is auto-populated by web browser and is read-only. Among them, userAgent is a useful property that contains the user-agent HTTP header string used by browser. You can access this value by simply calling navigator.userAgent. Here is a simple example.

console.log(navigator.userAgent);

userAgent contains a long string with name of web browser, its version and also the platform. It differs from one web browser to another. Here is a sample string, if you run it in Chrome web browser.

Mozilla/5.0(Windows NT 10.0; Win64; x64)AppleWebKit/537.36(KHTML, like Gecko) Chrome/129.0.0.0 ...

As you can see, it is very long and not easy to parse. We use this string to determine web browser by looking for browser-specific keywords in it. You can do this using indexOf() function which returns -1 if the keyword is absent and the position of first occurrence of keyword, if it is present.

The navigator.userAgent object contains ‘Chrome’ keyword in its value. So we look for this substring as shown below. It displays alert box if Chrome keyword is present in navigator.userAgent attribute.

if (navigator.userAgent.indexOf("Chrome") != -1) {
alert('Chrome');
}

Similarly, Firefox browser contains ‘Firefox’, Safari contains ‘Safari’, Opera contains ‘Opera’, Edge browser contains ‘Edg’ and IE contains ‘MSIE’ keywords respectively. So we can define a simple function which basically checks navigator.userAgent for each of the above keywords and accordingly returns the name of the browser.

<script type="text/javascript">

function my_browser(){
if (navigator.userAgent.indexOf("Chrome") != -1) {
alert('Google Chrome web browser');
} else if (navigator.userAgent.indexOf("Edg") != -1) {
alert('Microsoft Edge web browser');
} else if ((navigator.userAgent.indexOf("Opera") || navigator.userAgent.indexOf('OPR')) != -1) {
alert('Opera web browser');
} else if (navigator.userAgent.indexOf("Safari") != -1) {
alert('Safari web browser');
} else if (navigator.userAgent.indexOf("Firefox") != -1) {
alert('Firefox web browser');
} else if ((navigator.userAgent.indexOf("MSIE") != -1) || (!!document.documentMode == true)) //IF IE > 10
{
alert('IE browser');
} else {
alert('unknown browser');
}
}

</script>

You can call the above function directly.

<script>
my_browser();
</script>

2. Behavior Analysis

One of the problems of using User-Agent attribute is that it is easy to spoof this value, so it can be unreliable.

To overcome this problem, you can look for specific characteristics for each browser. For example, Firefox uses InstallTrigger API to install Add-Ons, Chrome web browser uses window.chrome global object, Edge browsers use Edg keyword in their User-Agent, opr.addons is present only in Opera browser and so on. Therefore, you can use the following series of checks to correctly identify the right browser.

var browser='not defined';
// Chrome 1 - 79
isChrome= !!window.chrome ;
if( isChrome ){
browser='Chrome';
}

// Firefox 1.0+
if( typeof InstallTrigger !== 'undefined'){
browser='Firefox';
}

// Safari 3.0+ "[object HTMLElementConstructor]"
if( /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && window['safari'].pushNotification))){
browser='Safari';
}

// Edge 20+
var isIE = /*@cc_on!@*/ false || !!document.documentMode;
if( !isIE && !!window.StyleMedia)
{
browser='Edge';
}

// Edge (based on chromium) detection
if( isChrome && (navigator.userAgent.indexOf("Edg") != -1))
{
browser='Edge';
}

// Opera 8.0+
isOpera= (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;

if(isOpera){
browser='Opera';
}

alert(browser);

This approach will allow you to determine web browser unambiguously. Also, it is almost impossible for anyone to spoof so many values.

3. Feature Detection

Sometimes a specific feature is supported by specific browser versions and not the rest. For example, WebRTC is a feature supported only by the following browsers and versions.

It can be very tedious to determine if WebRTC (and other features) are available in your web browser, using if…else conditions, due to the sheer number of browser and their versions. Also, this code will need to be updated regularly, whenever new versions are released.

In such cases, it is easier to directly call a function or attribute, we know, is supported by the feature. If the feature is present, then it will return a reasonable output, else it will return undefined.

Here is an example to determine if WebRTC function is supported by your web browser. We use getUserMedia attribute of navigator object. has_WebRTC is undefined by default and gets populated with the attribute values, if it is present. Otherwise, it will continue to remain undefined.

var has_WebRTC = navigator.getUserMedia ||
navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia ||
navigator.msGetUserMedia;

Different web browsers use different attribute names such as webkitGetUserMedia, mozGetUserMedia, etc. to store this information. So we need to use each of them. After this, you can directly use the value of has_WebRTC variable.

if (has_WebRTC) {
alert('WebRTC supported fully or partially');
}

4. Using jQuery

So far, we have looked at how to determine user web browser with plain JavaScript. There are also several third-party libraries that support this feature. For example, jQuery is a popular JavaScript library that allows you to easily work with web page elements. It also comes with many free plugins. For our case, we will use jQuery browser plugin. You can include it to your page by adding the following line to the head tag.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-browser/0.1.0/jquery.browser.min.js"></script>

The above code will include jQuery library as well as jQuery browser plugin.

Thereafter, you will be able to use $.browser object for your requirement. It contains lots of useful information about client web browser, automatically populated by the plugin. Here is a simple code snippet to get web browser name, version and platform, that can be used for browser determination.

console.log($.browser)
console.log("Browser name-" + $.browser.name +
"Version v" + $.browser.versionNumber +
"Platform " + $.browser.platform);

If you are already using a third-party library on your website/application, then it is better to use its browser checking method for this purpose. This is because there are many web browsers available, and they keep updating regularly. In some cases, this may change the value of User-Agent or other browse attributes.

If you use solution #1 or #2, it can be difficult to update your code to work for all web browsers, and keep testing them regularly. If you use a JS library, you only need to update the library and its creators will ensure that your code continues to work for latest browsers.

Why Not to Detect Web Browser

Earlier, we have mentioned when you should detect web browser. Now let us look at the flip side. There are also a couple of reasons why you should not detect web browser.

First of all, if JavaScript is disabled in your client’s web browser, then most of the above methods will not work. In some organizations, JavaScript is disabled for security purposes. In such cases, the browser-specific customization will fail.

Secondly, there are many web browsers out there and each of them releases several updates every year. It just takes one update to break your JavaScript code. For example, if the value of User-agent or any of the other browser attributes mentioned above changes, then your code will stop working. So it can be a headache to keep track of all web browsers and their versions, and maintain your code accordingly.

Conclusion

In this article, we have learnt several different ways to detect web browser using JavaScript. If you are doing browser detection to use a specific feature, then it is better to directly check if the feature exists or not, using feature detection. If you want to determine web browser to personalize the user experience, then you will need to use its User-Agent or other attributes (Solutions #1 and #2) for this purpose. If you already use a third-party library, then you may also use its own method to determine browser.

Also read:

How to Check if Element is Hidden in JS
How to Access Correct This in Callback
How to Return Asynchronous Response in JS

Leave a Reply

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