检测客户端的操作系统和浏览器名称是比较常见的需求,整理保存一下备用~
1、检测浏览器名称
function getBrowser() {
var UserAgent = navigator.userAgent.toLowerCase();
var browser = null;
var browserArray = {
IE: window.ActiveXObject || "ActiveXObject" in window, // IE
Chrome: UserAgent.indexOf('chrome') > -1 && UserAgent.indexOf('safari') > -1, // Chrome浏览器
Firefox: UserAgent.indexOf('firefox') > -1, // 火狐浏览器
Opera: UserAgent.indexOf('opera') > -1, // Opera浏览器
Safari: UserAgent.indexOf('safari') > -1 && UserAgent.indexOf('chrome') == -1, // safari浏览器
Edge: UserAgent.indexOf('edge') > -1 // Edge浏览器
QQBrowser: /qqbrowser/.test(UserAgent), // qq浏览器
WeixinBrowser: /MicroMessenger/i.test(UserAgent) // 微信浏览器
};
for (var i in browserArray) {
if (browserArray[i]) {
browser = i;
}
}
return browser;
}
2、 检测IE浏览器版本号(兼容IE11)
function getIEVersion() {
var UserAgent = navigator.userAgent.toLowerCase();
var re = new RegExp("msie ([0-9]{1,})");
var re11 = new RegExp("rv\:([0-9]{1,})");
var ver = null;
if (re.exec(UserAgent) != null) {
console.log(RegExp.$1);
ver = RegExp.$1;
} else { // IE11
if(re11.exec(UserAgent) != null) {
console.log(RegExp.$1);
ver = RegExp.$1;
}
}
return ver;
}
IE11浏览器和低版本的IE浏览器的userAgent格式上有很大的变化,用旧的方法无法获取版本号,需要使用新的方法。
3、获取操作系统
function getOperationSys() {
var OS = '';
var OSArray = {};
var UserAgent = navigator.userAgent.toLowerCase();
OSArray.Windows = (navigator.platform == 'Win32') || (navigator.platform == 'Windows');
OSArray.Mac = (navigator.platform == 'Mac68K') || (navigator.platform == 'MacPPC')
|| (navigator.platform == 'Macintosh') || (navigator.platform == 'MacIntel');
OSArray.iphone = UserAgent.indexOf('iPhone') > -1;
OSArray.ipod = UserAgent.indexOf('iPod') > -1;
OSArray.ipad = UserAgent.indexOf('iPad') > -1;
OSArray.Android = UserAgent.indexOf('Android') > -1;
for (var i in OSArray) {
if (OSArray[i]) {
OS = i;
}
}
return OS;
}
4、获取浏览器语言
function getBrowserLang() {
var currentLang = navigator.language;
if (!currentLang) {
currentLang = navigator.browserLanguage;
}
return currentLang;
}