JavaScript: How to detect the browser of user ?

picture of browsers

Open or create a html file in your favourite editor.

<p id="res"></p>

The above paragraph tag displays the our result.

<script>
    var browsers = ["Opera", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];
	.
	.
	.    
</script>

Then inside the script tag, we create an array of browsers.

<script>
    var browsers = ["Opera", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];
    var userbrowser, useragent = navigator.userAgent;
  	.
	.
	.
</script>

Here we initialize two variables ‘userbrowser’ and ‘useragent’.

The ‘navigator’ object contains information about browser and ‘userAgent’ property returns the user-agent header sent by the browser to the server.

<script>
    var browsers = ["Opera", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];
    var userbrowser, useragent = navigator.userAgent; 
    for (var i = 0; i < browsers.length; i++) {
        if (useragent.indexOf(browsers[i]) > -1) {
            userbrowser = browsers[i];
            break;
        }
    };
	.
	.
	.
</script>

The above loop checks each browser in our array, in the returned browser header.

<script>
	.
	.
    switch (userbrowser) {
        case 'MSIE':
            userbrowser = 'Internet Explorer';
            break;
        case 'Trident':
            userbrowser = 'Internet Explorer';
            break;
        case 'Edg':
            userbrowser = 'Microsoft Edge';
            break;
    }
	.
	.
</script>

We use the switch-case, to check for Internet Explorer and Edge.

<p id="res"></p>
<script>
	.
	.
	.
    document.getElementById("res").innerHTML = userbrowser;
</script>

And finally we display the result, in the paragraph tag.

Full Code

<p id="res"></p>
<script>
    var browsers = ["Opera", "Edg", "Chrome", "Safari", "Firefox", "MSIE", "Trident"];
    var userbrowser, useragent = navigator.userAgent;
    for (var i = 0; i < browsers.length; i++) {
        console.log(useragent.indexOf(browsers[i]))
        if (useragent.indexOf(browsers[i]) > -1) {
            userbrowser = browsers[i];
            break;
        }
    };
    switch (userbrowser) {
        case 'MSIE':
            userbrowser = 'Internet Explorer';
            break;
        case 'Trident':
            userbrowser = 'Internet Explorer';
            break;
        case 'Edg':
            userbrowser = 'Microsoft Edge';
            break;
    }

    document.getElementById("res").innerHTML = userbrowser;
</script>