121 commands · 7 cheat sheets · HTML
Security, Storage, and Devices master quick reference
Browse 121 commands from 7 focused cheat sheets on page 1 of 1. Each example opens its matching detailed section.
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 |



