742 commands · 48 cheat sheets · 6 subcategories
HTML master quick reference — Page 4
Browse 199 commands from 12 focused cheat sheets on page 4 of 4. Each example opens its matching detailed section.
Networking and Offline · 14 commands
Service Workers and Offline Caching Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Register within a scope | navigator.serviceWorker.register('/app/sw.js', { scope: '/app/' }) | View examples |
| Wait for an active worker | const registration = await navigator.serviceWorker.ready | View examples |
| Check current control | const controlled = navigator.serviceWorker.controller !== null | View examples |
| Extend installation | event.waitUntil(precachePromise) | View examples |
| Open a named cache | const cache = await caches.open('app-shell-v4') | View examples |
| Precache required URLs | await cache.addAll(['/app/', '/app/offline.html']) | View examples |
| Extend activation | event.waitUntil(deleteOldCaches()) | View examples |
| Claim matching clients | await self.clients.claim() | View examples |
| Activate a waiting update | registration.waiting.postMessage({ type: 'ACTIVATE_UPDATE' }) | View examples |
| Provide a fetch response | event.respondWith(responsePromise) | View examples |
| Find a cached response | const cached = await caches.match(event.request) | View examples |
| Store a response clone | await cache.put(request, response.clone()) | View examples |
| Check for an update | await registration.update() | View examples |
| Observe new control | navigator.serviceWorker.addEventListener('controllerchange', reloadOnce) | View examples |
Networking and Offline · 14 commands
Web Locks and Cross-Tab Coordination Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Request an exclusive lock | await navigator.locks.request('sync', async lock => runSync()) | View examples |
| Detect Web Locks | if (!navigator.locks) useFallback() | View examples |
| Return a callback value | const result = await navigator.locks.request('cache', () => rebuildCache()) | View examples |
| Request a shared lock | await navigator.locks.request('catalog', { mode: 'shared' }, readCatalog) | View examples |
| Try without waiting | await navigator.locks.request('leader', { ifAvailable: true }, lock => lock && lead()) | View examples |
| Bound lock waiting | await navigator.locks.request('sync', { signal: AbortSignal.timeout(5000) }, synchronize) | View examples |
| Cancel a pending request | controller.abort(new DOMException('Navigation', 'AbortError')) | View examples |
| Hold leadership | await navigator.locks.request('primary', () => leadershipLifetime) | View examples |
| Broadcast state | const channel = new BroadcastChannel('app-coordination') | View examples |
| Close messaging | channel.close() | View examples |
| Order nested locks | for (const name of [...names].sort()) await acquire(name) | View examples |
| Snapshot lock state | const { held, pending } = await navigator.locks.query() | View examples |
| Use a storage transaction | const transaction = database.transaction(['queue'], 'readwrite') | View examples |
| Avoid reserved names | const lockName = `document:${documentId}` | View examples |
Networking and Offline · 14 commands
Web Workers and Messaging Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a dedicated worker | const worker = new Worker('/workers/tasks.js') | View examples |
| Create a module worker | new Worker('/workers/tasks.js', { type: 'module', name: 'tasks' }) | View examples |
| Send a typed message | worker.postMessage({ type: 'sum', id, values }) | View examples |
| Receive worker output | worker.addEventListener('message', event => use(event.data)) | View examples |
| Connect to a shared worker | const shared = new SharedWorker('/workers/shared.js', { name: 'counter' }) | View examples |
| Start a message port | shared.port.addEventListener('message', handler); shared.port.start() | View examples |
| Clone structured data | const copy = structuredClone({ map: new Map([['x', 1]]) }) | View examples |
| Transfer an ArrayBuffer | worker.postMessage({ buffer }, [buffer]) | View examples |
| Create a private channel | const { port1, port2 } = new MessageChannel() | View examples |
| Transfer a message port | worker.postMessage({ type: 'attach', port: port2 }, [port2]) | View examples |
| Close a port | port1.close() | View examples |
| Observe worker errors | worker.addEventListener('error', reportWorkerError) | View examples |
| Observe decode failures | worker.addEventListener('messageerror', reportBadMessage) | View examples |
| Terminate immediately | worker.terminate() | View examples |
Networking and Offline · 14 commands
WebRTC Peer Connections Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Create a peer connection | const pc = new RTCPeerConnection({ iceServers }) | View examples |
| Use expiring TURN credentials | iceServers: [{ urls: 'turn:turn.example.com:3478', username, credential }] | View examples |
| Add a local track | pc.addTrack(track, localStream) | View examples |
| Create a transceiver | pc.addTransceiver('video', { direction: 'recvonly' }) | View examples |
| Render remote media | pc.ontrack = event => { remoteVideo.srcObject = event.streams[0] ?? new MediaStream([event.track]) } | View examples |
| Create and signal an offer | await pc.setLocalDescription(); signal({ description: pc.localDescription }) | View examples |
| Apply a remote description | await pc.setRemoteDescription(description) | View examples |
| Signal ICE candidates | pc.onicecandidate = ({ candidate }) => candidate && signal({ candidate }) | View examples |
| Apply a remote candidate | await pc.addIceCandidate(candidate) | View examples |
| Restart failed ICE | pc.restartIce() | View examples |
| Create a data channel | const channel = pc.createDataChannel('chat', { ordered: true }) | View examples |
| Bound buffered data | channel.bufferedAmountLowThreshold = 65536 | View examples |
| Read connection statistics | const report = await pc.getStats() | View examples |
| Close the session | pc.getSenders().forEach(({ track }) => track?.stop()); pc.close() | View examples |
Networking and Offline · 22 commands
WebSockets and Server-Sent Events Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Open a WebSocket | const socket = new WebSocket('wss://realtime.example.com/v1') | View examples |
| Open an event stream | const events = new EventSource('/api/events') | View examples |
| Include cross-origin credentials | const events = new EventSource('https://events.example/stream', { withCredentials: true }) | View examples |
| Offer subprotocols | const socket = new WebSocket(url, ['realtime.v2', 'realtime.v1']) | View examples |
| Wait for an open connection | socket.addEventListener('open', handleOpen, { once: true }) | View examples |
| Check the ready state | if (socket.readyState === WebSocket.OPEN) socket.send(payload) | View examples |
| Start a normal close | socket.close(1000, 'view unmounted') | View examples |
| Send a JSON message | socket.send(JSON.stringify({ type: 'subscribe', topic: 'orders' })) | View examples |
| Receive a WebSocket message | socket.addEventListener('message', event => routeMessage(event.data)) | View examples |
| Receive binary as ArrayBuffer | socket.binaryType = 'arraybuffer' | View examples |
| Send binary data | socket.send(new Uint8Array([1, 2, 3])) | View examples |
| Inspect queued outgoing bytes | const queuedBytes = socket.bufferedAmount | View examples |
| Apply an outgoing high-water mark | if (socket.bufferedAmount
< 262144) socket.send(nextMessage) | View examples |
| Handle default SSE messages | events.addEventListener('message', event => render(JSON.parse(event.data))) | View examples |
| Handle a named SSE event | events.addEventListener('order.updated', handleOrderUpdate) | View examples |
| Read the last event ID | const cursor = event.lastEventId | View examples |
| Resume from an SSE cursor | Last-Event-ID: 1042 | View examples |
| Set the SSE retry delay | retry: 5000 | View examples |
| Send an SSE comment heartbeat | : heartbeat | View examples |
| Inspect EventSource state | if (events.readyState === EventSource.CONNECTING) showReconnecting() | View examples |
| Stop EventSource reconnects | events.close() | View examples |
| Restrict realtime endpoints | Content-Security-Policy: connect-src 'self' wss://realtime.example.com https://events.example.com | View examples |
Security, Storage, and Devices · 15 commands
File System Access and Origin-Private Storage Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Choose files | const [handle] = await showOpenFilePicker({ multiple: false, types }) | View examples |
| Choose a save destination | const handle = await showSaveFilePicker({ suggestedName: 'report.txt', types }) | View examples |
| Choose a directory | const directory = await showDirectoryPicker({ mode: 'readwrite' }) | View examples |
| Query handle permission | const state = await handle.queryPermission({ mode: 'readwrite' }) | View examples |
| Request handle permission | const state = await handle.requestPermission({ mode: 'readwrite' }) | View examples |
| Read a file snapshot | const file = await handle.getFile(); const text = await file.text() | View examples |
| Open a writable stream | const writable = await handle.createWritable({ keepExistingData: true }) | View examples |
| Write and commit | await writable.write(contents); await writable.close() | View examples |
| Get or create a child file | const file = await directory.getFileHandle('notes.txt', { create: true }) | View examples |
| Iterate directory entries | for await (const [name, handle] of directory.entries()) inspect(name, handle) | View examples |
| Remove a directory entry | await directory.removeEntry('cache', { recursive: true }) | View examples |
| Open the OPFS root | const root = await navigator.storage.getDirectory() | View examples |
| Open worker synchronous access | const access = await fileHandle.createSyncAccessHandle() | View examples |
| Estimate storage usage | const { usage, quota } = await navigator.storage.estimate() | View examples |
| Request persistent storage | const persistent = await navigator.storage.persist() | View examples |
Security, Storage, and Devices · 14 commands
HTML File Inputs and File API Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Choose one file | <input id="avatar" name="avatar" type="file"> | View examples |
| Hint accepted formats | <input type="file" accept="image/png,image/jpeg,.webp"> | View examples |
| Choose several files | <input type="file" name="attachments" multiple> | View examples |
| Require a selection | <input type="file" name="document" required> | View examples |
| Access selected files | const files = input.files | View examples |
| Inspect file metadata | const { name, size, type, lastModified } = file | View examples |
| Check a byte limit | if (file.size > 5 * 1024 * 1024) reject(file) | View examples |
| Read text with a promise | const text = await file.text() | View examples |
| Read binary with FileReader | reader.readAsArrayBuffer(file) | View examples |
| Cancel a FileReader read | reader.abort() | View examples |
| Create a local preview URL | const url = URL.createObjectURL(file) | View examples |
| Release a preview URL | URL.revokeObjectURL(url) | View examples |
| Submit multipart form data | <form method="post" enctype="multipart/form-data"> | View examples |
| Build an upload body | formData.append('attachment', file, file.name) | View examples |
Security, Storage, and Devices · 25 commands
Web Authentication and Passkeys Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Detect the WebAuthn interface | if (!window.PublicKeyCredential) showPasswordFallback() | View examples |
| Require a secure context | if (!isSecureContext) throw new Error('WebAuthn requires a secure context') | View examples |
| Start registration on the server | const optionsJSON = await fetch('/api/passkeys/register/options', { method: 'POST' }).then(r => r.json()) | View examples |
| Restrict credential operations | Permissions-Policy: publickey-credentials-create=(self), publickey-credentials-get=(self) | View examples |
| Parse registration options | const publicKey = PublicKeyCredential.parseCreationOptionsFromJSON(optionsJSON.publicKey) | View examples |
| Create a credential | const credential = await navigator.credentials.create({ publicKey, signal: controller.signal }) | View examples |
| Require discoverability | authenticatorSelection: { residentKey: 'required', userVerification: 'required' } | View examples |
| Exclude registered credentials | excludeCredentials: credentials.map(({ id, transports }) => ({ type: 'public-key', id, transports })) | View examples |
| Minimize attestation | attestation: 'none' | View examples |
| Serialize a Level 3 credential | const payload = credential.toJSON() | View examples |
| Encode bytes as base64url | const encoded = bytesToBase64url(new Uint8Array(credential.rawId)) | View examples |
| Verify registration on the server | await verifier.verifyRegistrationResponse({ response, expectedChallenge, expectedOrigin, expectedRPID }) | View examples |
| Store the verified credential | await credentialStore.insert({ accountId, userHandle, credentialId, publicKey, counter, transports }) | View examples |
| Parse authentication options | const publicKey = PublicKeyCredential.parseRequestOptionsFromJSON(optionsJSON.publicKey) | View examples |
| Request an assertion | const assertion = await navigator.credentials.get({ publicKey, signal: controller.signal }) | View examples |
| Enable usernameless discovery | delete publicKey.allowCredentials | View examples |
| Require an expected origin | expectedOrigin: 'https://login.example.com' | View examples |
| Require the registered RP ID | expectedRPID: 'example.com' | View examples |
| Enforce user verification | requireUserVerification: true | View examples |
| Detect conditional mediation | const available = await PublicKeyCredential.isConditionalMediationAvailable() | View examples |
| Mark the autofill field | <input name="username" autocomplete="username webauthn"> | View examples |
| Start a conditional request | const assertion = await navigator.credentials.get({ publicKey, mediation: 'conditional', signal }) | View examples |
| Record transport hints | const transports = credential.response.getTransports() | View examples |
| Cancel a stale ceremony | controller.abort(new DOMException('Replaced by a new request', 'AbortError')) | View examples |
| Classify expected DOM errors | if (error instanceof DOMException && error.name === 'NotAllowedError') showRetry() | View examples |
Security, Storage, and Devices · 14 commands
Web Crypto API Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Generate random bytes | crypto.getRandomValues(new Uint8Array(32)) | View examples |
| Generate a random UUID | const id = crypto.randomUUID() | View examples |
| Hash bytes | const digest = await crypto.subtle.digest('SHA-256', data) | View examples |
| Generate an HMAC key | await crypto.subtle.generateKey({ name: 'HMAC', hash: 'SHA-256' }, false, ['sign', 'verify']) | View examples |
| Verify an HMAC | await crypto.subtle.verify('HMAC', key, tag, message) | View examples |
| Generate an AES-GCM key | await crypto.subtle.generateKey({ name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']) | View examples |
| Encrypt with AES-GCM | await crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData, tagLength: 128 }, key, plaintext) | View examples |
| Decrypt and authenticate | await crypto.subtle.decrypt({ name: 'AES-GCM', iv, additionalData, tagLength: 128 }, key, ciphertext) | View examples |
| Derive a password key | await crypto.subtle.deriveKey({ name: 'PBKDF2', salt, iterations, hash: 'SHA-256' }, baseKey, aes, false, usages) | View examples |
| Expand input key material | await crypto.subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt, info }, baseKey, 256) | View examples |
| Generate an ECDSA pair | await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']) | View examples |
| Verify an ECDSA signature | await crypto.subtle.verify({ name: 'ECDSA', hash: 'SHA-256' }, publicKey, signature, data) | View examples |
| Import a JWK | await crypto.subtle.importKey('jwk', jwk, algorithm, false, ['verify']) | View examples |
| Export a public key | const jwk = await crypto.subtle.exportKey('jwk', publicKey) | View examples |
Security, Storage, and Devices · 18 commands
Web Permissions, Geolocation, and Device Access Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Check the transport context | if (!isSecureContext) throw new Error('Device access requires HTTPS') | View examples |
| Read geolocation permission state | const status = await navigator.permissions.query({ name: 'geolocation' }) | View examples |
| Observe a permission change | status.addEventListener('change', () => updateControls(status.state)) | View examples |
| Restrict location to this origin | Permissions-Policy: geolocation=(self) | View examples |
| Disable camera and microphone | Permissions-Policy: camera=(), microphone=() | View examples |
| Delegate location to one frame | <iframe
src="https://maps.example/"
allow="geolocation"
title="Store map">
</iframe> | View examples |
| Request one position | navigator.geolocation.getCurrentPosition(onPosition, onError, { timeout: 10000, maximumAge: 60000 }) | View examples |
| Watch position changes | const watchId = navigator.geolocation.watchPosition(onPosition, onError, options) | View examples |
| Stop watching location | navigator.geolocation.clearWatch(watchId) | View examples |
| Request camera and microphone | const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true }) | View examples |
| Stop every media track | stream.getTracks().forEach(track => track.stop()) | View examples |
| List exposed media devices | const devices = await navigator.mediaDevices.enumerateDevices() | View examples |
| Request a display surface | const stream = await navigator.mediaDevices.getDisplayMedia({ video: true, audio: false }) | View examples |
| Detect stopped screen sharing | stream.getVideoTracks()[0].addEventListener('ended', handleShareEnded) | View examples |
| Request orientation access | const state = await DeviceOrientationEvent.requestPermission() | View examples |
| Listen for orientation changes | addEventListener('deviceorientation', handleOrientation) | View examples |
| Stop orientation updates | removeEventListener('deviceorientation', handleOrientation) | View examples |
| React to page visibility | document.addEventListener('visibilitychange', () => { if (document.hidden) stopSensitiveAccess() }) | View examples |
Security, Storage, and Devices · 16 commands
Web Security: CSP, SRI, and Trusted Types Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Deny undeclared resource types | Content-Security-Policy: default-src 'none'; base-uri 'none'; object-src 'none' | View examples |
| Allow required same-origin resources | Content-Security-Policy: default-src 'none'; img-src 'self'; style-src 'self'; connect-src 'self' | View examples |
| Authorize a script with a nonce | <script
nonce="RANDOM_BASE64_VALUE"
src="/assets/app.js">
</script> | View examples |
| Require a script nonce | Content-Security-Policy: script-src 'nonce-RANDOM_BASE64_VALUE'; object-src 'none'; base-uri 'none' | View examples |
| Propagate trust from a nonce | Content-Security-Policy: script-src 'nonce-RANDOM_BASE64_VALUE' 'strict-dynamic'; base-uri 'none' | View examples |
| Block hostile framing | Content-Security-Policy: frame-ancestors 'none' | View examples |
| Restrict form submissions | Content-Security-Policy: form-action 'self' https://payments.example | View examples |
| Monitor a candidate policy | Content-Security-Policy-Report-Only: default-src 'self'; report-to csp | View examples |
| Name a reporting endpoint | Reporting-Endpoints: csp="https://example.com/reports/csp" | View examples |
| Verify an external script | <script
src="https://cdn.example/app.js"
integrity="sha384-BASE64_DIGEST"
crossorigin="anonymous">
</script> | View examples |
| Verify an external stylesheet | <link
rel="stylesheet"
href="/assets/site.css"
integrity="sha384-BASE64_DIGEST"> | View examples |
| Require Trusted Types at sinks | Content-Security-Policy: require-trusted-types-for 'script'; trusted-types app-html | View examples |
| Create a TrustedHTML policy | const policy = trustedTypes.createPolicy('app-html', { createHTML: input => sanitize(input) }) | View examples |
| Insert untrusted text safely | output.textContent = untrustedText | View examples |
| Validate a link destination | const url = new URL(candidate, location.origin) | View examples |
| Observe local CSP violations | addEventListener('securitypolicyviolation', event => console.warn(event.effectiveDirective)) | View examples |
Security, Storage, and Devices · 19 commands
Web Storage and IndexedDB Cheat Sheet
| Use | Syntax | Examples |
|---|---|---|
| Save a persistent string | localStorage.setItem('theme', 'dark') | View examples |
| Read a persistent string | const theme = localStorage.getItem('theme') | View examples |
| Remove one stored value | localStorage.removeItem('theme') | View examples |
| Save tab-scoped state | sessionStorage.setItem('draft-step', '2') | View examples |
| Serialize a small object | localStorage.setItem('prefs', JSON.stringify(preferences)) | View examples |
| Observe another document | addEventListener('storage', event => syncPreference(event)) | View examples |
| Open a versioned database | const request = indexedDB.open('notes', 3) | View examples |
| Create an object store | db.createObjectStore('notes', { keyPath: 'id', autoIncrement: true }) | View examples |
| Create a non-unique index | store.createIndex('by-updated', 'updatedAt') | View examples |
| Release an old connection | db.onversionchange = () => db.close() | View examples |
| Start an atomic write | const tx = db.transaction('notes', 'readwrite') | View examples |
| Insert a new record | store.add({ title: 'Plan', updatedAt: Date.now() }) | View examples |
| Insert or replace a record | store.put({ id: 7, title: 'Revised', updatedAt: Date.now() }) | View examples |
| Read by primary key | const request = store.get(7) | View examples |
| Query an index range | const request = index.getAll(IDBKeyRange.lowerBound(cutoff)) | View examples |
| Iterate in reverse order | const request = index.openCursor(null, 'prev') | View examples |
| Estimate usage and quota | const { usage, quota } = await navigator.storage.estimate() | View examples |
| Request persistent storage | const persistent = await navigator.storage.persist() | View examples |
| Delete a database | const request = indexedDB.deleteDatabase('notes') | View examples |



