---
title: "Clipboard 读取:navigator.clipboard.read 与类型过滤"
keywords:
- clipboard.read
- ClipboardItem
- image/png
- text/plain
- 权限与安全
description: "介绍剪贴板读取的权限与类型过滤,使用 navigator.clipboard.read() 读取图片与富文本,限制来源与数据处理,提供示例与回退。"
categories:
- 应用软件
- 系统工具
---
概述
navigator.clipboard.read() 允许读取剪贴板项目(图片/富文本/纯文本),需在安全上下文并获得用户授权。应用应仅读取必要类型并进行清理。
示例
if (navigator.clipboard.read) {
const items = await navigator.clipboard.read()
for (const item of items) {
if (item.types.includes('image/png')) {
const blob = await item.getType('image/png')
preview(blob)
} else if (item.types.includes('text/plain')) {
const text = await (await item.getType('text/plain')).text()
processText(text)
}
}
} else {
// 回退到输入选择与粘贴事件
}
工程建议
- 权限与手势:在用户手势后读取;提示用途与类型。
- 安全与清理:对 HTML 进行 Sanitizer 清理;限制图片大小与类型。
- 兼容:不支持时回退到
paste事件与输入方案。
参考与验证
- MDN Clipboard API 文档:https://developer.mozilla.org/docs/Web/API/Clipboard/read
- Chrome 平台文档:https://developer.chrome.com/docs/web-platform/async-clipboard/

发表评论 取消回复