最近在做公司PC端低版本浏览器兼容性问题,现将检测浏览器版本号接口封装一下,和大家一起分享交流下。
browserCheck.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>浏览器版本检测接口封装</title> <script src="browserCheck.js"></script> <script> window.onload = function () { top.CY.BrowserCheck.getBrowserInfo({ IE: 10, Firefox: 10, Chrome: 21, SafariWindow: 500, Safari1Mac: 500, }, function (results) { if (results) { alert('您的浏览器版本太低!'); } else { alert('您的浏览器版本正常!'); } }); } </script> </head> <body> </body> </html>
browserCheck.js
if (!window.CY) window.CY = {}; var CY = window.CY; CY.BrowserCheck = { getBrowserInfo: function (obj, callback) { var agent = navigator.userAgent.toLowerCase(); //判断是否是Windows操作系统 var isWin = (navigator.platform == "Win32") || (navigator.platform == "Win64") || (navigator.platform == "Windows"); //判断是否是Mac操作系统 var isMac = (navigator.platform == "Mac68K") || (navigator.platform == "MacPPC") || (navigator.platform == "Macintosh") || (navigator.platform == "MacIntel"); //获取当前浏览器版本号 var version_ie = (agent.match(/msie [\d.]+;/gi) + "").replace(/[^0-9.]/ig, "").split(".")[0]; var version_ff = (agent.match(/firefox\/[\d.]+/gi) + "").replace(/[^0-9.]/ig, "").split(".")[0]; var version_chrome = (agent.match(/chrome\/[\d.]+/gi) + "").replace(/[^0-9.]/ig, "").split(".")[0]; var version_saf = (agent.match(/safari\/[\d.]+/gi) + "").replace(/[^0-9.]/ig, "").split(".")[0]; var flag = false; if (isWin) { //IE if (agent.indexOf("msie") > 0 && version_ie < obj.IE) { flag = true; } //firefox if (agent.indexOf("firefox") > 0 && version_ff < obj.Firefox) { flag = true; } //Chrome if (agent.indexOf("chrome") > 0 && version_chrome < obj.Chrome) { flag = true; } //Safari if (agent.indexOf("safari") > 0 && agent.indexOf("chrome") < 0 && version_saf < obj.SafariWindow) { flag = true; } } if (isMac) { //Safari if (agent.indexOf("safari") > 0 && version_saf < obj.Safari1Mac) { flag = true; } } flag == true ? callback(true) : callback(false) } }
代码DEMO: 链接: http://pan.baidu.com/s/1eRSarlw 密码: 87r8