检测移动浏览器

以下是一些检查用户是否正在从移动浏览器浏览的方法。

检查 userAgent(不推荐)

// 如果需要,您可以添加更多
const isMobile = /Android|BlackBerry|iPad|iPod|iPhone|webOS/i.test(navigator.userAgent)

我不推荐这种方法,因为服务器可以发送一个假的用户代理。

使用特征检测

检查浏览器是否支持 pointer:coarse 媒体查询:

const isMobile = function () {
  const match = window.matchMedia('(pointer:coarse)')
  return match && match.matches
}

我们不能依赖屏幕尺寸,因为移动设备越来越大。

检测 mac OS 浏览器

检查当前浏览器是否在 Mac 上运行:

const isMacBrowser = /Mac|iPod|iPhone|iPad/.test(navigator.platform)

检测 Internet Explorer 浏览器

检查当前浏览器是否为 Internet Explorer (IE):

const isIe = function () {
  const ua = window.navigator.userAgent
  return ua.indexOf('MSIE') > -1 || ua.indexOf('Trident') > -1
}

我们也可以依靠 document.documentMode。该属性表示文档的兼容模式,在 IE 5-11 中为整数。其他浏览器返回 undefined

const isIE = !!document.documentMode;

更多

更多方法可查看阮一峰总结的 JavaScript 侦测手机浏览器的五种方法