萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 判斷裝置類型:PC、行動裝置、iPad 完整方案

核心原理:User Agent 字串解析

透過 navigator.userAgent(UA)與 navigator.platform 判斷裝置類型、作業系統與瀏覽器核心。雖然 UA 可被偽造,但仍是客戶端偵測最常用的手段。

方案一:騰訊網適配邏輯(經典寫法)

var system = {
  win: false, mac: false, x11: false, ipad: false
};
var p = navigator.platform;
system.win = p.indexOf('Win') === 0;
system.mac = p.indexOf('Mac') === 0;
system.x11 = (p === 'X11') || (p.indexOf('Linux') === 0);
system.ipad = navigator.userAgent.match(/iPad/i) !== null;

// 非 PC / Mac / Linux / iPad 則導向行動版
if (!(system.win || system.mac || system.x11 || system.ipad)) {
  window.location.href = 'https://m.example.com/';
}

方案二:詳細瀏覽器核心與裝置判斷物件

var browser = {
  versions: (function() {
    var u = navigator.userAgent, app = navigator.appVersion;
    return {
      trident: u.indexOf('Trident') > -1,        // IE 核心
      presto: u.indexOf('Presto') > -1,          // Opera 核心
      webKit: u.indexOf('AppleWebKit') > -1,     // WebKit 核心
      gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // Firefox
      mobile: !!u.match(/AppleWebKit.*Mobile.*/) || !!u.match(/AppleWebKit/),
      ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
      android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1,
      iPhone: u.indexOf('iPhone') > -1,
      iPad: u.indexOf('iPad') > -1,
      webApp: u.indexOf('Safari') === -1,        // WebApp 模式(無工具列)
      google: u.indexOf('Chrome') > -1
    };
  })(),
  language: (navigator.browserLanguage || navigator.language).toLowerCase()
};

// 使用範例
console.log('語言:', browser.language);
console.log('是否行動裝置:', browser.versions.mobile);
console.log('是否 iOS:', browser.versions.ios);
console.log('是否 Android:', browser.versions.android);

方案三:專用 iPad 偵測函式

function isIPad() {
  return navigator.userAgent.toLowerCase().match(/ipad/i) === 'ipad';
}

// 伺服端(PHP)同步判斷
$is_ipad = (bool) strpos($_SERVER['HTTP_USER_AGENT'], 'iPad');

// Nginx 重寫規則
// RewriteCond %{HTTP_USER_AGENT} ^.*iPad.*$
// RewriteRule ^(.*)$ https://ipad.example.com [R=301]

方案四:支援強制 PC 模式的完整跳轉函式

var bForcePC = getQuery('dv') === 'pc'; // URL 參數 ?dv=pc 強制 PC 版

function browserRedirect() {
  if (bForcePC) return;
  var ua = navigator.userAgent.toLowerCase();
  var isIPad = ua.match(/ipad/i) === 'ipad';
  var isIPhone = ua.match(/iphone os/i) === 'iphone os';
  var isAndroid = ua.match(/android/i) === 'android';
  var isMobile = isIPad || isIPhone || isAndroid || ua.match(/mobile/i);

  if (isMobile) {
    window.location.href = 'https://m.example.com/';
  }
}
browserRedirect();

現代最佳實踐建議

  • 優先使用響應式設計(RWD):CSS Media Queries + 彈性佈局,單一代碼庫適配所有裝置。
  • 功能偵測優於瀏覽器偵測:使用 'ontouchstart' in window、window.matchMedia 判斷觸控、螢幕尺寸。
  • 避免 UA 重導:導致 SEO 問題、快取複雜度、使用者體驗中斷。
  • 若必須區分,建議採用 navigator.userAgentData(Client Hints API,現代瀏覽器支援)。
copyright © 萬盛學電腦網 all rights reserved