JS侦测手机浏览器方法

272 阅读1分钟
  1. navigator.userAgent JS 通过navigator.userAgent属性拿到这个字符串,只要里面包含mobiandroidiphone等关键字,就可以认定是移动设备。
if (/Mobi|Android|iPhone/i.test(navigator.userAgent)) {
  // 当前设备是移动设备
}

该方法不可靠,用户可以修改这个字符串,伪装成桌面浏览器。

navigator.platform该属性表示用户的操作系统,已经废弃。

if (/Android|iPhone|iPad|iPod/i.test(navigator.platform)) {
  // 当前设备是移动设备
}
  1. window.screenwindow.innerWidth

  2. window.orientation 只有移动端设备才有这个属性,桌面设备的值为undefined

if (typeof window.orientation !== 'undefined') {
  // 当前设备是移动设备 
}

注意:iphone的safari浏览器不支持该属性。

  1. 触控事件 手机浏览器的 DOM 元素可以通过ontouchstart属性,为touch事件指定监听函数。桌面设备没有这个属性。
function isMobile() { 
  return ('ontouchstart' in document.documentElement); 
}

// 另一种写法
function isMobile() {
  try {
    document.createEvent("TouchEvent"); return true;
  } catch(e) {
    return false; 
  }
}
  1. 通过css 屏幕宽度: window.matchMedia()方法接受一个 CSS 的 media query 语句作为参数,判断这个语句是否生效。
let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

通过指针的精确性判断:

let isMobile = window.matchMedia("(pointer:coarse)").matches;

有些设备支持多种指针,比如同时支持鼠标和触摸。pointer:coarse只用来判断主指针,此外还有一个any-pointer命令判断所有指针。

let isMobile = window.matchMedia("(any-pointer:coarse)").matches;

any-pointer:coarse表示所有指针里面,只要有一个指针是不精确的,就符合查询条件。

搬运至阮大师的博客: www.ruanyifeng.com/blog/2021/0…