如果不添加 https 协议,则无法将 URL 复制到剪贴板

HU *_* EW 2 javascript

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

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");
    });
}
Run Code Online (Sandbox Code Playgroud)

Ali*_*cia 9

正如您正确指出的那样,这是由于未使用 HTTPS。根据 MDNClipboard文档: “此功能仅在安全上下文中可用”最好的选择是仅使用 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);
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用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);
}

Run Code Online (Sandbox Code Playgroud)

  • 很好的解决方案,但有点烦人,滚动到文档末尾新创建的元素,为了避免这种情况,只需使用“textArea.focus({preventScroll:true});”而不是“textArea.focus();” (2认同)