JavaScript 侦测手机浏览器的五种方法

侦测方法

JS 通过 navigator.userAgent 属性拿到这个字符串,只要里面包含 mobi、android、iphone 等关键字,就可以认定是移动设备。

1
2
3
4
5
6
7
8
9
10
11
12
if (/Mobi|Android|iPhone/i.test(navigator.userAgent)) {
// 当前设备是移动设备
}

// 另一种写法
if (
navigator.userAgent.match(/Mobi/i) ||
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/iPhone/i)
) {
// 当前设备是移动设备
}

缺点: 不可靠,因为用户可以修改这个字符串,让手机浏览器伪装成桌面浏览器

此外,还有一个已经废除的 navigator.platform 属性,所有浏览器都支持,所以也可以用。它返回一个字符串,表示用户的操作系统。

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

window.screen,window.innerWidth

通过屏幕宽度,判断是否为手机。
window.screen 对象返回用户设备的屏幕信息,该对象的 width 属性是屏幕宽度(单位为像素)

1
2
3
if (window.screen.width < 500) {
// 当前设备是移动设备
}

缺点:如果手机横屏使用,就识别不了。
另一个属性 window.innerWidth 返回浏览器窗口里面的网页可见部分的宽度,比较适合指定网页在不同宽度下的样式

1
2
3
4
5
6
7
8
9
10
11
const getBrowserWidth = function () {
if (window.innerWidth < 768) {
return "xs";
} else if (window.innerWidth < 991) {
return "sm";
} else if (window.innerWidth < 1199) {
return "md";
} else {
return "lg";
}
};

window.orientation

侦测屏幕方向,手机屏幕可以随时改变方向(横屏或竖屏),桌面设备做不到
window.orientation 属性用于获取屏幕的当前方向,只有移动设备才有这个属性,桌面设备会返回 undefined

1
2
3
4
// iPhone 的 Safari 浏览器不支持该属性
if (typeof window.orientation !== "undefined") {
// 当前设备是移动设备
}

touch 事件

手机浏览器的 DOM 元素可以通过 ontouchstart 属性,为 touch 事件指定监听函数。桌面设备没有这个属性

1
2
3
4
5
6
7
8
9
10
11
12
13
function isMobile() {
return "ontouchstart" in document.documentElement;
}

// 另一种写法
function isMobile() {
try {
document.createEvent("TouchEvent");
return true;
} catch (e) {
return false;
}
}

window.matchMedia()

CSS 通过 media query(媒介查询)为网页指定响应式样式。

window.matchMedia() 方法接受一个 CSS 的 media query 语句作为参数,判断这个语句是否生效。

1
let isMobile = window.matchMedia("only screen and (max-width: 760px)").matches;

除了通过屏幕宽度判断,还可以通过指针的精确性判断。

1
2
// 由于手机不支持鼠标,只支持触摸,所以符合这个条件
let isMobile = window.matchMedia("(pointer:coarse)").matches;

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

1
2
// any-pointer:coarse表示所有指针里面,只要有一个指针是不精确的,就符合查询条件
let isMobile = window.matchMedia("(any-pointer:coarse)").matches;

工具 js 侦测

推荐 react-device-detect,它支持多种粒度的设备侦测。

1
2
3
4
5
import { isMobile } from "react-device-detect";

if (isMobile) {
// 当前设备是移动设备
}
作者

Huasun47

发布于

2021-08-21

更新于

2021-08-21

许可协议