JavaScript 浏览器类型及版本号

前提是你 提交于 2020-03-29 08:04:43

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

        function getBrowserVertion(userAgent) {

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

 

  

测试:

getBrowserInfo(navigator.userAgent);

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!