阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > 浏览器检测方法

浏览器检测方法

作者:陈川 阅读数:60215人阅读 分类: JavaScript

浏览器检测方法

浏览器检测是前端开发中常见的需求,用于处理不同浏览器之间的兼容性问题或提供特定功能。主要方法包括用户代理字符串分析、特性检测以及现代API检测。

用户代理字符串检测

通过navigator.userAgent获取浏览器信息是最传统的方式。虽然存在被篡改的可能,但对于基础识别仍然有效。

const userAgent = navigator.userAgent;

// 检测Chrome
if (userAgent.indexOf('Chrome') > -1) {
  console.log('Chrome浏览器');
} 

// 检测Firefox
if (userAgent.indexOf('Firefox') > -1) {
  console.log('Firefox浏览器');
}

// 检测Safari
if (userAgent.indexOf('Safari') > -1 && userAgent.indexOf('Chrome') === -1) {
  console.log('Safari浏览器');
}

// 检测Edge
if (userAgent.indexOf('Edg') > -1) {
  console.log('Microsoft Edge浏览器');
}

更完整的检测方案可以结合正则表达式:

const browser = {
  isIE: /Trident|MSIE/.test(userAgent),
  isEdge: /Edg/.test(userAgent),
  isFirefox: /Firefox/.test(userAgent),
  isChrome: /Chrome/.test(userAgent) && !/Edg/.test(userAgent),
  isSafari: /Safari/.test(userAgent) && !/Chrome/.test(userAgent)
};

特性检测方法

相比用户代理检测,特性检测更可靠,通过检查浏览器是否支持特定API或功能来判断。

// 检测WebP图片支持
function supportsWebp() {
  const elem = document.createElement('canvas');
  return elem.toDataURL('image/webp').indexOf('data:image/webp') === 0;
}

// 检测Fetch API
if (window.fetch) {
  console.log('支持Fetch API');
} else {
  console.log('不支持Fetch API,需要polyfill');
}

// 检测CSS Grid布局支持
if (CSS.supports('display', 'grid')) {
  document.documentElement.classList.add('cssgrid');
} else {
  document.documentElement.classList.add('no-cssgrid');
}

现代检测技术

随着浏览器标准化,更精确的检测方法出现:

// 检测ES6模块支持
const supportsModules = 'noModule' in HTMLScriptElement.prototype;

// 检测Web Components支持
const supportsWebComponents = 'customElements' in window;

// 检测Service Worker支持
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/sw.js');
}

// 检测WebGL支持
function detectWebGL() {
  try {
    const canvas = document.createElement('canvas');
    return !!(
      window.WebGLRenderingContext &&
      (canvas.getContext('webgl') || canvas.getContext('experimental-webgl'))
    );
  } catch (e) {
    return false;
  }
}

浏览器版本检测

有时需要特定版本浏览器的检测:

// 获取Chrome主版本号
const chromeVersion = userAgent.match(/Chrome\/(\d+)/)?.[1];

// 获取Firefox版本
const firefoxVersion = userAgent.match(/Firefox\/(\d+)/)?.[1];

// 检测IE11及以下版本
const isIE11OrBelow = !!window.MSInputMethodContext && !!document.documentMode;

移动设备检测

区分移动端和桌面端浏览器:

const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);

// 更精确的触摸设备检测
const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;

// 检测iOS设备
const isIOS = /iPad|iPhone|iPod/.test(userAgent) || 
              (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);

性能特性检测

检测浏览器性能相关特性:

// 检测硬件加速状态
const supportsHardwareAcceleration = 
  'WebGLRenderingContext' in window && 
  'getExtension' in WebGLRenderingContext.prototype;

// 检测WebAssembly支持
const supportsWasm = 'WebAssembly' in window;

// 检测Web Workers支持
const supportsWorkers = 'Worker' in window;

隐私模式检测

检测浏览器是否处于隐私浏览模式:

