copyexecCommand粘贴板
document.execCommand(“Copy”) - 该API将被浏览器弃用
export function copyAddress(address:String) {
// 动态创建 textarea 标签
const textarea = document.createElement("textarea");
// 将该 textarea 设为 readonly 防止 iOS 下自动唤起键盘,同时将 textarea 移出可视区域
textarea.readOnly = "readonly";
textarea.style.position = "absolute";
textarea.style.left = "-9999px";
// 将要 copy 的值赋给 textarea 标签的 value 属性
textarea.value = address;
// 将 textarea 插入到 body 中
document.body.appendChild(textarea);
// 选中值并复制
textarea.select();
const result = document.execCommand("Copy");
if (
result &&
typeof address === "string"
) {
window.$message?.success("copy successfully")
}
document.body.removeChild(textarea);
}
/**
* @description 复制内容到剪切板
* @param {string} content 文本内容
*/
export function clearClipboard () {
const dom = document.createElement('input');
document.body.appendChild(dom);
dom.value = '';
dom.select();
document.execCommand('copy');
document.body.removeChild(dom);
};
clipboard API
/**
* @description 读取剪切板内容
* @return {string}
*/
export async function readClipboard() {
const result = await navigator.permissions.query({ name: 'clipboard-read' });
if (result.state === 'granted' || result.state === 'prompt') {
return navigator.clipboard
.readText()
.then(text => text)
.catch(err => Promise.reject(err));
}
return Promise.reject(result);
}
/**
* @description: 新Clipboard API
* @param {string} text
* @return {*}
*/
export async function writeClipboard(text: string, successContent: string) {
try {
await navigator.clipboard.writeText(text);
window.$message?.success(successContent);
} catch (error) {
console.log(error);
}
}
/**
* @description 复制内容到剪切板
* @param {string} content 文本内容
*/
export async function clearClipboard () {
try {
await navigator.clipboard.writeText("")
} catch (error) {
console.error('Failed to copy: ', error);
}
};