JavaScript Web API

Web API概述

Web API是浏览器提供的一系列API,允许JavaScript与浏览器和网页进行交互。这些API不是JavaScript语言的一部分,而是浏览器提供的扩展功能。

常用的Web API包括:

  • Fetch API:用于网络请求
  • Web Storage:用于客户端存储
  • Canvas API:用于绘制图形
  • DOM API:用于操作文档对象模型
  • BOM API:用于操作浏览器对象模型
  • Geolocation API:用于获取地理位置
  • Web Audio API:用于音频处理
  • Web Socket API:用于实时通信

1. Fetch API

Fetch API提供了一种现代的、基于Promise的方式来进行网络请求。

基本用法

javascript
// 基本GET请求
fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('There was a problem with the fetch operation:', error);
  });

// POST请求
fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    name: 'John',
    age: 30
  })
})
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

与Axios的比较

javascript
// 使用Axios(需要先安装)
axios.get('https://api.example.com/data')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

// 使用Fetch API
fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    console.log(data);
  })
  .catch(error => {
    console.error('Error:', error);
  });

2. Web Storage API

Web Storage API提供了在浏览器中存储数据的能力,包括localStorage和sessionStorage。

localStorage

localStorage用于长期存储数据,数据不会随着浏览器关闭而删除。

javascript
// 存储数据
localStorage.setItem('username', 'John');
localStorage.setItem('age', 30);

// 读取数据
const username = localStorage.getItem('username');
const age = localStorage.getItem('age');

// 删除数据
localStorage.removeItem('age');

// 清空所有数据
localStorage.clear();

// 存储对象
const user = {
  name: 'John',
  age: 30
};

localStorage.setItem('user', JSON.stringify(user));
const storedUser = JSON.parse(localStorage.getItem('user'));

sessionStorage

sessionStorage用于存储会话期间的数据,数据会随着浏览器窗口关闭而删除。

javascript
// 存储数据
sessionStorage.setItem('sessionId', 'abc123');

// 读取数据
const sessionId = sessionStorage.getItem('sessionId');

// 删除数据
sessionStorage.removeItem('sessionId');

// 清空所有数据
sessionStorage.clear();

与Cookie的比较

特性 localStorage sessionStorage Cookie
存储大小 约5MB 约5MB 约4KB
过期时间 长期存储 会话期间 可设置过期时间
发送到服务器 是(每次请求)
跨窗口共享 是(同域名)

3. Canvas API

Canvas API用于在网页上绘制图形。

基本用法

html
<canvas id="myCanvas" width="400" height="200"></canvas>
javascript
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(50, 50, 100, 100);

// 绘制圆形
ctx.fillStyle = 'blue';
ctx.beginPath();
ctx.arc(200, 100, 50, 0, Math.PI * 2);
ctx.fill();

// 绘制文本
ctx.fillStyle = 'black';
ctx.font = '20px Arial';
ctx.fillText('Hello Canvas!', 150, 150);

// 绘制路径
ctx.strokeStyle = 'green';
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(300, 50);
ctx.lineTo(350, 100);
ctx.lineTo(300, 150);
ctx.stroke();

4. Geolocation API

Geolocation API用于获取用户的地理位置。

基本用法

javascript
// 获取当前位置
navigator.geolocation.getCurrentPosition(
  position => {
    console.log('纬度:', position.coords.latitude);
    console.log('经度:', position.coords.longitude);
    console.log('准确度:', position.coords.accuracy);
  },
  error => {
    console.error('获取位置失败:', error.message);
  },
  {
    enableHighAccuracy: true,
    timeout: 5000,
    maximumAge: 0
  }
);

// 监视位置变化
const watchId = navigator.geolocation.watchPosition(
  position => {
    console.log('当前位置:', position.coords.latitude, position.coords.longitude);
  },
  error => {
    console.error('获取位置失败:', error.message);
  }
);

// 停止监视
// navigator.geolocation.clearWatch(watchId);

5. Web Audio API

Web Audio API用于处理音频,包括播放、录制、处理等。

基本用法

javascript
// 创建音频上下文
const audioContext = new (window.AudioContext || window.webkitAudioContext)();

