Skip to content Skip to sidebar Skip to footer

Why Copy To Clipboard Doesn't Work Using Javascript?

I'm trying this function: function copyToClipboard(str) { const el = document.createElement('textarea'); el.textContent = str; el.setAttribute('readonly', ''); el.style.position =

Solution 1:

The document.execCommand has been deprecated but still accessible across web browsers

The navigator.clipboard API is an alternative navigator.clipboard

You pass in the text to be copied to the clipboard like so

navigator.clipboard.writeText(str_to_copy).then(success_callback, failure_callback);

Note that the tab must be active for this to work else you won’t have permissions to copy the clipboard

The API is asynchronous so you can use the .then callback to alert the user if copying the clipboard was successful or not. Check out the Can I Use for its availability across web browsers.

Solution 2:

You are creating an element that will be appended to DOM for a split second, just to allow the execCommand("copy")... And that will "display" at left -9999px.

So why the el.setAttribute('readonly', ''); ?

Just remove it and try again. My guess is the el.select(); just doesn't work on a readonly element.

Disclaimer: I did test nothing. But from what I read, this is the only weird thing to mention. Else is to find a duplicate answer or mark it as unreproducible.

Solution 3:

Use this way to copy the text to clipboard.

functioncopyToClipboradFunc() {

      let copiedText = document.getElementById("copyMe");
          copiedText.select();
          copiedText.setSelectionRange(0, 99999);
    
          document.execCommand("copy");
    
          console.log("Copied the text: " + copiedText.value);
    }
<inputtype="text"value="Amoos Check Console"id="copyMe"><buttononclick="copyToClipboradFunc()">Copy to Clipboard</button>

Minor edits in your code.

/*
YOUR CODE
*/functioncopyToClipboard(str) {

const el = document.createElement('textarea');
el.textContent = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
    document.getSelection().rangeCount > 0 ?
    document.getSelection().getRangeAt(0) :
    false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
}
alert("Copy Text: " + str );}
<!-- YOUR CODE  --><buttononclick="copyToClipboard('Your Function Copied')">Copy ( Original Function )</button>

Solution 4:

Well, after some research I found the solution. Thanks to @VLAZ and @a.mola I found out that execCommand is deprecated. So I started to look for alternatives. I found about the clipboard API on this page Using the Clipboard API, that's from https://developer.mozilla.org/, so we know that's serious business. Anyway, here's my working function:

functioncopyToClipboard(str) {
    navigator.permissions.query({
        name: "clipboard-write"
    }).then(result => {
        if (result.state == "granted") {
            navigator.clipboard.writeText(str).then(function () {
                alert("Enlace copiado con succeso!");
            }, function () {
                alert("No fue posible copiar el enlace.");
            });
        }
    });
};

Post a Comment for "Why Copy To Clipboard Doesn't Work Using Javascript?"