原生 JS 判断设备类型方法

可通过以下两种主流方案实现设备类型检测:


方案一:基于 navigator.userAgent 的 User Agent 检测

实现代码

function isMobileDevice() {
  const ua = navigator.userAgent || navigator.vendor || window.opera;
  const mobileRegex = /android|iphone|ipad|ipod|blackberry|iemobile|opera mini|mobile|windows phone|phone|webos|kindle|tablet/i;
  return mobileRegex.test(ua.toLowerCase());
}

逻辑说明

  1. 通过 navigator.userAgent 获取浏览器标识字符串‌。

  2. 正则表达式匹配移动端关键词(如 androidiphonemobile 等)‌。

  3. 返回 true 表示移动端,false 表示 PC 端。

!!!接下来是方案二,方案二不太建议使用,因为三折叠可能不止768

方案二:结合屏幕分辨率与 User Agent 检测(增强版)

实现代码

function detectDeviceType() {
  const ua = navigator.userAgent.toLowerCase();
  const isMobileUA = /mobile|android|iphone|ipad|ipod|windows phone|phone|webos/i.test(ua);
  const isSmallScreen = window.innerWidth <= 768;
  return isMobileUA || isSmallScreen ? 'mobile' : 'pc';
}

逻辑说明

  1. 同时检测 User Agent 和屏幕宽度(移动端通常小于等于 768px)‌。

  2. 双条件验证减少误判(如 iPad 可能被识别为 PC 端)‌。

注意事项

  1. User Agent 的局限性:部分浏览器可能伪造 UA(如 Chrome 移动端模拟 PC 模式)‌。

  2. 平板设备处理:若需区分平板与手机,需额外增加关键词(如 ipadtablet)‌。

  3. 动态响应式场景:建议结合 CSS 媒体查询实现布局适配,而非仅依赖 JS 检测‌。

代码调用示例

if (isMobileDevice()) {
  console.log("当前设备为手机/平板");
} else {
  console.log("当前设备为 PC");
}

1. 基于 navigator.userAgent 的插件方案

推荐插件mobile-detect.jsplatform.js
实现逻辑

  • 插件通过解析 navigator.userAgent 中的设备标识符(如 AndroidiPhoneWindows 等)实现设备判断‌。

  • 支持更细分的设备类型检测(如平板、手机、PC)‌。

代码示例(以 mobile-detect.js 为例)

// 引入插件
import MobileDetect from 'mobile-detect';

// 初始化检测器
const md = new MobileDetect(navigator.userAgent);

// 判断设备类型
if (md.mobile()) {
  console.log("移动端登录设备(手机/平板)");
} else if (md.tablet()) {
  console.log("平板设备");
} else {
  console.log("PC 端设备");
}

2. 结合屏幕分辨率的增强方案

推荐插件react-device-detect(适用于 React 项目)
实现逻辑

  • 通过 User Agent 和屏幕宽度综合判断设备类型,减少误判‌。

  • 支持动态响应式场景(如横竖屏切换)‌。

代码示例

import { isMobile } from 'react-device-detect';

if (isMobile) {
  console.log("移动端登录设备");
} else {
  console.log("PC 端登录设备");
}

注意事项

  1. User Agent 的局限性

    • 浏览器可能伪造 UA(如 Chrome 的“桌面模式”模拟 PC 端)‌。

    • 建议结合后端设备指纹(如 IP、设备型号)增强准确性‌。

  2. 平板设备的特殊处理

    • 部分平板(如 iPad)可能被识别为 PC 端,需额外判断 navigator.platform(如 MacIntel 表示 iPad)‌。

  3. 动态设备切换场景

    • 监听 window.resize 事件,更新设备状态(如横竖屏切换导致屏幕宽度变化)‌。

推荐插件对比

插件适用场景优点
mobile-detect.js需要细分设备类型(手机/平板)支持 5000+ 设备类型识别
react-device-detectReact 项目集成简单,支持响应式设计
platform.js轻量级检测(仅区分 PC/移动端)体积小(< 5KB)