浏览器api兼容性检测需“存在性判断+可用性验证”,优先用typeof检查函数/对象类型,构造函数需验证可实例化,原型属性查原型链,敏感api调用前加try/catch,推荐封装复用工具函数。

检测浏览器API兼容性,核心是“存在性判断 + 可用性验证”,避免直接调用未定义属性或方法导致报错。
检测全局对象上的API(如 fetch、localStorage)
优先检查全局对象(window 或 self)是否拥有该属性,且类型为函数或对象。仅检查是否存在不够可靠,例如某些旧版浏览器可能声明了 fetch 但值为 undefined 或 null。
- ✅ 推荐写法:
typeof window.fetch === 'function' - ✅ 更稳妥(兼顾 Worker 环境):
typeof self.fetch === 'function' - ❌ 避免:
!!window.fetch(可能因值为undefined报错)或'fetch' in window(IE 中可能返回true但实际不可用)
检测构造函数或类(如 Promise、IntersectionObserver)
需确认其存在且可被 new 调用。有些环境(如低版本 Android WebView)虽有构造函数名,但无法实例化。
- ✅ 安全检测:
typeof Promise === 'function' && Promise.toString().includes('native code')(辅助判断是否原生实现) - ✅ 实用兜底:
typeof Promise === 'function' ? new Promise(() => {}) : null(尝试实例化并捕获异常) - ✅ 更健壮的封装示例:
<script><br> const supportsIntersectionObserver = () => {<br> try {<br> return typeof IntersectionObserver === 'function' &&<br> typeof IntersectionObserver.prototype.observe === 'function';<br> } catch {<br> return false;<br> }<br> };<br> </script>
检测事件、方法或属性(如 Element.prototype.classList、navigator.clipboard)
对原型链上的成员,应查原型而非实例;对可能抛错的 API(如 clipboard.writeText),需结合 try/catch 和权限判断。
- ✅ 检测
classList:'classList' in document.documentElement(比typeof element.classList !== 'undefined'更早、更安全) - ✅ 检测剪贴板写入:
navigator.clipboard && typeof navigator.clipboard.writeText === 'function',但实际调用前仍需try/catch处理拒绝权限或 DOM 异步限制 - ✅ 检测 CSS 自定义属性支持:
CSS.supports('color', 'var(--c)')(需注意部分老浏览器不支持CSS.supports,可先检测该方法存在性)
封装可复用的兼容性工具函数
将常用检测逻辑抽象为函数,便于维护和复用。避免重复写 typeof xxx === 'xxx' 判断。
- ✅ 基础检测函数:
const hasAPI = (target, key, type = 'function') =>
typeof target === 'object' &&
target !== null &&
typeof target[key] === type; - ✅ 组合式检测(如 Fetch + AbortController):
const supportsModernFetch = () =>
hasAPI(self, 'fetch') &&
hasAPI(self, 'AbortController'); - ✅ 按需加载降级方案:
若IntersectionObserver不可用,自动引入轻量 polyfill 或切换为 scroll 事件监听
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











