Skip to content

Clipboard API 不可用

快速摘要

你调用了 navigator.clipboard.writeText 但 clipboard 为 undefined——页面不在安全上下文或浏览器不支持。

为什么发生

  • 页面通过 HTTP 提供(clipboard 需要 HTTPS 或 localhost)

  • 旧浏览器无异步 Clipboard API

  • 调用时文档未聚焦

最小示例

✗ 错误代码
navigator.clipboard.writeText('hello'); // TypeError: Cannot read properties of undefined (reading 'writeText')
✓ 修复代码
async function copy(text) {
  if (navigator.clipboard) {
    await navigator.clipboard.writeText(text);
  } else {
    const ta = document.createElement('textarea');
    ta.value = text; document.body.appendChild(ta); ta.select();
    document.execCommand('copy'); ta.remove();
  }
}

HTTP 下 navigator.clipboard 为 undefined,writeText 抛错。特性检测并回退到 execCommand('copy') 可处理旧版与非安全上下文。

如何诊断

  • 检查 typeof navigator.clipboard === 'undefined'

  • 确认 location.protocol 为 https: 或 hostname 为 localhost

  • 确保调用发生在用户手势后且文档聚焦时

如何修复

  • 特性检测:if (navigator.clipboard) ... 否则回退到 execCommand

  • 通过 HTTPS 提供以使 Clipboard API 可用

  • 用 document.execCommand('copy') 作为旧版回退

如何预防

  • 使用 navigator.clipboard 前始终特性检测

  • 为非安全上下文与旧浏览器提供回退

相关资源

相关术语

相关课程

  • HTTP

    学习 clipboard API。

← 返回语言