首页 > 代码库 > JavaScript 浏览器类型及版本号

JavaScript 浏览器类型及版本号

项目中偶尔用到判断浏览器类型及相关版本问题,现记录相关代码:

 

function getBrowserInfo(userAgent) {            var browserName, browserVersion;            if (userAgent.indexOf("MSIE") > -1) {                var types = userAgent.substring(userAgent.indexOf("MSIE"));                var Info = (types.split(";")[0]).split(" ");                browserName = Info[0];                browserVersion = Info[1];            } else if (userAgent.indexOf("Firefox") > -1) {                var types = userAgent.substring(userAgent.indexOf("Firefox"));                var Info = (types.split(" ")[0]).split("/");                browserName = Info[0];                browserVersion = Info[1];            } else if (userAgent.indexOf("Chrome") > -1) {                var types = userAgent.substring(userAgent.indexOf("Chrome"));                var Info = (types.split(" ")[0]).split("/");                browserName = Info[0];                browserVersion = Info[1];            } else if (userAgent.indexOf("Opera") > -1) {                var types = userAgent.substring(userAgent.indexOf("Opera"));                var Info = (types.split(" ")[0]).split("/");                browserName = Info[0];                browserVersion = Info[1];            } else if (userAgent.indexOf("Safari") > -1) {                var types = userAgent.substring(userAgent.indexOf("Safari"));                var Info = (types.split(" ")[0]).split("/");                browserName = Info[0];                browserVersion = Info[1];            } else if (userAgent.indexOf("rv") > -1) { // for IE11                var substring = userAgent.substring(userAgent.indexOf("rv"), userAgent.indexOf(")"));                browserName = "MSIE";                browserVersion = substring.split(":")[1];            }            if (browserVersion.indexOf(‘.‘) != -1) {                browserVersion = browserVersion.substring(0, browserVersion.indexOf(‘.‘));            }            return browserName + "-" + browserVersion;        }

 

 

测试:

getBrowserInfo(navigator.userAgent);

 

JavaScript 浏览器类型及版本号