剪切操作
写入多样化数据
剪切板同时可以写入多种 MIME 类型数据,例如图片、文本、HTML 等。参考 ClipBoardItems
不同读取方会有自己的读取方式,比如在 IM 软件,向微信等,在输入区域粘贴,会优先读取到图片类型的数据。而又比如浏览器的输入框大部分会优先读取文本类型的数据。
将 DOM 当做图片写入剪切板
import html2canvas from 'html2canvas'
const canvas = await html2canvas(document.querySelector('#app'))
const blob = await fetch(canvas.toDataURL('image/png')).then(res => res.blob())
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob,
}),
])写入文本或者 HTML
await navigator.clipboard.write([
new ClipboardItem({
'text/plain': new Blob(['Hello World'], { type: 'text/plain' }),
'text/html': new Blob(['<html><body><h1>Title</h1></body></html>'], { type: 'text/html' }),
}),
])这非常适用于一组数据在多场景下的可用性
案例
举一个例子,点击下面右侧的按钮,将得到图片和文本的复制,方便在不同场景粘贴使用
<script setup lang="ts">
import { VPButton } from 'vitepress/theme'
async function copyData() {
const blob = await fetch('https://share.peterroe.me/public/avatar/avatar.png').then(data => data.blob())
await navigator.clipboard.write([
new ClipboardItem({
[blob.type]: blob,
'text/plain': new Blob(['peterroe'], { type: 'text/plain' }),
'text/html': new Blob(['<html><body><img src="https://share.peterroe.me/public/avatar/avatar.png"/></body></html>'], { type: 'text/html' }),
}),
])
}
</script>
<template>
<VPButton text="复制数据" @click="copyData" />
</template>通过
TIP
UTI 是 Uniform Type Identifier(统一类型标识符) 的缩写,是 macOS 和 iOS 系统中用来标识文件、数据和服务类型的一套标准化字符串
public.png → 表示 PNG 图片 public.html → 表示 HTML 富文本 public.utf8-plain-text → 表示 UTF-8 编码的纯文本
public.png:
public.html:
public.utf8-plain-text:
不同的软件可以根据 UTI 来判断如何处理剪切板中的数据,例如 IM 软件会优先读取图片类型的数据,而浏览器的输入框会优先读取文本类型的数据。
Windows 和 MacOS 系统下的剪切板实现和规范也是不同的,在 Web 层面,通过 ClipboardItem 可以实现跨平台的剪切操作,通过 MIME 类型来指定数据的类型即可