Clipboard Writes Need A Fallback Path
navigator.clipboard.writeText needs a secure context and a user gesture; wiring it into a click handler with a caught failure keeps copy working visibly.
Code
// navigator.clipboard 是异步 API:需要安全上下文与用户手势,失败要有可见退路
async function copyToClipboard(text) {
try {
await navigator.clipboard.writeText(text);
return 'copied';
} catch (error) {
// NotAllowedError(缺用户手势)或权限被拒:提示用户手动复制
return 'manual copy needed: ' + error.name;
}
}
const button = document.createElement('button');
button.textContent = 'Copy build id';
button.addEventListener('click', async () => {
button.textContent = await copyToClipboard('build 2026-11-14');
});
document.body.append(button);
console.log('copyToClipboard wired to the click handler with a visible fallback');How it works
Count the function copyToClipboard as the entire surface area of Clipboard Writes Need A Fallback Path.
Await points sequence the asynchronous work; a rejection lands at the awaiting line.
What to watch for
- Uses
document,navigator, so it needs a browser context — it will not run as-is in Node without shims.
Applying it
Signature: async function copyToClipboard(text)
Statements that matter
button.addEventListener('click', async () => {
button.textContent = await copyToClipboard('build 2026-11-14');
});
return 'manual copy needed: ' + error.name;
await navigator.clipboard.writeText(text);
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.JSONPath TesterTest JSONPath expressions against JSON documents with dot notation, brackets, wildcards, and recursive descent.SVG Path VisualizerParse SVG path d attributes (M/L/H/V/C/S/Q/T/A/Z), render a scaled wireframe preview with vertices and control handles, and compute bounding boxes.
FAQ
- Does Clipboard Writes Need A Fallback Path run in plain Node.js?
- No — it touches `document`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.