import throttle from "lodash/throttle";
const copyToClipboard = throttle(async (text: string) => {
let isCopied = false;
// 兼容
if (!navigator.clipboard) {
isCopied = fallbackCopyTextToClipboard(text);
} else {
try {
await navigator.clipboard.writeText(text);
isCopied = true;
errorMessage.value = "";
} catch (error) {
errorMessage.value = "copy fail: " + error;
isCopied = false;
show("T_Toast_Copy_Error", {
type: "none",
duration: 1500,
});
}
}
if (isCopied) {
alert("T_Toast_Copy_Success);
}
return isCopied;
}, 500);
const fallbackCopyTextToClipboard = (text: string) => {
let isCopied = false;
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed"; // 避免页面在移动的时候变动
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand("copy");
isCopied = true;
errorMessage.value = "";
console.log("Backup: Text copied to clipboard");
} catch (error) {
errorMessage.value = "Backup: Unable to copy";
isCopied = false;
console.error("Backup: Oops, unable to copy", error);
alert("T_Toast_Copy_Error");
}
document.body.removeChild(textArea);
return isCopied;
};
网友评论