タイトル: API
SEOタイトル: HTML5 / Web API 完全ガイド
| この記事の要点 |
|
Web API とは
Web API は、ブラウザが JavaScript から呼べるように提供している組み込み機能の総称です。HTML5 と並んで現代の Web プラットフォームを構成する核となる仕様群です。
たとえば fetch('/api/users') でリクエストが飛ぶのも、document.querySelector('.btn') で DOM 操作できるのも、これらの Web API が JS から呼べるからです。
主要な分類
| カテゴリ | API 例 | 用途 |
|---|---|---|
| DOM / コア | DOM, Fetch, URL, FormData | HTML 操作、HTTP 通信 |
| ストレージ | localStorage, sessionStorage, IndexedDB, Cache | クライアントデータ保存 |
| グラフィック | Canvas 2D, WebGL, WebGPU, SVG | 描画 / 3D |
| メディア | Web Audio, Media Stream, WebRTC, WebCodecs | 音声 / カメラ / リアルタイム通信 |
| 背景処理 | Web Workers, Service Worker, SharedWorker | 並列・PWA |
| UI / 入力 | Pointer Events, Gamepad, Web Speech | 入力デバイス |
| デバイス | Geolocation, Bluetooth, USB, Sensor | 位置・周辺機器 |
| セキュリティ | WebAuthn, Credential Management, Web Crypto | 認証 / 暗号 |
| 支払い | Payment Request, Payment Handler | 決済統合 |
| 監視 | IntersectionObserver, ResizeObserver, MutationObserver, PerformanceObserver | 変化検知 |
DOM API
// 要素取得 / 操作
const btn = document.querySelector('#submit');
btn.addEventListener('click', () => alert('clicked'));
// 動的生成
const li = document.createElement('li');
li.textContent = 'item';
li.classList.add('item');
document.querySelector('ul').appendChild(li);
// 属性 / データ
btn.setAttribute('disabled', '');
btn.dataset.userId = '123'; //
Fetch / XHR / WebSocket
// Fetch (XHR の現代版)
const res = await fetch('/api/users', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: 'taro' }),
});
const json = await res.json();
// AbortController でキャンセル可能
const ctrl = new AbortController();
fetch('/slow', { signal: ctrl.signal });
setTimeout(() => ctrl.abort(), 3000);
// WebSocket (双方向通信)
const ws = new WebSocket('wss://example.com/ws');
ws.onmessage = (e) => console.log(e.data);
ws.send('hello');
// Server-Sent Events (片方向)
const sse = new EventSource('/events');
sse.onmessage = (e) => console.log(e.data);
Storage 系
// localStorage: 永続化 (5-10 MB)
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme');
// sessionStorage: タブ閉じたら消える
sessionStorage.setItem('csrf', 'xyz');
// IndexedDB: 大容量 (数百 MB) NoSQL
const req = indexedDB.open('myDb', 1);
req.onupgradeneeded = (e) => {
const db = e.target.result;
db.createObjectStore('users', { keyPath: 'id' });
};
// Cache API (Service Worker と相性◎)
const cache = await caches.open('v1');
await cache.put('/index.html', new Response('...'));
const cached = await cache.match('/index.html');
Canvas / WebGL
// Canvas 2D
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#3498db';
ctx.fillRect(10, 10, 100, 50);
ctx.beginPath();
ctx.arc(200, 50, 40, 0, Math.PI * 2);
ctx.fill();
// WebGL (低レベル 3D)
const gl = canvas.getContext('webgl2');
// WebGPU (次世代、Chrome 113+)
const adapter = await navigator.gpu.requestAdapter();
const device = await adapter.requestDevice();
メディア系 (Audio, WebRTC)
// Web Audio (合成、エフェクト)
const audioCtx = new AudioContext();
const osc = audioCtx.createOscillator();
osc.frequency.value = 440; // 440Hz (ラ)
osc.connect(audioCtx.destination);
osc.start();
setTimeout(() => osc.stop(), 1000);
// マイク / カメラ
const stream = await navigator.mediaDevices.getUserMedia({
audio: true, video: true,
});
document.querySelector('video').srcObject = stream;
// WebRTC (P2P 通信)
const pc = new RTCPeerConnection();
pc.addTrack(stream.getVideoTracks()[0], stream);
// Web Speech (音声認識・合成)
const rec = new (window.SpeechRecognition || window.webkitSpeechRecognition)();
rec.onresult = (e) => console.log(e.results[0][0].transcript);
rec.start();
speechSynthesis.speak(new SpeechSynthesisUtterance('こんにちは'));
Background API
// Web Worker (CPU 重い処理を別スレッド)
const worker = new Worker('/heavy.js');
worker.postMessage({ data: largeArray });
worker.onmessage = (e) => console.log(e.data);
// Service Worker (PWA, オフライン, プッシュ通知)
navigator.serviceWorker.register('/sw.js');
// sw.js 側
self.addEventListener('fetch', (e) => {
e.respondWith(
caches.match(e.request).then(r => r || fetch(e.request))
);
});
// Notifications
await Notification.requestPermission();
new Notification('完了', { body: 'アップロードが完了' });
Observer 系
// IntersectionObserver: 要素が画面に入った検知 (遅延読み込み)
const io = new IntersectionObserver(entries => {
for (const e of entries) {
if (e.isIntersecting) {
e.target.src = e.target.dataset.src;
io.unobserve(e.target);
}
}
});
document.querySelectorAll('img[data-src]').forEach(img => io.observe(img));
// ResizeObserver: 要素サイズ変化検知
new ResizeObserver(entries => {
console.log(entries[0].contentRect.width);
}).observe(document.body);
// MutationObserver: DOM 変化検知
new MutationObserver(muts => console.log(muts))
.observe(document.body, { childList: true, subtree: true });
// PerformanceObserver: パフォーマンスメトリクス
new PerformanceObserver(list => {
for (const e of list.getEntries()) console.log(e);
}).observe({ entryTypes: ['largest-contentful-paint'] });
デバイス系
// Geolocation
navigator.geolocation.getCurrentPosition(pos => {
console.log(pos.coords.latitude, pos.coords.longitude);
});
// Web Bluetooth (Chrome 系)
const device = await navigator.bluetooth.requestDevice({
filters: [{ services: ['battery_service'] }],
});
// Web USB
const usb = await navigator.usb.requestDevice({ filters: [] });
// Gamepad
window.addEventListener('gamepadconnected', e => {
console.log(e.gamepad.id);
});
// DeviceOrientation (スマホ傾き)
window.addEventListener('deviceorientation', e => {
console.log(e.alpha, e.beta, e.gamma);
});
セキュリティ系
// WebAuthn (パスキー、生体認証)
const cred = await navigator.credentials.create({
publicKey: { challenge: new Uint8Array(32), rp: { name: 'My App' }, ... },
});
// Web Crypto API
const data = new TextEncoder().encode('hello');
const hash = await crypto.subtle.digest('SHA-256', data);
const hex = Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0')).join('');
// 安全な乱数
const buf = new Uint8Array(16);
crypto.getRandomValues(buf);
標準化団体
| 団体 | 主な仕様 |
|---|---|
| W3C | CSS, ARIA, Web Crypto, WebRTC, WebAuthn (Editor 機関) |
| WHATWG | HTML Living Standard, DOM, Fetch, URL, Streams |
| TC39 | ECMAScript (JavaScript 言語本体) |
| Khronos | WebGL, WebGPU (3D グラフィック) |
HTTPS 必須の API
セキュリティクリティカルな API は Secure Context (HTTPS or localhost) 必須:
- Service Worker / PWA
- Web Push / Notifications
- Geolocation
- Web Bluetooth / USB
- Web Crypto (一部)
- Clipboard API (書込)
FAQ
Q: ブラウザ対応を確認したい
A: caniuse.com が定番。MDN ドキュメントの各 API ページにも対応表があります。
Q: 古いブラウザで動かない
A: Polyfill (core-js, whatwg-fetch) で機能補完するか、Feature Detection で代替動作にフォールバック。
Q: REST API と Web API の違いは?
A: 別物。REST API はサーバ側 HTTP エンドポイント (例: GET /api/users)。本記事の Web API はブラウザ提供の JS インターフェースです。