最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Why copy to clipboard doesn't work using JavaScript? - Stack Overflow

programmeradmin1浏览0评论

I'm trying this function:

function copyToClipboard(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("Success");}

I've tried with el.value = str; too. What am I doing wrong?

I'm trying this function:

function copyToClipboard(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("Success");}

I've tried with el.value = str; too. What am I doing wrong?

Share Improve this question asked Mar 13, 2021 at 0:09 Ezequias LopesEzequias Lopes 1473 silver badges14 bronze badges 5
  • 2 execCommand has been deprecated – VLAZ Commented Mar 13, 2021 at 0:13
  • Do you see an error? – evolutionxbox Commented Mar 13, 2021 at 0:17
  • The code runs successfully on my browser though. It could be a matter of execCommand not being supported. – a.mola Commented Mar 13, 2021 at 0:57
  • Ohh, it must be that. Not, I don't get any type of error. – Ezequias Lopes Commented Mar 13, 2021 at 0:58
  • Read through the answers for something different though @EzequiasLopes – a.mola Commented Mar 13, 2021 at 1:05
Add a ment  | 

5 Answers 5

Reset to default 4

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.

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.

Use this way to copy the text to clipboard.

 function copyToClipboradFunc() {

      let copiedText = document.getElementById("copyMe");
          copiedText.select();
          copiedText.setSelectionRange(0, 99999);
    
          document.execCommand("copy");
    
          console.log("Copied the text: " + copiedText.value);
    }
 <input type="text" value="Amoos Check Console" id="copyMe">

<button onclick="copyToClipboradFunc()">Copy to Clipboard</button>

Minor edits in your code.

/*
YOUR CODE
*/
function copyToClipboard(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  -->
<button onclick="copyToClipboard('Your Function Copied')">Copy ( Original Function )</button>

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/, so we know that's serious business. Anyway, here's my working function:

function copyToClipboard(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.");
            });
        }
    });
};

I am using this. navigator.clipboard doesnt work for http.

function CopyToClipBoard(textToCopy) {
var successMessage = 'Success! The text was copied to your clipboard';
var errorMessage = 'Oops! Copy to clipboard failed. ';

// navigator clipboard api needs a secure context (https)
if (navigator.clipboard && window.isSecureContext) {

    // navigator clipboard api method'
    navigator.clipboard.writeText(textToCopy).then(
        function () {
            /* clipboard successfully set */
            console.log(successMessage)
        },
        function () {
            /* clipboard write failed */
            console.warn(errorMessage)
        }
    )
} else
    if (document.queryCommandSupported && document.queryCommandSupported("copy")) {

    // text area method
    var textarea = document.createElement("textarea");
    textarea.value = textarea.textContent = textToCopy;
    textarea.style.opacity = "0"; 

    document.body.appendChild(textarea);
    textarea.focus();
        textarea.select();

        var selection = document.getSelection();
        var range = document.createRange();
        
        range.selectNode(textarea);
        selection.removeAllRanges();
        selection.addRange(range);

    try {
        var successful = document.execCommand('copy'); // Security exception may be thrown by some browsers.
        var msg = successful ? console.log(successMessage) : console.warn(errorMessage);
    }
    catch (ex) {
        console.warn(errorMessage, ex);
    }
    finally {
        selection.removeAllRanges();
        document.body.removeChild(textarea);
    }
}
发布评论

评论列表(0)

  1. 暂无评论