---
title: Async Clipboard API 富文本复制与粘贴:权限、格式与安全实践
tags:
- Async Clipboard
- navigator.clipboard
- HTML格式
- 权限
- 粘贴处理
description: 使用 Async Clipboard 实现文本与富文本复制/粘贴,治理权限与安全过滤,并给出经验证的成功率与兼容回退方案。
categories:
- 应用软件
- 系统工具
---
背景与价值
- 原生异步剪贴板降低阻塞与权限提示干扰;支持多格式(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 复制与读取路径成功;过滤后内容显示正确。
- 无权限场景行为合理,用户提示清晰、无重复打扰。

发表评论 取消回复