← 中文资源

简体中文版本

剪贴板写入需要兜底路径

navigator.clipboard.writeText 需要安全上下文与用户手势:把调用接进点击处理并用 try/catch 兜住 NotAllowedError,复制失败时给用户可见的降级提示。

阅读英文原文

实现说明

整个示例围绕函数 copyToClipboard组织。 异步部分依次 await 结果,顺序可预测。

使用要点

  • 用到了 document、navigator,需要在浏览器环境运行,Node 里直接跑会缺 API。

常见问题

「剪贴板写入需要兜底路径」能在裸 Node.js 里跑吗?

不能——document 这些 API 由浏览器提供,Node 进程里拿不到。要执行的话,请在页面里(或 DevTools 控制台)运行。

签名一览:async function copyToClipboard(text)

核心语句

button.addEventListener('click', async () => {
  button.textContent = await copyToClipboard('build 2026-11-14');
});
return 'manual copy needed: ' + error.name;
await navigator.clipboard.writeText(text);

代码示例

// 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');