gpt4 book ai didi

javascript - 不添加协议(protocol) https 就无法将 URL 复制到剪贴板

转载 作者:行者123 更新时间:2023-12-02 01:36:52 29 4
gpt4 key购买 nike

我在使用 ASP.NET 和 Javascript 方面相当陌生。最近我遇到了这个问题,我必须在 javascript 按钮操作上复制 URL 并粘贴到新选项卡上才能访问该网站。它确实可以在本地工作,但不能在实时服务器上工作。我发现这是因为没有添加“https”。有什么方法可以在不使用像“http”这样的“https”的情况下工作吗?

function CopyTextFunction() {
const params = new URLSearchParams(window.location.search);
params.get('ID')
var copyText = "https://randomshop.net/OnlineShop/ShopProducts?ID=" + params.get('ID');
console.log(copyText);
navigator.clipboard
.writeText(copyText)
.then(() => {
alert("successfully copied");
})
.catch(() => {
alert("something went wrong");
});
}

最佳答案

正如您正确指出的那样,这是由于未使用 HTTPS。根据 MDN Clipboard文档:“此功能仅在 secure contexts 中可用”最好的选择是只使用 HTTPS。


但由于您要求解决方法,这里有一个(hacky)工作示例。它使用 Document.exec命令,将来会弃用,取而代之的是 ClipboardAPI .

function unsecuredCopyToClipboard(text) {
const textArea = document.createElement("textarea");
textArea.value = text;
document.body.appendChild(textArea);
textArea.focus();
textArea.select();
try {
document.execCommand('copy');
} catch (err) {
console.error('Unable to copy to clipboard', err);
}
document.body.removeChild(textArea);
}

然后您可以使用 navigator.clipboard == undefined 来使用回退方法,否则使用支持的普通 navigator.clipboard.writeText(...) 函数.

例如,从您上面的代码:

const copyText = `https://randomshop.net/OnlineShop/ShopProducts?ID=${params.get('ID')}`;

if (navigator.clipboard) { // If normal copy method available, use it
navigator.clipboard.writeText(copyText);
} else { // Otherwise fallback to the above function
unsecuredCopyToClipboard(copyText);
}

关于javascript - 不添加协议(protocol) https 就无法将 URL 复制到剪贴板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72237719/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com