Web API 是浏览器提供的原生接口集合,非 JavaScript 语言本身;包括 DOM 操作、fetch、localStorage 等,脱离浏览器(如 Node.js)即不可用;需注意 null 安全、NodeList 转换、样式修改方式、fetch 错误处理、存储序列化及 API 兼容性。
Web API 不是 JavaScript 语言本身的一部分,而是浏览器提供的、供 JS 调用的原生接口集合;它让 JS 能操作 DOM、发起网络请求、管理存储、控制媒体等——离开浏览器环境(比如 Node.js),这些 API 就不可用。
document 和 Element 接口几乎所有前端交互都从这里开始。注意:获取不到元素时 querySelector 返回 null,直接调用 .addEventListener 会报 TypeError: Cannot read property 'addEventListener' of null。
document.querySelector('.btn') 比 getElementById 更灵活,但只返回第一个匹配项document.querySelectorAll('.item'),它返回 NodeList,不是数组,不能直接用 map
,得先转:Array.from(nodeList).map(...) 或用 forEach
element.classList.add('active'),而不是直接拼 element.style.cssText,避免覆盖其他内联样式fetch(),但别忘了它不拒绝 HTTP 错误状态码fetch() 只在网络失败(如断网、DNS 错误)时 reject,而 404、500 这类响应仍算“成功”,需手动检查 response.ok 或 response.status。
fetch('/api/user')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error: ${response.status}`);
}
return response.json();
})
.then(data => console.log(data))
.catch(err => console.error('Fetch failed:', err));
headers: { 'Content-Type': 'application/json' }
credentials: 'include',否则默认不带fetch() 原生不支持 timeout 选项localStorage 和 sessionStorage 只能存字符串试图存对象会自动调用 toString(),结果变成 [object Object]。必须用 JSON.stringify() 和 JSON.parse() 手动编解码。
const user = { id: 123, name: 'Alice' };
localStorage.setItem('user', JSON.stringify(user));
const saved = localStorage.getItem('user');
const parsed = saved ? JSON.parse(saved) : null;
QuotaExceededError,需 try/catch
sessionStorage 关闭标签页即清空,localStorage 持久保存,但不同协议/端口/子域间完全隔离Web API 的边界常被忽略:比如 setTimeout 和 Promise 是 JS 引擎能力,而 navigator.geolocation、AudioContext、IntersectionObserver 才是真正的 Web API——它们依赖浏览器实现,行为和兼容性差异大,查 MDN 时务必看 “Browser compatibility” 表格里的具体版本支持情况。