User-Agent 判断设备需用 JavaScript 读取 navigator.userAgent 并匹配关键片段(如 iPhone、iPad、Android、MicroMessenger),再通过 window.location.href 跳转;不能仅靠 CSS 媒体查询,因其无法触发跳转;服务端跳转更优但须注意大小写、正则鲁棒性及 Vary 响应头。

怎么用 User-Agent 判断设备类型并跳转
HTML5 本身不提供设备跳转能力,必须靠 JavaScript 读取 navigator.userAgent 做识别,再用 window.location.href 跳转。这不是响应式设计的推荐做法(响应式应优先用 CSS 媒体查询适配),但某些场景(如微信内强制跳微信版、iOS App 内嵌 WebView 跳专用页)确实需要服务端或客户端主动分流。
常见错误是只匹配 "iPhone" 或 "Android",漏掉 iPad("iPad" 不在 "iPhone" 里)、微信("MicroMessenger")、QQ 浏览器("MQQBrowser")等关键 UA 片段。
- iPhone 和 iPad 都要单独判断:
ua.includes("iPhone") || ua.includes("iPad") - 微信内置浏览器必须检查
ua.includes("MicroMessenger") && !ua.includes("WindowsWechat")(排除 Windows 微信桌面版) - 安卓手机建议用
ua.includes("Android") && !ua.includes("Mobile")辅助排除某些平板 UA(部分安卓平板 UA 含"Android"但不含"Mobile") - 跳转前加
setTimeout延迟 100ms,避免 iOS Safari 在页面未完全加载时跳转失败
为什么不能只靠 CSS 媒体查询做跳转
CSS @media 只能控制样式显示/隐藏,无法触发页面跳转。有人误以为用 display: none + 能“模拟跳转”,实际会导致白屏、SEO 恶化、UA 无法被服务端捕获等问题。
真实需求中,跳转往往依赖运行环境特征,比如:
立即学习“前端免费学习笔记(深入)”;
- 微信 JS-SDK 初始化失败时需降级到 H5 页面 —— 必须 JS 检测
typeof WeixinJSBridge === "undefined" - App 内 WebView 注入了全局变量(如
window.isInApp === true),比 UA 更可靠 - 需要区分「桌面 Safari」和「iOS Safari」:前者无
"Mobile",后者有,仅靠max-width无法区分
服务端跳转比前端更稳,但要注意什么
如果后端(如 Nginx、Node.js、PHP)能直接读取请求头 User-Agent,优先在服务端 302 跳转。好处是首屏无白屏、SEO 友好、UA 不可被前端伪造干扰。
但容易踩的坑是:
- Nginx 的
$http_user_agent匹配大小写敏感,建议用~*(忽略大小写)而非~ - 正则不要写死
Android.*Mobile,有些国产定制 ROM UA 格式混乱,建议分段匹配:Android.*Mobile|iPhone|iPad - 务必设置
Vary: User-Agent响应头,否则 CDN 或代理可能缓存错版本 - 微信爬虫(
wechatdevtools)UA 含"MicroMessenger",但它是开发工具,不是真用户,需额外排除
跳转逻辑放在哪里最安全
放在 末尾或 DOMContentLoaded 回调里,别放 load 事件后——等图片、字体加载完再跳,用户已看到首页内容,体验割裂。
示例代码(轻量、无依赖):
if (/iPad|iPhone|iPod/.test(navigator.userAgent) && !window.MSStream) {
window.location.href = "/ios.html";
} else if (/Android/.test(navigator.userAgent) && /Mobile/.test(navigator.userAgent)) {
window.location.href = "/android.html";
} else if (/MicroMessenger/.test(navigator.userAgent) && !/WindowsWechat/.test(navigator.userAgent)) {
window.location.href = "/wx.html";
}
注意:iOS 上 location.href 在某些 WebView 中可能被拦截,必要时改用 location.replace() 避免后退堆栈污染;真机测试务必覆盖微信、QQ、支付宝、钉钉四类主流容器。











