Skip to content

Instantly share code, notes, and snippets.

@sorrycc
Created March 29, 2011 05:58
Show Gist options
  • Save sorrycc/891872 to your computer and use it in GitHub Desktop.
Save sorrycc/891872 to your computer and use it in GitHub Desktop.
Two way to get browser type[ and version]
var getBrowserInfo = function() {
// Ref: http://www.useragentstring.com/pages/useragentstring.php
var token = [ // 顺序有关
"Opera", // 某些版本会伪装成 MSIE, Firefox
"Chrome", // 某些版本会伪装成 Safari
"Safari", // 某些版本会伪装成 Firefox
"MSIE 6",
"MSIE 7",
"MSIE 8",
"MSIE 9",
"Firefox"
],
ua = navigator.userAgent;
for (var i = 0, len = token.length; i < len; ++i) {
if(ua.indexOf(token[i]) != -1) {
return token[i].replace(' ', '');
}
}
return "Other";
};
var browser = (function() {
var userAgent = navigator.userAgent;
var regexs = [
/MS(?:(IE) ([0-9]\.[0-9]))/,
/(Chrome)\/([0-9]+\.[0-9]+)/,
/(Firefox)\/([0-9a-z\.]+)/,
/(Opera).*Version\/([0-9]+\.[0-9]+)/,
/Version\/([0-9]+\.[0-9]+).*(Safari)/
];
for (var i = 0; i < regexs.length; i++){
var regex = regexs[i];
var match = userAgent.match(regex);
if (match){
var results = match.slice(1);
if (match.toString().indexOf('Safari') >= 0)
results = [results[1], results[0]];
return results.join(' ');
}
}
return userAgent;
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment