HU EW
HU EW

Reputation: 93

Not being able to copy URL to Clipboard without adding the protocol https

I am fairly new in working with ASP.NET and Javascript. Recently I came across this problem where I had to copy the URL on a javascript button action and paste on a new tab to visit the website. It does work locally but not on the live server. I found out that it was due to not adding 'https'. Is there any way where it can work without using 'https' like 'http' only?

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");
    });
}

Upvotes: 6

Views: 15642

Answers (1)

Alicia Sykes
Alicia Sykes

Reputation: 7107

As you correctly stated this is due to not using HTTPS. According to MDN Clipboard docs: "This feature is available only in secure contexts". The best option would be to just use HTTPS.


But since you asked for a workaround, here's a (hacky) working sample. It uses the Document.exec command, which in the future will be deprecated in favor of 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);
}

You could then use navigator.clipboard == undefined to use the fallback method, otherwise use the normal navigator.clipboard.writeText(...) function where supported.

E.g, from your above code:

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);
}

Upvotes: 14

Related Questions