我的复制文本代码在本地环境中运行良好,但是当我将其部署到生产环境时,文本复制功能无法按预期运行。
这是我正在使用的代码:
const handleCopyClick = (copyableContent, unifiedKey) => {
setCopiedLink(unifiedKey);
new Promise((resolve, reject) => {
navigator.clipboard.writeText(copyableContent)
.then(() => {
resolve();
})
.catch((error) => {
reject(error);
});
})
.then(() => {
setTimeout(() => {
setCopiedLink(null);
}, 2000);
})
.catch((error) => {
setCopiedLink(null);
toastrOnTopCenter("An issue occurred while copying. Please try again.", "error");
});
};
尽管使用基于承诺的方法,我仍然在成功复制文本时遇到问题。
Navigator API 仅适用于安全网站。这意味着它应该是 HTTPS 或应该有 SSL 证书。如果项目位于本地系统中,它将在 localhost 中完美运行:但如果您托管它并且它是 http,则它将无法运行。所以一定要确保生产有保障。