techie questie techie questie - 4 months ago 13
JSON Question

Detection of OS and version on page load afer matching the browser User Agent with the list of user agents for each version in JSON

I have a JSON array-
Level1>>Level2>>Level3.
Level1 will have all the OS name like Windows , Linux etc.
For each OS we have level 2 array which has the OS and version under each category.For ex. windows 10 64 bit
Inside level 2, we have list of user agents.we have to match the browser user agent with the userAgent lists in the JSON and display as detected OS.
My code-

matchTheOSVersionWithUserAgent: function (osVersion){
var userAgentList = osVersion.userAgent;
var matchRes;
for(i in userAgentList){

matchRes = navigator.userAgent.match(userAgentList[i]);

}


mock JSON:

osPlatforms: [{

"name": "Windows",
"osVersions": [{
"name": "Windows 10 (32 bit)",
"osBit": "32",
"userAgent": ["Windows 10 (32 bit)", "win10", "Microsoft Windows 10", "Windows NT 10.0", "Microsoft Windows 10 (64-bit)"],


}, {
"name": "Windows 10 (64 bit)",
"osBit": "64",
"userAgent": ["win10", "Microsoft Windows 10", "Windows NT 10.0", "Microsoft Windows 10 (32-bit)"],


}]


I am getting matchedRes as null and detection is not happening.I tried checking in mac and windows.can anyone help on this.TIA.

Answer

You need to do is in this way :

var osPlatforms = [{
  "name": "Windows",
  "osVersions": [{
    "name": "Windows 10 (32 bit)",
    "osBit": "32",
    "userAgent": ["Windows 10 (32 bit)", "win10", "Microsoft Windows 10", "Windows NT 10.0", "Microsoft Windows 10 (64-bit)", "Windows NT 6.1"],
  }, {
    "name": "Windows 10 (64 bit)",
    "osBit": "64",
    "userAgent": ["win10", "Microsoft Windows 10", "Windows NT 10.0", "Microsoft Windows 10 (32-bit)"],
  }]
}];

function matchTheOSVersionWithUserAgent(osVersion) {
  console.log(navigator.userAgent);
  var userAgentList = osVersion.userAgent;
  var matchRes;
  for (var i = 0; i < userAgentList.length; i++) {
    if (navigator.userAgent.match(userAgentList[i])) {
      matchRes = navigator.userAgent.match(userAgentList[i]);
      break;
    }
  }
  console.log(matchRes);
}

matchTheOSVersionWithUserAgent(osPlatforms[0].osVersions[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Basically break the loop once you have found the result.

Comments