How to copy to the clipboard in JavaScript?

October 02, 2022 No comments javascript clipboard copy

Introduction

In JavaScript, we may need to copy text to the clipboard.

In this article, we'll show how to do it.

How to copy to the clipboard in JavaScript

To copy text to the clipboard in JavaScript we need to use document.queryCommandSupported("copy") or document.execCommand("copy") if the first method is not supported by the browser.

Note that document.execCommand('copy') is deprecated but some browsers still support that command.

function copyToClipboard(text) {
    if (window.clipboardData && window.clipboardData.setData) {
        // IE specific code path to prevent textarea being shown while dialog is visible.
        return clipboardData.setData("Text", text); 

    } else if (document.queryCommandSupported && document.queryCommandSupported("copy")) {
        var textarea = document.createElement("textarea");
        textarea.textContent = text;
        textarea.style.position = "fixed";  // Prevent scrolling to bottom of page in MS Edge.
        document.body.appendChild(textarea);
        textarea.select();
        try {
            return document.execCommand("copy");  // Security exception may be thrown by some browsers.
        } catch (ex) {
            console.warn("Copy to clipboard failed.", ex);
            return false;
        } finally {
            document.body.removeChild(textarea);
        }
    }
}

document.querySelector("#copy").onclick = function() {
    var result = copyToClipboard(new Date().toString());
    console.log("copied?", result);
};
<button id="copy">Copy to clipboard</button>

The copyToClipboard function copies a string to the clipboard. This function must be called from within an event handler for example button click.

The function may return false if it failed.

Conclusion

In this article, we presented how to copy a string to the clipboard in JavaScript.

{{ message }}

{{ 'Comments are closed.' | trans }}