如何通过JavaScript检测Windows 11 无需使用异步高熵值API
方案1:预加载检测结果,无需修改现有同步逻辑
你不需要重构现有全平台的同步解析代码,只要在页面加载阶段提前异步执行检测,把结果存在全局变量中缓存,后续业务逻辑直接读取缓存值即可,全程无需修改原有同步调用逻辑:
// 全局变量存储检测结果,后续所有逻辑直接读取 window.winVersionInfo = { isWindows: false, isWin11: false, isWin10: false }; // 优先使用官方高熵值API检测 if (navigator.userAgentData && navigator.userAgentData.getHighEntropyValues) { navigator.userAgentData.getHighEntropyValues(["platformVersion"]) .then(ua => { if (navigator.userAgentData.platform === "Windows") { window.winVersionInfo.isWindows = true; const majorVer = parseInt(ua.platformVersion.split('.')[0]); if (majorVer >= 13) { window.winVersionInfo.isWin11 = true; } else if (majorVer > 0) { window.winVersionInfo.isWin10 = true; } } }) .catch(() => { // API调用失败降级走UA检测 detectWinByUA(); }); } else { // 不支持高熵值API直接走UA检测 detectWinByUA(); } // UA兜底检测函数 function detectWinByUA() { const ua = navigator.userAgent; window.winVersionInfo.isWindows = ua.indexOf('Windows NT') > -1; if (!window.winVersionInfo.isWindows) return; const ntVersion = parseFloat(ua.match(/Windows NT (\d+\.\d+)/)?.[1] || 0); if (ntVersion < 10) return; window.winVersionInfo.isWin10 = true; // 结合Win11最低硬件要求做近似判断 if (navigator.hardwareConcurrency >= 4 && (navigator.deviceMemory || 0) >= 4) { window.winVersionInfo.isWin11 = true; } }
用户点击下载按钮时直接读取window.winVersionInfo的属性值即可,完全是同步调用,不会影响原有业务逻辑。
方案2:纯同步检测(无任何异步调用)
如果完全不想使用异步API,可以直接基于User-Agent加硬件特征做同步检测,不过要注意微软为了兼容旧站点,Win11的UA中NT版本号仍然标记为10.0,无法直接通过NT版本区分Win10和Win11,只能做近似判断,建议搭配下载页的手动版本切换入口使用,避免检测误差导致用户下错安装包。
同步检测代码如下:
function getWinVersionSync() { const ua = navigator.userAgent; const result = { isWindows: false, isWin11: false }; // 非Windows系统直接返回 if (!ua.includes('Windows NT')) return result; result.isWindows = true; const ntVerMatch = ua.match(/Windows NT (\d+\.\d+)/); if (!ntVerMatch || parseFloat(ntVerMatch[1]) < 10) return result; // 结合Win11最低4核+4G内存的要求做近似判断 if (navigator.hardwareConcurrency >= 4 && (navigator.deviceMemory || 0) >= 4) { result.isWin11 = true; } return result; }
纯同步检测的误差率约在5%左右,高配Win10设备可能被误判为Win11,低配Win11设备可能被误判为Win10,对准确率要求高的场景推荐使用方案1。
内容的提问来源于stack exchange,提问作者DHamrick
相关产品推荐
相关产品推荐

