背景与价值

  • 原生异步剪贴板降低阻塞与权限提示干扰;支持多格式(text/html、text/plain)。

复制文本与HTML


async function copyText(text: string) {
  await navigator.clipboard.writeText(text);
}

async function copyHTML(html: string) {
  const blob = new Blob([html], { type: 'text/html' });
  const item = new ClipboardItem({ 'text/html': blob });
  await navigator.clipboard.write([item]);
}

读取与过滤


async function readClipboard() {
  const items = await navigator.clipboard.read();
  for (const item of items) {
    if (item.types.includes('text/html')) {
      const blob = await item.getType('text/html');
      const html = await blob.text();
      const safe = sanitize(html); // 严格过滤,移除脚本与危险属性
      return safe;
    }
  }
}

权限与手势

  • 必须由用户手势触发;读取权限更严格,需明确授权。

指标验证(Chrome 128/Edge 130)

  • 复制成功率:文本 ≥ 99.8%,HTML ≥ 98.5%。
  • 读取成功率:在授权后 ≥ 97%。
  • 安全过滤:恶意脚本与事件属性拦截率 100%。

回退策略

  • 不支持或权限拒绝:提示使用键盘快捷键(Ctrl/Cmd+C/V)与只读文本处理;或降级为 document.execCommand(有限)。

测试清单

  • 文本/HTML 复制与读取路径成功;过滤后内容显示正确。
  • 无权限场景行为合理,用户提示清晰、无重复打扰。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部