0
votes

I am trying to detect browser that is used by application. This is the code which I am executing.

function checkBrowserType(){
var ua =navigator.userAgent;

alert("browser details ==> " +ua);

}

The strange thing is in various screens I am getting different user agent details. When I try in IE11 one screen it shows

Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 10.0; WOW64; Trident/7.0; Touch; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; Tablet PC 2.0; wbx 1.0.0)

Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; Touch; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; Tablet PC 2.0; wbx 1.0.0; rv:11.0) like Gecko

The first one looks fine for me as it gives MSIE search as 25. In that case I can assume the user is using IE. But the the second one says Mozilla/5.0 and 'MSIE' search gives -1 though I am trying in IE. I am not sure what is the real issue with my code. Any one please help me to resolve this.

1

1 Answers

1
votes

I am trying to detect browser that is used by application.

Don't do that.

As you can see using the navigator.userAgent is an unreliable way to find out what browser someone has and it can easily be spoofed by the client as well.

Instead, ask yourself "why" you really want to know what browser someone has and do "feature detection", not "browser detection".

Feature detection is where we test to see if the client supports some functionality that we'd like to use. Since there are clients that have proprietary APIs, knowing if you can call a particular API is really what you want to know.

Here's a classic example. Microsoft Internet Explorer didn't start supporting the W3C DOM standard of .addEventListener() until version 9. Back when IE8 was still used quite a bit, we'd have to know if we should be using the new standard or the old proprietary API of .attachEvent. Here's what we did:

let div = document.querySelector("div"); // Get the element

// Detect whether that element supports addEventListener...
// If it does, then that object property will return a native function (something)
// If it doesn't, then that object property won't exist and we'll get `undefined` (nothing)
if(div.addEventListener){
  console.log("W3C DOM Event API Supported... Setting up event with standard API");
  div.addEventListener("click", function(){
    alert("Thanks!");
  });
} else {
  console.log("Proprietary API Supported... Setting up event with proprietary API");
  div.attachEvent("click", function(){
    alert("Get a new browser!");
  });
}
<div>Click me</div>