Clipboard API
debt(d3/e3/b3/t5)
Closest to 'default linter catches the common case' (d3). The detection_hints list ESLint with a specific code_pattern `execCommand('copy')`, meaning the deprecated legacy usage is automatically flagged. However, the subtler issues (missing try/catch, calling readText without user gesture) are not caught by default linting rules.
Closest to 'simple parameterised fix' (e3). The quick_fix describes replacing `document.execCommand('copy')` with `await navigator.clipboard.writeText(text)`, wrapping in try/catch, and providing a fallback. This is slightly more than a one-line swap since it requires adding async/await scaffolding and error handling, but it stays within a single component or call site.
Closest to 'localised tax' (b3). The Clipboard API applies only to web contexts and is typically used in isolated UI components or utility functions. It doesn't impose a cross-cutting architectural constraint; only the specific component handling clipboard operations pays the cost of the HTTPS requirement, permission handling, and fallback logic.
Closest to 'notable trap' (t5). The misconception field explicitly states that `navigator.clipboard.writeText()` appears to work universally but silently fails or throws in non-secure contexts (non-HTTPS) and without a user gesture. A developer who's never used this API would naturally assume a standard browser API is broadly available, matching a documented gotcha that most devs eventually encounter.
TL;DR
Explanation
navigator.clipboard.writeText(text) and navigator.clipboard.readText() are Promise-based. For rich content: clipboard.write([new ClipboardItem({'text/html': blob})]).Read requires user permission (clipboard-read) and is only available in focused pages. Write usually doesn't require permission if triggered by user action. The old document.execCommand('copy') is deprecated — it only works synchronously and only with text. Security: clipboard access is restricted to secure contexts (HTTPS) and requires user gesture for write in some browsers.
Common Misconception
Why It Matters
Common Mistakes
- Using document.execCommand('copy') — deprecated and unreliable across browsers.
- Not wrapping clipboard operations in try/catch — permission denied throws.
- Calling readText() without user interaction — blocked by browsers.
Code Examples
// Deprecated approach:
document.execCommand('copy'); // Deprecated, unreliable
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
showToast('Copied!');
} catch (err) {
// Fallback for older browsers:
const el = document.createElement('textarea');
el.value = text;
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
}
}