この内容は古いバージョンです。最新バージョンを表示するには、戻るボタンを押してください。
バージョン:7
ページ更新者:atom
更新日時:2026-06-11 07:07:02

タイトル: API
SEOタイトル: HTML5 / Web API 完全ガイド

この記事の要点
  • Web API = ブラウザが提供し、JavaScript から呼べるインターフェースの総称
  • 分類: DOM 系 (DOM, Fetch) / UI 系 (Canvas, WebGL, Audio) / デバイス系 (Geolocation, Bluetooth) / 背景処理系 (Worker, Service Worker)
  • 標準化: W3C (主に古い API) と WHATWG (HTML Living Standard など現代の主要 API)
  • caniuse.com でブラウザ対応を必ず確認。古いブラウザ向けには Polyfill / Feature Detection
  • Service Worker / Web Push などの強力な API は HTTPS 必須 (localhost を除く)

Web API とは

Web API は、ブラウザが JavaScript から呼べるように提供している組み込み機能の総称です。HTML5 と並んで現代の Web プラットフォームを構成する核となる仕様群です。

たとえば fetch('/api/users') でリクエストが飛ぶのも、document.querySelector('.btn') で DOM 操作できるのも、これらの Web API が JS から呼べるからです。

主要な分類

カテゴリAPI 例用途
DOM / コアDOM, Fetch, URL, FormDataHTML 操作、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);

標準化団体

団体主な仕様
W3CCSS, ARIA, Web Crypto, WebRTC, WebAuthn (Editor 機関)
WHATWGHTML Living Standard, DOM, Fetch, URL, Streams
TC39ECMAScript (JavaScript 言語本体)
KhronosWebGL, 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 インターフェースです。