2014-10-11 138 views
1

我試圖從用戶代理中檢測瀏覽器類型和IE兼容性並相應地重定向。它只適用於IE,但不適用於Firefox和Chrome。我仍在四處尋找解決方案,但尚未弄清楚。使用Java腳本瀏覽器檢測和兼容性檢查

<html> 
<head> 
<title>Testing </title> 
<script src="UserAgent.js" type="text/javascript"></script> 
</head> 
<body> 
<div id="results">Output</div> 
<script type="text/javascript"> 

if (UserAgent.firefox){ 
    window.location.href("http://www.yahoo.com"); 
} 

if (UserAgent.compatibilityMode) { 
    window.location.href("http://192.168.10.236/iecorrect.html"); 
} else { 
    window.location.href("http://www.apple.com"); 
} 

</script> 
</body> 
</html> 

UserAgent.js

if (typeof jQuery == 'undefined') { 
document.write("\<script src='http://code.jquery.com/jquery-latest.min.js' type='text/javascript'>\<\/script>"); 
} 

// Create new object 
var UserAgent = { 
init: function() { 
    // Get the user agent string 
    var ua = navigator.userAgent; 
    this.compatibilityMode = false;  
    this.firefox = ua.toLowerCase().indexOf("firefox") > -1; 
    this.chrome = ua.toLowerCase().indexOf("chrome") > -1 

    if (ua.indexOf("MSIE 7.0") > -1) { 
     this.compatibilityMode = true; 
    } 
} 
}; 

// Initialize the object 
ieUserAgent.init(); 
+0

你有什麼需要這個?爲了向用戶顯示警告,如「升級到更體面的瀏覽器」或其他內容? – Juri 2014-10-11 08:07:48

+0

我們的網站實際上在幾個客戶端IE中處於兼容模式,因此將它們重定向到指令頁面以從兼容性視圖設置中刪除。 – zhtway 2014-10-11 08:11:50

回答

0

更改您的window.loacation.href調用下面的代碼:

if (UserAgent.compatibilityMode) { 
    window.location.href = "http://192.168.10.236/iecorrect.html"; 
} else { 
    window.location.href = "http://www.apple.com"; 
} 

你寫他們喜歡你會寫jQuery的:)

+1

另外,你可以使用''強制IE用戶退出兼容模式。 – ACarlson1994 2014-10-11 08:18:32

+0

你太棒了!謝謝 – zhtway 2014-10-11 08:22:47

+0

不是問題!祝你好運! – ACarlson1994 2014-10-11 08:25:37

0

要檢查IE和/或IE瀏覽器的特定版本,你最好使用條件語句。

http://www.quirksmode.org/css/condcom.html

+0

我其實不想知道IE版本。我只想知道兼容性視圖狀態。主要的問題是主html不能重定向的Firefox或鉻。 – zhtway 2014-10-11 08:15:31

+0

您是否嘗試添加以防止兼容模式? – 2014-10-11 08:20:18