除了另無它法,肯定不使用navigator.userAgent來判定瀏覽器。因為在第一次瀏覽器大戰初期,Netscape占絕對統計地位,大部分人們不願意相容其他瀏覽器,並通過檢測其UA讓他們的網站只允許Netscape訪問,這就逼使其他瀏覽器(包括IE)修改自己的UA偽裝成Netscape來通過那些自以為是的指令碼,於是出現每個人都聲稱自己是別人的局面,即使最新的IE9的UA也是:
//Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; Trident/5.0)
下面我收集或獨創的一些判定:
//IE8 新特徵一覽: http://www.cnblogs.com/rubylouvre/articles/1716755.html//2010 4 16日更新 ie678 = !+"\v1" ; ie678 = !-[1,];//IE9預覽版中失效 ie678 ='\v'=='v' ; ie678 = ('a~b'.split(/(~)/))[1] == "b" ie678 = 0.9.toFixed(0) == "0" IE8 = window.toStaticHTML IE9 = window.msPerformance ie = !!document.recalc ie = !!window.VBArray ie = !!window.ActiveXObject ie678 = 0//@cc_on+1; ie = !!window.createPopup; ie = /*@cc_on!@*/!1; ie = document.expando;//document.all在opera firefox的古老版本也存在 ie = /\w/.test('\u0130') //由群裡的abcd友情提供 ie6 = !"1"[0] //利用IE6或IE5的字串不能使用數組下標的特徵 ie8 = !!window.XDomainRequest; ie9 = document.documentMode && document.documentMode === 9; //自創,基於條件編譯的嗅探指令碼,IE會返回其JS引擎的版本號碼,非IE返回0 var ieVersion = eval("''+/*@cc_on"+" @_jscript_version@*/-0")*1 ie9 = ieVersion === 5.9 ie8 = ieVersion === 5.8 ie7 = ieVersion === 5.7 ie6 = ieVersion === 5.6 ie5 = ieVersion === 5.5 //https://developer.mozilla.org/En/Windows_Media_in_Netscape netscape = !!window.GeckoActiveXObject gecko = !!window.netscape //包括firefox firefox = !!window.Components firefox = !!window.updateCommands safari = !!(navigator.vendor && navigator.vendor.match(/Apple/)) safari = window.openDatabase && !window.chrome; chrome= !!(window.chrome && window.google) opera=!!window.opera ; //傲遊2 3 maxthon = /maxthon/i.test(navigator.userAgent) //360安全瀏覽器 is360se = /360se/i.test(navigator.userAgent)
//2010.6.4 setTimeout(function(){//FF的setTimeout總是有一個額餘的參數0 var isFF = !!arguments.length; alert(isFF) }, 0);
//判定IE版本2010.10.1 ie = (function(undefined){ var v = 3, div = document.createElement('div'); while ( div.innerHTML = '', div.getElementsByTagName('i')[0]); return v> 4 ? v : undefined; }());
//判定IE版本 2011.2.24 ie = (function() { var v = 3, div = document.createElement('div'), a = div.all || []; while (div.innerHTML = '', a[0]); return v > 4 ? v : !v; }());
//手機的相關判定 2011.9.21 isIPhone = /iPhone/i.test(navigator.userAgent); isIPhone4 = window.devicePixelRatio >= 2//在網頁中,pixel與point比值稱為device-pixel-ratio,普通裝置都是1,iPhone 4是2,有些Android機型是1.5//http://blog.webcreativepark.net/2011/01/25-173502.htmlvar ua = navigator.userAgent;isAndroid = /Android/i.test(ua);isBlackBerry = /BlackBerry/i.test(ua)isWindowPhone = /IEMobile/i.test(ua)isIOS = /iPhone|iPad|iPod/i/i.test(ua)isMobile = isAndroid || isBlackBerry || isWindowPhone || isIOS