Browser Detection Collection

One of the biggest headaches when developing HTML5 code is how the final result can vary greatly, depending on the browser and/or device interpreting the code.

While there are many libraries that help handling that work, there are occasions you may need to know which browser and device you’re dealing with, in order to trigger specific actions.

So here’s a function I had to cobble together over a year ago for that purpose:

var browserName = “other”;
var browserVersion = “”;
var browserOS = “other”;
var isMobile = false;

function DetectBrowser(){

// Checks if it’s Internet Explorer
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)){

browserName = “IE”;
browserVersion = new Number(RegExp.$1);

}

// Checks if it’s Firefox
if(/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){

browserName = “Firefox”;
browserVersion = new Number(RegExp.$1);

}

// Checks if it’s Chrome
if(/Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor)){

browserName = “Chrome”;
browserVersion = new Number(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]);

}

// Checks if it’s Safari
if(/Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor)){

browserName = “Safari”;
browserVersion = new Number(navigator.userAgent.split(“/”)[3].split(“.”)[0]);

}

// Checks if it’s Opera
if (/Opera[\/\s](\d+\.\d+)/.test(navigator.userAgent)){

browserName = “Opera”;
browserVersion = new Number(navigator.userAgent.split(“/”)[3].split(“.”)[0]);

}

///////////////////////

// Checks if it’s Windows
if(navigator.appVersion.indexOf(“Win”) != -1){

browserOS = “Windows”;

}

// Checks if it’s Mac
if(navigator.appVersion.indexOf(“Mac”) != -1){

browserOS = “Mac”;

}

// Checks if it’s Unix
if(navigator.appVersion.indexOf(“X11″) != -1){

browserOS = “Unix”;

}

// Checks if it’s Linux
if(navigator.appVersion.indexOf(“Linux”) != -1){

browserOS = “Linux”;

}

// Checks if it’s iPad
if(navigator.userAgent.match(/iPad/i) != null){

browserOS = “iPad”;
isMobile = true;

}

// Checks if it’s iPhone
if(navigator.userAgent.match(/iPhone/i) != null || navigator.userAgent.match(/iPod/i) != null){

browserOS = “iPhone”;
isMobile = true;

}

// Checks if it’s Android
if(navigator.userAgent.match(/Android/i)){

// Checks if it’s a Smartphone
if(navigator.userAgent.match(/Mobile/i)){

browserOS = “AndroidMobile”;

}
else{

browserOS = “AndroidTablet”;

}
isMobile = true;

}

// Checks if it’s IEMobile
if(navigator.userAgent.match(/IEMobile/i)){

browserOS = “IEMobile”;
isMobile = true;

}

// Checks if it’s BlackBerry
if(navigator.userAgent.match(/BlackBerry/i)){

browserOS = “BlackBerry”;
isMobile = true;

}

}

You may also like...