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.

JavascriptResilience

Code

javascriptsnippet
19 lines
// 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

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.