export function copyToClipboard(textToCopy: string) {
if (navigator.clipboard && window.isSecureContext) {
// secure
return navigator.clipboard.writeText(textToCopy);
} else {
// non-secure
let textArea: HTMLTextAreaElement = document.createElement("textarea");
textArea.value = textToCopy;
textArea.style.position = "absolute";
textArea.style.opacity = '0';
textArea.style.left = "-999999px";
textArea.style.top = "-999999px";
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
return new Promise<void>((res, rej) => {
document.execCommand('copy') ? res() : rej();
textArea.remove();
});
}
}
copy to clipboard
最新推荐文章于 2025-09-12 11:40:30 发布
本文介绍了一个JavaScript函数,用于在不同安全环境下(secure和non-secure)实现文本复制到浏览器剪贴板的功能,确保在各种场景下都能无缝工作。
1484

被折叠的 条评论
为什么被折叠?



