JavaScript API是浏览器内置的工具箱,提供DOM操作、网络请求、本地存储、地理位置等能力,挂载于window对象,调用需注意兼容性、权限和异步处理。
JavaScript API 是浏览器提供的一组预定义功能,让你能用 JavaScript 控制网页行为、访问设备能力、处理数据或与用户交互。它不是你写的代码,而是浏览器“自带的工具箱”,比如弹出提示框、获取当前时间、操作网页结构、发送网络请求、读取本地存储等。
这些 API 直接挂载在全局 window 对象上(所以通常可以直接调用,不用额外导入):
document.getElementById()、element.addEventListener()
fetch('/api/data').then(r => r.json())
localStorage.setItem('theme', 'dark')
new Date().getFullYear()
navigator.geolocation.getCurrentPosition(...)
console.log()、console.error()
绝大多数浏览器 API 都通过对象方法或属性调用,语法和普通 JS 函数一样,但要注意使用条件和权限限制:
alert('Hello')、location.href = 'https://example.com'
navigator.onLine 判断是否联网,document.body.innerHTML = '...' 修改页面内容
fetch、geolocation)通常返回 Promise 或需要传回调函数,记得用 then() 或 async/await 处理结果不是所有 API 在每个浏览器或版本中都支持,调用前建议检测:
typeof 或 in 检查是否存在,例如:if ('fetch' in window) { ... }
XMLHttpRequest
这段代码展示了真实场景中如何调用 Geolocation API,并处理成功与失败情况:
if ('geolocation' in navigator) {
navigator.geolocation.getCurrentPosition(
(position) => {
const { latitude, longitude } = position.coords;
console.log(`纬度:${latitude},经度:${longitude}`);
},
(error) => {
console.error('定位失败:', error.message);
}
);
} else {
console.warn('当前浏览器不支持地理位置');
}