Js recognizes different browsers based on the userAgent

  • 2020-03-30 03:38:32
  • OfStack

Check the browser and pay attention to the order of browser judgment, which is mainly based on the userAgent.


//Detect browser
var client = function(){
var engine = {
ie:0,
gecko:0,
webkit:0,
khtml:0,
opera:0,
ver:null
};
var browser = {
//The browser
ie: 0,
firefox: 0,
safari: 0,
konq: 0,
opera: 0,
chrome: 0,
ver:null
};
var ua = navigator.userAgent;
//The browser Detection in sequence 
if(window.opera){//Opera camouflage, so check first
engine.ver = browser.ver = window.opera.version();
engine.opera = browser.opera = parseFloat(engine.ver);
} else if(/AppleWebKit/(S+)/.test(ua)){
engine.ver = RegExp["$1"];
engine.webkit = parseFloat(engine.ver);


//Decide whether it's Chrome or Safari
if (/Chrome/(S+)/.test(ua)){
browser.ver = RegExp["$1"];
browser.chrome = parseFloat(browser.ver);
} else if (/Version/(S+)/.test(ua)){
browser.ver = RegExp["$1"];
browser.safari = parseFloat(browser.ver);
} else {
//Approximately determine the version number
var safariVersion = 1;
if (engine.webkit < 100){
safariVersion = 1;
} else if (engine.webkit < 312){
safariVersion = 1.2;
} else if (engine.webkit < 412){
safariVersion = 1.3;
} else {
safariVersion = 2;
}


browser.safari = browser.ver = safariVersion;
}

}else if (/KHTML/(S+)/.test(ua) || /Konqueror/([^;]+)/.test(ua)){
engine.ver = browser.ver = RegExp["$1"];
engine.khtml = browser.konq = parseFloat(engine.ver);
}else if (/rv:([^)]+)) Gecko/d{8}/.test(ua)){
engine.ver = RegExp["$1"];
engine.gecko = parseFloat(engine.ver);
//Determine if it's Firefox
if (/Firefox/(S+)/.test(ua)){
browser.ver = RegExp["$1"];
browser.firefox = parseFloat(browser.ver);
}
}else if (/MSIE ([^;]+)/.test(ua)){
engine.ver = browser.ver = RegExp["$1"];
engine.ie = browser.ie = parseFloat(engine.ver);
}
return {
engine:engine,
browser: browser
};
}();


// call 

if (client.engine.webkit) { //if it's WebKit 
if (client.browser.chrome){ 
//Execute the code for Chrome
} else if (client.browser.safari){ 
//Execute the code for Safari
} 
} else if (client.engine.gecko){ 
if (client.browser.firefox){ 
//Execute the code for Firefox
} else { 
// Execution against others  Gecko The browser The code of  
} 
}


Related articles: