HTML5如何检测支持特性_HTML5检测支持特性代码【步骤】

HTML5特性检测应优先使用in操作符判断全局API存在性、typeof检测函数类型、创建元素试探行为,避免依赖UA或documentMode。

HTML5 本身没有统一的“检测支持”API,所有特性检测都依赖具体接口是否存在、能否执行或返回合理值。直接查 document.createElement('video').canPlayType'localStorage' in window 比用第三方库更轻量、更可靠。

in 操作符检测全局 API 存在性

这是最常用也最安全的方式,适用于 localStorage、sessionStorage、history、geolocation 等挂载在 window 上的 API。

  • in 只判断属性是否声明(包括 undefined),不触发 getter,无副作用
  • 避免用 typeof window.localStorage !== 'undefined' —— 在某些旧版 iOS Safari 中会抛错
  • 不要写成 window.localStorage != null,因为未定义时会报 ReferenceError
if ('localStorage' in window) {
  try {
    localStorage.setItem('test', 'ok');
    localStorage.removeItem('test');
  } catch (e) {
    // 私密模式下可能抛 QuotaExceededError
  }
}

typeof 检测函数型接口

URL.createObjectURLf

etchIntersectionObserver 这类必须是函数才能用的特性,优先用 typeof 判断类型。

  • typeof fetch === 'function''fetch' in window 更准确:有些浏览器(如 IE11)有 fetch 属性但值为 undefined
  • 不能只靠存在性,比如 new Audio().play 存在,但调用可能立即 reject,需结合实际调用测试
  • 注意 Promise:ES6+ 环境中它必须是函数,但某些 polyfill 会把 Promise 设为 null 或对象
if (typeof IntersectionObserver === 'function') {
  const io = new IntersectionObserver(callback);
  io.observe(target);
}

用元素方法或属性返回值判断渲染/能力支持

Canvas、Video、Audio、Form validation 等特性无法仅靠存在性判断,必须创建元素并试探其行为。

  • document.createElement('canvas').getContext('2d') 返回 object 才算真正支持 2D Canvas
  • document.createElement('input').checkValidity 存在且为函数,不代表表单验证 UI 一定生效(如 Android WebView 可能静默忽略)
  • audio.canPlayType('audio/mp3') 返回 '''maybe''probably',空字符串即不支持该 MIME 类型
const audio = document.createElement('audio');
const canPlayMP3 = audio.canPlayType('audio/mpeg') !== '';

避免用 document.documentMode 或 UA 字符串做 HTML5 特性推断

IE 的 document.documentMode 只反映文档模式,和 HTML5 支持度无关;UA 字符串不可靠,且现代浏览器已普遍禁用或伪造 UA。

  • Chrome 110+ 默认屏蔽 navigator.userAgent,返回 Chrome/110.0.0.0
  • document.documentMode 在 Edge Chromium 中始终为 undefined
  • 所谓 “IE10+ 支持 localStorage” 是经验结论,不是保证——企业内网策略可能禁用它

真实环境里,哪怕 Modernizr 生成的检测结果,也要在目标设备上实测关键路径。比如 iOS Safari 私密模式下 localStorage 会抛错,而大部分检测脚本根本跑不到那一步。