Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 837
Melab Avatar asked Jul 03 '18 15:07

Melab


People also ask

How do I transfer data to clipboard?

Select the first item that you want to copy, and press CTRL+C. Continue copying items from the same or other files until you have collected all of the items that you want. The Office Clipboard can hold up to 24 items.

How do you add text to your clipboard?

Select the text or graphics you want to copy, and press Ctrl+C. Each selection appears in the Clipboard, with the latest at the top. Optionally, repeat step 2 until you've copied all the items you want to use. Tip: After you open the Clipboard, it stores content that you copy or cut from anywhere.


2 Answers

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

like image 149
Donald Avatar answered Sep 25 '22 02:09

Donald


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">
like image 21
Rohit.007 Avatar answered Sep 24 '22 02:09

Rohit.007