function isPrivateBrowsing() {
  return new Promise(resolve => {
    const fs = window.RequestFileSystem || window.webkitRequestFileSystem;
    if (!fs) return resolve(false);
    
    fs(window.TEMPORARY, 100, () => resolve(false), () => resolve(true));
  });
}

// 使用示例
isPrivateBrowsing().then(isPrivate => {
  console.log(isPrivate ? '隐私模式' : '正常模式');
});

浏览器引擎检测

识别底层渲染引擎:

const engine = {
  isWebKit: 'WebkitAppearance' in document.documentElement.style,
  isGecko: 'MozAppearance' in document.documentElement.style,
  isBlink: 'chrome' in window && 'CSS' in window,
  isTrident: 'msWriteProfilerMark' in window
};

网络连接检测

检测网络状态和类型:

// 检测网络连接状态
const isOnline = navigator.onLine;

// 检测连接类型(需要浏览器支持)
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
if (connection) {
  console.log('网络类型:', connection.type);
  console.log('有效类型:', connection.effectiveType);
  console.log('下行速度:', connection.downlink + 'Mb/s');
}

// 监听网络变化
if (connection) {
  connection.addEventListener('change', () => {
    console.log('网络状态变化:', connection.effectiveType);
  });
}

浏览器语言检测

获取用户首选语言:

// 获取浏览器语言设置
const userLanguage = navigator.language || navigator.userLanguage;

// 获取所有支持的语言
const languages = navigator.languages || [navigator.language];

// 检测中文用户
const isChineseUser = /^zh/.test(userLanguage);

浏览器插件检测

检测已安装的浏览器插件:

// 检测Flash插件
function hasFlash() {
  try {
    const flash = navigator.plugins['Shockwave Flash'];
    return !!flash;
  } catch (e) {
    return false;
  }
}

// 检测PDF查看器
const hasPDFViewer = navigator.mimeTypes['application/pdf'] !== undefined;

// 列出所有插件
const plugins = Array.from(navigator.plugins).map(plugin => ({
  name: plugin.name,
  description: plugin.description,
  filename: plugin.filename
}));

浏览器视窗检测

获取浏览器窗口信息:

// 检测视窗尺寸
const viewportWidth = Math.max(
  document.documentElement.clientWidth || 0,
  window.innerWidth || 0
);
const viewportHeight = Math.max(
  document.documentElement.clientHeight || 0,
  window.innerHeight || 0
);

// 检测设备像素比
const pixelRatio = window.devicePixelRatio || 1;

// 检测屏幕方向
const orientation = window.screen.orientation || 
                   window.screen.mozOrientation || 
                   window.screen.msOrientation;

if (orientation) {
  console.log('当前方向:', orientation.type);
}

浏览器存储检测

检测各种存储API的可用性:

// 检测localStorage可用性
function hasLocalStorage() {
  try {
    const test = '__storage_test__';
    localStorage.setItem(test, test);
    localStorage.removeItem(test);
    return true;
  } catch(e) {
    return false;
  }
}

// 检测IndexedDB支持
const hasIndexedDB = 'indexedDB' in window;

// 检测WebSQL支持(已废弃)
const hasWebSQL = 'openDatabase' in window;

// 检测Cookie支持
function hasCookies() {
  document.cookie = 'testcookie=1';
  return document.cookie.indexOf('testcookie=') !== -1;
}

浏览器安全特性检测

检测安全相关功能:

// 检测HTTPS状态
const isSecure = window.location.protocol === 'https:';

// 检测内容安全策略
const hasCSP = 'securityPolicy' in document || 
              'webkitSecurityPolicy' in document;

// 检测Referrer Policy支持
const hasReferrerPolicy = 'referrerPolicy' in document.createElement('a');

// 检测混合内容自动升级
const hasMixedContentAutoUpgrade = 
  'upgradeInsecureRequests' in document.createElement('meta');

浏览器API兼容性检测

检测新API的兼容性:

// 检测Intersection Observer API
const hasIntersectionObserver = 'IntersectionObserver' in window;