// 加载音频文件
fetch('audio.mp3')
  .then(response => response.arrayBuffer())
  .then(buffer => audioContext.decodeAudioData(buffer))
  .then(audioBuffer => {
    // 创建音频源
    const source = audioContext.createBufferSource();
    source.buffer = audioBuffer;
    
    // 连接到输出
    source.connect(audioContext.destination);
    
    // 播放音频
    source.start();
  })
  .catch(error => {
    console.error('音频加载失败:', error);
  });

6. Web Socket API

Web Socket API用于实现浏览器和服务器之间的实时通信。

基本用法

javascript
// 创建WebSocket连接
const socket = new WebSocket('ws://echo.websocket.org');

// 连接打开事件
socket.addEventListener('open', event => {
  console.log('WebSocket连接已打开');
  socket.send('Hello WebSocket!');
});

// 接收消息事件
socket.addEventListener('message', event => {
  console.log('收到消息:', event.data);
});

// 连接关闭事件
socket.addEventListener('close', event => {
  console.log('WebSocket连接已关闭');
});

// 连接错误事件
socket.addEventListener('error', event => {
  console.error('WebSocket错误:', event);
});

// 发送消息
// socket.send('Another message');

// 关闭连接
// socket.close();

7. Notification API

Notification API用于向用户显示系统通知。

基本用法

javascript
// 请求通知权限
if ('Notification' in window) {
  Notification.requestPermission().then(permission => {
    if (permission === 'granted') {
      // 显示通知
      new Notification('Hello!', {
        body: '这是一条通知消息',
        icon: 'icon.png'
      });
    }
  });
}

8. Intersection Observer API

Intersection Observer API用于观察元素是否进入视口。

基本用法

javascript
// 创建Intersection Observer
const observer = new IntersectionObserver(
  entries => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        // 元素进入视口
        entry.target.classList.add('visible');
        // 停止观察
        observer.unobserve(entry.target);
      }
    });
  },
  {
    threshold: 0.5 // 当元素50%进入视口时触发
  }
);

// 观察元素
const element = document.getElementById('myElement');
observer.observe(element);

9. IndexedDB API

IndexedDB是一种客户端数据库,用于存储大量结构化数据。

基本用法

javascript
// 打开数据库
const request = indexedDB.open('myDatabase', 1);

// 数据库升级事件
request.onupgradeneeded = event => {
  const db = event.target.result;
  
  // 创建对象存储
  const objectStore = db.createObjectStore('users', {
    keyPath: 'id',
    autoIncrement: true
  });
  
  // 创建索引
  objectStore.createIndex('name', 'name', { unique: false });
};

// 数据库打开成功事件
request.onsuccess = event => {
  const db = event.target.result;
  
  // 开始事务
  const transaction = db.transaction(['users'], 'readwrite');
  const objectStore = transaction.objectStore('users');
  
  // 添加数据
  const addRequest = objectStore.add({
    name: 'John',
    age: 30
  });
  
  addRequest.onsuccess = () => {
    console.log('数据添加成功');
  };
  
  // 查询数据
  const getRequest = objectStore.get(1);
  
  getRequest.onsuccess = () => {
    console.log('查询结果:', getRequest.result);
  };
  
  // 事务完成事件
  transaction.oncomplete = () => {
    // 关闭数据库
    db.close();
  };
};

// 数据库打开失败事件
request.onerror = event => {
  console.error('数据库打开失败:', event.target.error);
};

Web API最佳实践

  1. 检查API支持:在使用API之前,检查浏览器是否支持该API

    javascript
    if ('fetch' in window) {
      // 使用Fetch API
    } else {
      // 使用替代方案(如XMLHttpRequest)
    }
    
  2. 处理错误:始终处理API调用可能出现的错误

  3. 考虑性能:避免频繁调用API,合理使用缓存

  4. 尊重用户隐私:在使用需要权限的API(如Geolocation)时,始终请求用户许可

  5. 使用现代API:优先使用现代API(如Fetch API)而不是过时的API(如XMLHttpRequest)

总结

Web API是JavaScript与浏览器和网页交互的桥梁,它们提供了丰富的功能,包括网络请求、客户端存储、图形绘制、地理位置获取等。了解和掌握常用的Web API对于开发现代Web应用至关重要。在使用Web API时,我们应该检查浏览器支持、处理错误、考虑性能并尊重用户隐私。