0

I need to copy text to the users clipboard. But for some reason this simple snippet is not working (prints false)

<html>
<head>
</head>
<body>
<textarea id="clip">Test</textarea>
<script>

    var ta = document.getElementById('clip');
    ta.focus();
    ta.select();

    setTimeout(function() {
        console.log(document.execCommand('copy'));
    }, 1000);

</script>
</body>
</html>

Is there something I am doing wrong? Any Ideas?

1

4 Answers 4

1

document.execCommand('copy') must be called as a direct result of user action.

For example: click event handler.

Google dev post: https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en

Update: It looks like a duplicate. I advise you to checkout the following response on the similar topic: https://stackoverflow.com/a/30810322/4754887

0

Yes you are right. This is working

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<textarea id="clip" style="position: absolute; left: 100px; top: -100px;">Test</textarea>
<button id="copyButton">Copy To Clipboard</button>
<script>

    document.getElementById('copyButton').addEventListener('click', function() {

        var ta = document.getElementById('clip');

        ta.innerHTML = "Test2";

        ta.focus();
        ta.select();

        console.log(document.execCommand('copy'));

    });

</script>
</body>
</html>
0

..or simpler:

<html>
<head>
</head>
<body>
<textarea id="clip" onclick="copyToClp()">Test</textarea><!-- this executes copyToClp() function on user's click -->
<script>

var ta = document.getElementById('clip');
ta.focus();
ta.select();

function copyToClp(){
    console.log(document.execCommand('copy'));
}

</script>
</body>
</html>
0

Actually, you should use Document.execCommand() (as you did) AND the (so cool) JavaScript Selection API.

Selection API allows you to programatically make a text selection from any HTML element on the page, and it works exactly like pressing CTRL+C on your keyboard. Usefull to quickly grab URLs, long texts, SSH keys, in one click.

You can try something like this :

var button = document.getElementById("yourButtonId");
var content = document.getElementById("yourContentElement");

button.addEventListener("click", function() {
    // Define range and selection.
    var range = document.createRange();
    var selection = window.getSelection();

    // Clear selection from any previous data.
    selection.removeAllRanges();

    range.selectNodeContents(content);
    selection.addRange(range);

    // Copy to clipboard.
    document.execCommand('copy');
}, false);

Edit : One of the advantages of this method is that you can manipulate content in the clipboard after it’s been copied (escaping code, formatting numbers or dates, uppercase, lowercase, changing HTML tags, etc).

Not the answer you're looking for? Browse other questions tagged or ask your own question.