// 检测Resize Observer API
const hasResizeObserver = 'ResizeObserver' in window;

// 检测Payment Request API
const hasPaymentRequest = 'PaymentRequest' in window;

// 检测Web Share API
const hasWebShare = 'share' in navigator;

// 检测Web Bluetooth API
const hasWebBluetooth = 'bluetooth' in navigator;

浏览器图形能力检测

检测图形相关功能:

// 检测Canvas支持
const hasCanvas = !!document.createElement('canvas').getContext;

// 检测SVG支持
const hasSVG = !!document.createElementNS && 
              !!document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect;

// 检测WebGL版本
function getWebGLVersion() {
  try {
    const canvas = document.createElement('canvas');
    const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
    if (!gl) return 0;
    
    const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
    return debugInfo ? gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) : 1;
  } catch (e) {
    return 0;
  }
}

浏览器媒体能力检测

检测媒体相关功能:

// 检测视频格式支持
function canPlayVideoType(type) {
  const video = document.createElement('video');
  return !!video.canPlayType(type).replace(/no/, '');
}

// 检测音频API
const hasWebAudio = 'AudioContext' in window || 
                   'webkitAudioContext' in window;

// 检测媒体设备访问
const hasMediaDevices = 'mediaDevices' in navigator && 
                       'getUserMedia' in navigator.mediaDevices;

// 检测屏幕共享API
const hasScreenCapture = 'getDisplayMedia' in navigator.mediaDevices;

浏览器输入法检测

检测输入法相关状态:

// 检测输入法编辑器状态
const isIMEActive = () => {
  const input = document.createElement('input');
  input.style.position = 'fixed';  // 防止布局变化
  document.body.appendChild(input);
  input.focus();
  
  const initialWidth = input.offsetWidth;
  input.value = 'あ';  // 触发IME输入
  const imeWidth = input.offsetWidth;
  
  document.body.removeChild(input);
  return imeWidth !== initialWidth;
};

// 检测虚拟键盘状态
const isVirtualKeyboardVisible = () => {
  return window.innerHeight < window.screen.height;
};

浏览器扩展检测

检测浏览器扩展的存在:

// 检测AdBlock等广告拦截器
function detectAdBlocker() {
  return new Promise(resolve => {
    const ad = document.createElement('div');
    ad.innerHTML = '&nbsp;';
    ad.className = 'adsbox';
    ad.style.position = 'absolute';
    ad.style.left = '-999px';
    ad.style.height = '1px';
    
    document.body.appendChild(ad);
    
    window.setTimeout(() => {
      const isBlocked = ad.offsetHeight === 0;
      document.body.removeChild(ad);
      resolve(isBlocked);
    }, 100);
  });
}

浏览器自动化检测

检测是否运行在自动化测试环境中:

// 检测Headless Chrome
const isHeadlessChrome = () => {
  return navigator.webdriver === true || 
         /HeadlessChrome/.test(navigator.userAgent);
};

// 检测Puppeteer
const isPuppeteer = () => {
  return navigator.userAgent.includes('Puppeteer');
};

// 检测Selenium
const isSelenium = () => {
  return navigator.webdriver === true && 
         !navigator.userAgent.includes('HeadlessChrome');
};

浏览器内存检测

获取浏览器内存信息:

// 检测设备内存(需要浏览器支持)
const deviceMemory = navigator.deviceMemory || 0;

// 检测性能内存API
if ('performance' in window && 'memory' in performance) {
  console.log('已用JS堆:', performance.memory.usedJSHeapSize);
  console.log('JS堆大小限制:', performance.memory.jsHeapSizeLimit);
}

// 检测内存压力API
const hasMemoryPressure = 'memory' in navigator && 
                         'pressure' in navigator.memory;

浏览器权限检测

检测各种权限状态:

// 检测通知权限
const notificationPermission = Notification.permission;

// 检测地理位置权限
navigator.permissions.query({name: 'geolocation'})
  .then(result => {
    console.log('地理位置权限:', result.state);
  });

