Melab
Melab

Reputation: 2812

Copy data to clipboard without selecting any text

Is there any cross-platform, or even mostly cross-platform, way to copy text to the clipboard in JavaScript without making an element, putting it on the page, and then selecting the text? How do the websites with "Copy to clipboard" buttons do it? I don't want it to use input fields because the idea is to copy anything into the clipboard, even stuff that may not be in an element.

Upvotes: 5

Views: 9586

Answers (3)

Danyu
Danyu

Reputation: 507

You can try Clipboard.js, plenty of examples out there.

Upvotes: 2

Donald
Donald

Reputation: 399

I believe these days you can use navigator.clipboard if you only care about this working in modern versions of chrome, firefox, edge and opera.

https://developer.mozilla.org/en-US/docs/Web/API/Clipboard

e.g.

var amazingText = "Hello World! How sweet the content";
navigator.clipboard.writeText(amazingText);

Your best best for safari, ie,old browsers and anything else support is to check if navigator.clipboard is defined and have a fallback to the old inefficient create throw away element select and copy as a last resort.

I have used this mainly when there is a reasonably large about of data to copy to the clipboard as i have noticed performance issues with the select and exec methods.

Edit*

I briefly looked on the clipboard.js website as suggested and there is a sentence which says "This library relies on both Selection and execCommand APIs." which suggests perhaps it does not provide answer the question. However I have not looked at the source to verify this assumption.

https://clipboardjs.com/#browser-support

Upvotes: 11

Rohit.007
Rohit.007

Reputation: 3502

Hope this is what you looking for.

document.getElementById("copyButton").addEventListener("click", function() {
    copyToClipboard(document.getElementById("txt"));
});

setInterval(function(){
document.getElementById("txt").innerHTML = "Copy Me!!! @ " + new Date().getTime();
},1000);

function copyToClipboard(elem) {
	  // create hidden text element, if it doesn't already exist
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // can just use the original source element for the selection and copy
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // must use a temporary form element for the selection and copy
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // select the content
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    
    // copy the selection
    var succeed;
    try {
    	  succeed = document.execCommand("copy");
    } catch(e) {
        succeed = false;
    }
    // restore original focus
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    
    if (isInput) {
        // restore prior selection
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // clear temporary content
        target.textContent = "";
    }
    return succeed;
}
input {
  width: 400px;
}
<div id="txt">copy me!!!</div><br><br><button id="copyButton">Copy</button><br><br>
<input type="text" placeholder="Click here and press Ctrl-V to see clipboard contents">

Upvotes: 3

Related Questions