剪切操作
写入多样化数据
剪切板同时可以写入多种 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'
const copyData = async () => {
const blob = await fetch('https://fe-book.netlify.app/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://fe-book.netlify.app/avatar.png"/></body></html>'], { type: "text/html" }),
}),
]);
}
</script>
<template>
<VPButton @click="copyData" text="复制数据"></VPButton>
</template>