// 检测摄像头权限
async function checkCameraPermission() {
  try {
    const stream = await navigator.mediaDevices.getUserMedia({video: true});
    stream.getTracks().forEach(track => track.stop());
    return true;
  } catch (e) {
    return false;
  }
}

浏览器电池状态检测

检测设备电池信息:

// 检测电池API
if ('getBattery' in navigator) {
  navigator.getBattery().then(battery => {
    console.log('电量:', battery.level * 100 + '%');
    console.log('充电状态:', battery.charging ? '充电中' : '未充电');
    
    battery.addEventListener('levelchange', () => {
      console.log('电量变化:', battery.level * 100 + '%');
    });
    
    battery.addEventListener('chargingchange', () => {
      console.log('充电状态变化:', battery.charging ? '充电中' : '未充电');
    });
  });
}

浏览器支付方式检测

检测支持的支付方式:

// 检测Payment Request API支持的支付方式
async function getPaymentMethods() {
  if (!window.PaymentRequest) return [];
  
  try {
    const request = new PaymentRequest(
      [{supportedMethods: 'basic-card'}],
      {total: {label: 'Total', amount: {currency: 'USD', value: '0.01'}}}
    );
    const methods = await request.canMakePayment();
    return methods;
  } catch (e) {
    return [];
  }
}

// 检测特定支付方式
async function supportsPaymentMethod(method) {
  try {
    const request = new PaymentRequest(
      [{supportedMethods: method}],
      {total: {label: 'Total', amount: {currency: 'USD', value: '0.01'}}}
    );
    return await request.canMakePayment();
  } catch (e) {
    return false;
  }
}

浏览器WebRTC检测

检测WebRTC相关功能:

// 检测WebRTC支持
const hasWebRTC = 'RTCPeerConnection' in window || 
                 'webkitRTCPeerConnection' in window ||
                 'mozRTCPeerConnection' in window;

// 获取WebRTC IP泄漏信息
function getRTCPeerConnectionIceServers() {
  const config = {iceServers: [{urls: 'stun:stun.l.google.com:19302'}]};
  const pc = new (window.RTCPeerConnection || 
                 window.webkitRTCPeerConnection || 
                 window.mozRTCPeerConnection)(config);
  
  return new Promise(resolve => {
    pc.createDataChannel('');
    pc.createOffer().then(offer => pc.setLocalDescription(offer));
    
    pc.onicecandidate = ice => {
      if (!ice.candidate) {
        const candidates = pc.localDescription.sdp.match(/a=candidate:.+/g) || [];
        resolve(candidates);
      }
    };
  });
}

浏览器WebXR检测

检测虚拟现实和增强现实支持:

// 检测WebXR API
async function checkWebXRSupport() {
  if (!navigator.xr) return 'unsupported';
  
  try {
    const supported = await navigator.xr.isSessionSupported('immersive-vr');
    return supported ? 'immersive-vr' : 'unsupported';
  } catch (e) {
    return 'unsupported';
  }
}

// 检测AR支持
async function checkARSupport() {
  if (!navigator.xr) return false;
  
  try {
    return await navigator.xr.isSessionSupported('immersive-ar');
  } catch (e) {
    return false;
  }
}

浏览器WebAssembly检测

检测WebAssembly支持情况:

// 检测WebAssembly支持
const hasWasm = typeof WebAssembly === 'object' && 
               typeof WebAssembly.instantiate === 'function';

// 检测特定WebAssembly特性
async function checkWasmFeatures() {
  if (!hasWasm) return {};
  
  try {
    const result = await WebAssembly.validate(new Uint8Array([
      0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00
    ]));
    
    return {
      simd: WebAssembly.validate(new Uint8Array([
        0x00, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00,
        0x01, 0x05, 0x01, 0x60, 0x00, 0x01, 0x7b
      ])),
      threads: WebAssembly.validate(new Uint8Array([

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:对话框方法

下一篇:cookie操作

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