navigator.clipboard.writeText并不是所有浏览器都能工作。我尝试了下面的代码。它在firefox上工作和复制,但在opera上,它显示代码被复制的警告,但实际上它没有复制链接,也没有显示错误提示。在浏览器控制台上,它显示了以下错误:Uncaught (in promise) DOMException: Document is not focused.
那么,我如何捕捉到这个错误,以便在提示中显示链接,以便用户手动复制链接?
如果不可能,将当前链接复制到剪贴板的最受支持的方法是什么?
let shareProjectBtn = document.getElementById("share-project-btn");
function copyCurrentURL() {
navigator.clipboard.writeText(window.location.href);
try {
if (navigator.clipboard.value !== null) {
alert("Project's link copied to clipboard");
}
} catch (error) {
window.prompt("Your browser can't copy the link, please copy this link manually",window.location.href);
}
}发布于 2022-08-10 16:24:18
您可以使用Promise.catch()来处理它。下面是一个直接从MDN抓取的例子
navigator.clipboard.writeText("<empty clipboard>").then(() => {
/* clipboard successfully set */
}, () => {
/* clipboard write failed */
});发布于 2022-08-10 16:25:35
navigator.clipboard.writeText返回一个Promise,所以您可以:
将其移动到您的try块中并使用:await navigator.clipboard.writeText(window.location.href)
或使用:
navigator.clipboard.writeText(window.location.href).catch((err) => window.prompt("Your browser can’t copy the link, …"))
您可以在这里阅读更多关于承诺的内容:对象/承诺
https://stackoverflow.com/questions/73309629
复制相似问题