$.browser.version 或 navigator.userAgent.indexOf('MSIE 8.0') 獲取版本卻得到 7.0。<meta http-equiv="x-ua-compatible" content="IE=9"> 後仍為 7.0。x-ua-compatible 控制的是渲染引擎模式(文檔模式),不改變 navigator.userAgent 字符串。userAgent 固定報告 IE7。// C# 後台代碼
private int GetIEVersion() {
using (var key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"Software\Microsoft\Internet Explorer")) {
string version = key.GetValue("Version").ToString(); // "9.0.8112.16421"
return int.Parse(version.Substring(0, 1)); // 返回 9
}
}
// 應用:在啟動 WebBrowser 前寫入 FEATURE_BROWSER_EMULATION
var appName = System.IO.Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName);
using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true)) {
key.SetValue(appName, 11001, Microsoft.Win32.RegistryValueKind.DWord); // 11001 = IE11 標準模式
}
// 不要判斷版本,判斷功能是否存在
if (document.addEventListener) { /* 現代事件模型 */ }
if (window.Promise) { /* Promise 支援 */ }
if ('fetch' in window) { /* Fetch API */ }
if (CSS.supports('display', 'grid')) { /* CSS Grid */ }
<!--[if IE 9]> <script> console.log('IE9'); </script> <![endif]-->
// 引入 ua-parser-js
var parser = new UAParser();
var result = parser.getResult();
console.log(result.browser.name, result.browser.version); // "IE", "11.0"
解決:統一全站文檔模式,或在子頁面同樣聲明 meta 標籤。
FEATURE_BROWSER_EMULATION。$.browser / navigator.userAgent 進行邏輯分支。