userAgent是HTTP请求中的用户标识,是能够代表客户端类型的字符串,比如浏览器类型 操作系统等信息。
console.log(navigator)
console.log(navigator.userAgent);
判断设备是PC端还是移动端: false PC端 | true 移动端
//判断设备是PC端还是移动端: false PC端 | true 移动端
const isMobile = () => {
return !!navigator.userAgent.match(/(iPhone|iPod|Android|ios|iOS|WebOS|Windows Phone|Phone)/i);
}
判断设备时安卓还是IOS
// 判断设备时安卓还是IOS
const isAndroid = () => {
return /android/i.test(navigator.userAgent.toLowerCase());
};
const isIOS = () => {
let reg = /iPhone|iPad|iOS|Macintosh/i;
return reg.test(navigator.userAgent.toLowerCase());
};
判断浏览器类型及其版本
// 获取浏览器类型及其版本
const getExplorerInfo = () => {
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("mise")
? {
// IE<11
type: "IE",
version: Number(t.match(/mise ([\d]+)/)[1]),
}
: !!t.match(/trident\/.+?rv:(([\d.]+))/)
? {
// IE 11
type: "IE",
version: 11,
}
: 0 <= t.indexOf("edge")
? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("firefox")
? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("chrome")
? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d/]+)/)[1]),
}
: 0 <= t.indexOf("opera")
? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1]),
}
: {
type: t,
version: -1,
};
}
测试:打开控制台(检查自己的浏览器)
console.log(isMobile());//false电脑
if (isMobile() == false) {
alert("PC端");
alert("浏览器类型:" + getExplorerInfo().type + "," + "版本号:" + getExplorerInfo().version)
console.log("PC端", getExplorerInfo());//浏览器类型
} else {
alert("移动端")
console.log("移动端");
if (isAndroid() !== false) {
alert("安卓")
console.log("安卓");
} else {
console.log("不是安卓");
}
if (isIOS() !== false) {
alert("IOS")
console.log("IOS");
} else {
console.log("不是IOS");
}
}