jh-front-end-example-2/src/util/CopyToClipboard.js

45 lines
1.2 KiB
JavaScript
Raw Normal View History

2022-05-06 22:29:53 +08:00
/*
* @Author: Billy
* @Date: 2022-03-15 15:18:55
* @LastEditors: Billy
* @LastEditTime: 2022-03-24 14:37:08
* @Description: 剪切板工具
*/
/**
* @description 把字符串粘贴到剪切板
* @param {string} text 要粘贴到剪切板的文字内容
*/
function copyStr(text) {
var aux = document.createElement("input");
aux.setAttribute("value", text);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);
}
/**
* @description 把base64格式的图片粘贴到剪切板
* @param {string} base64 base64格式的图片
*/
async function copyImgBase64(base64) {
if (navigator.clipboard) {
const imgURL = base64;
const data = await fetch(imgURL);
const blob = await data.blob();
await navigator.clipboard.write([
new window.ClipboardItem({
[blob.type]: blob,
}),
]);
} else {
// 如果navigator.clipboard属性返回undefined就说明当前浏览器不支持这个 API
console.log('当前浏览器不支持 navigator.clipboard');
}
}
export default {
copyStr,
copyImgBase64
}