2011-06-28 96 views
7

任何人都知道一個好的和可靠的方式來找出類型&版本的客戶端上安裝的瀏覽器使用JavaScript/jQuery?查找瀏覽器類型和版本?

看起來像jQuery有一些內置函數,但它在檢測Chrome時遇到問題。任何其他可靠的方法呢?

+1

檢測爲的是什麼? – Gareth

回答

8

如果您需要訪問者使用的瀏覽器信息,並將其用於統計信息或向用戶顯示信息,則可以使用jQuery Browser Plugin

它可以讓你在JavaScript 對象包含所有有關瀏覽器的信息 被使用。

當你想,以確定是否有一定的特點是在瀏覽器中可用,適用錯誤修正等

無需推倒重來一定要do feature detection,而不是瀏覽器檢測。

+0

看起來像jQuery Browser Plugin是最適合我的情況。感謝有關功能檢測的信息。 – Arjun

7

方法1:
注:由於JQuery的1.3,jQuery.browser已被棄用

試試這個:

<!DOCTYPE html> 
<html> 
<head> 
<style> 
p { color:green; font-weight:bolder; margin:3px 0 0 10px; } 
div { color:blue; margin-left:20px; font-size:14px; } 
span { color:red; } 
</style> 
<script src="http://code.jquery.com/jquery-latest.js"></script> 
</head> 
<body> 

<p>Browser info: (key : value)</p> 

<script> 
    jQuery.each(jQuery.browser, function(i, val) { 
    $("<div>" + i + " : <span>" + val + "</span>") 
       .appendTo(document.body); 
    });</script> 

</body> 
</html> 

方法2:

 

// A quick solution without using regexp (to speed up a little). 
var userAgent = navigator.userAgent.toString().toLowerCase(); 
if ((userAgent.indexOf('safari') != -1) && !(userAgent.indexOf('chrome') != -1)) { 
alert('We should be on Safari only!'); 
} 
 
+2

作爲一個方便的JsFiddle:http://jsfiddle.net/dZs7D/ – configurator

+0

當我在Chrome中運行該程序時,以下是結果:瀏覽器信息:(key:value) webkit:true 版本:534.7 safari: true – Arjun

+0

有什麼辦法可以區分黑白鉻和safari嗎? – Arjun

1

由於$.browser在jQuery的1.9被刪除,使用:

// ---------------------------------------------------------- 
// A short snippet for detecting versions of IE in JavaScript 
// without resorting to user-agent sniffing 
// ---------------------------------------------------------- 
// If you're not in IE (or IE version is less than 5) then: 
//  ie === undefined 
// If you're in IE (>=5) then you can determine which version: 
//  ie === 7; // IE7 
// Thus, to detect IE: 
//  if (ie) {} 
// And to detect the version: 
//  ie === 6 // IE6 
//  ie > 7 // IE8, IE9 ... 
//  ie < 9 // Anything less than IE9 
// ---------------------------------------------------------- 

// UPDATE: Now using Live NodeList idea from @jdalton 

var ie = (function(){ 

    var undef, 
     v = 3, 
     div = document.createElement('div'), 
     all = div.getElementsByTagName('i'); 

    while (
     div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->', 
     all[0] 
    ); 

    return v > 4 ? v : undef; 

}()); 
+0

有點特定於IE。 – Stephan

+0

@Alex比用戶代理嗅探更可靠。 – Johan

+0

你能用其他主流瀏覽器的瀏覽器檢測完成你的答案嗎? – Stephan