1、Navigator.clipboard 在 Web 应用程序中,Clipboard API 可用于实现剪切、复制和粘贴功能
所有 Clipboard API 的方法都是异步的;它们返回一个 Promise 对象,在剪贴板访问完成后被兑现。如果剪贴板访问被拒绝,promise 也会被拒绝。
只有http协议为https或者host为localhost可以使用
try{
// 读取剪切板的内容(异步的)
navigator.clipboard.read().then( res=>{
// 读取剪切板成功
clipboardItems=res
// 判断剪切板内容是否为图片
if (clipboardItems[0].types[0].indexOf('image') > -1) {
// 得到blob对象(异步的)
clipboardItems[0].getType(clipboardItems[0].types[0]).then( b=>{
// blob转换为file对象
const files = new window.File([b], `${Math.floor(Math.random() * 2147483648).toString(36)}.png`, {type: clipboardItems[0].types[0]});
console.log('已粘贴的图片',files)
});
}
})
}catch (e) {
console.log('出错了')
}
2、clipboard的方法
read()从剪贴板读取数据(比如图片)
readText() 从操作系统读取文本
write() 写入任意数据至操作系统剪贴板
writeText() 写入文本至操作系统剪贴板