通過userAgent判斷檢測一下userAgent返回的字符串裡面是否包含“Chrome”, 具體怎麼檢測是通過indexOf方法進行的。
<script type="text/javascript"> var isChrome = window.navigator.userAgent.indexOf("Chrome") !== -1; alert(isChrome); if (isChrome) { alert("是Chrome瀏覽器") ; } else { alert("不是Chrome瀏覽器"); }</script>
關於indexOf方法:
indexOf方法返回一個整數值,指出String對象內子字符串的開始位置。即indexOf()括號內所包含的字符在該字符串內的位置,在第幾位就返回幾,從0開始記數。如果有重複的字符出現,以第一個字符為準。如果沒有找到子字符串,則返回-1。
JS通過內核判斷各種瀏覽器|區分360與穀歌(親測可用)
function getBrowserInfo(){ var ua = navigator.userAgent.toLocaleLowerCase(); var browserType=null; if (ua.match(/msie/) != null || ua.match(/trident/) != null) { browserType = "IE"; browserVersion = ua.match(/msie ([/d.]+)/) != null ? ua.match(/msie ([/d.]+)/)[1] : ua.match (/rv:([/d.]+)/)[1]; } else if (ua.match(/firefox/) != null) { browserType = "火狐"; }else if (ua.match(/ ubrowser/) != null) { browserType = "UC"; }else if (ua.match(/opera/) != null) { browserType = "歐朋"; } else if (ua.match(/bidubrowser/) != null) { browserType = "百度"; }else if (ua.match(/metasr/) != null) { browserType = "搜狗"; }else if (ua.match(/tencenttraveler/) != null | | ua.match(/qqbrowse/) != null) { browserType = "QQ"; }else if (ua.match(/maxthon/) != null) { browserType = "遨遊"; }else if (ua.match (/chrome/) != null) { var is360 = _mime("type", "application/vnd.chromium.remoting-viewer"); function _mime(option, value) { var mimeTypes = navigator.mimeTypes; for (var mt in mimeTypes) { if (mimeTypes[mt][option] == value) { return true; } } return false; } if(is360){ browserType = '360'; }else{ $('html').css ("zoom",".80"); } }else if (ua.match(/safari/) != null) { browserType = "Safari"; }}
只有原生Chrome中存在一種MimeType“application/vnd.chromium.remoting-viewer”,由此可以判斷瀏覽器是加殼Chrome或是原生Chrome。
再如,只有IE內核的瀏覽器存在ActiveXObject對象。由此可以判斷是否為IE瀏覽器
判斷瀏覽器類型,我們需要遵循以下原則:
1、採取命中特徵原則,當且僅當完全符合區分瀏覽器的特徵時我們才會採用此特徵。例如單純通過UA中MSIE來檢測是否為IE瀏覽器是不可靠的。而通過判斷是否存在MimeType“application/vnd.chromium.remoting-viewer”來斷言原生Chrome在現階段來看是可行性,但也不保證永久有效。
2、對於主流瀏覽器來說一般不存在UserAgent關鍵字衝突,但對於許多加殼瀏覽器者就不一定了。再次提出某數字瀏覽器,userAgent乾脆和IE一模一樣,但渲染模式等等不不知道動了什麼手腳,與標準IE行為差異很大。通過userAgent來判斷瀏覽器時,優先命中瀏覽器特徵字。匹配則基本確定為該瀏覽器,但未匹配也並不代表不是此瀏覽器。請悉知。
3、優先使用瀏覽器特性來區分瀏覽器,因為這個準確性較高。其次再採用userAgent輔助判斷,從而達到最高的匹配度。
4、優先檢測第三方加殼瀏覽器,目前並未有十分好的方案,只能枚舉大部分世面上存在並可以判斷的瀏覽器,其他未匹配任何規則的瀏覽器,為了兼容,請將規則落到四大瀏覽器之一。
5、判斷瀏覽器版本,僅僅是為了針對特定瀏覽器進行優化,需要有特定的業務場景需要才要這麼做。或者當某個瀏覽器出現兼容問題時,緊急添加針對瀏覽器的補丁代碼時才判斷。更加科學穩妥的辦法是使用標準的JS函數和API,頁面元素和样式設計遵循W3C標準。可能存在爭議的兼容性問題盡可能採用第三方框架如jQuery。這才是解決兼容性問題的根本。
下面附上最近整理規納判斷瀏覽器類型的代碼