Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy to Clipboard in Chrome Extension

I'm making an extension for Google Chrome and I have hit a snag.

I need to copy a readonly textarea's content to the clipboard on click in the popup. Does anyone know the best way to go about this with pure Javascript and no Flash? I also have jQuery loaded in the extension, if that helps any. My current (non-working) code is...

function copyHTMLCB() {
$('#lb_html').select();
$('#lb_html').focus();
textRange = document.lb_html_frm.lb_html.createTextRange();
textRange.execCommand("RemoveFormat");
textRange.execCommand("Copy");
alert("HTML has been copied to your clipboard."); }
like image 949
Kyle Ross Avatar asked Aug 08 '10 21:08

Kyle Ross


People also ask

How do I add clipboard to Chrome?

How to Enable Clipboard Sharing. This hidden feature is available as a flag. To find it, open a new tab, paste chrome://flags into Chrome's Omnibox and then press the Enter key. Search for “Clipboard” in the search box.

Is there a clipboard on Google Chrome?

Like many other platforms, Chrome OS has a clipboard manager.

How do I copy something to the 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.


9 Answers

All credit goes to joelpt, but in case anyone else needs this to work in pure javascript without jQuery (I did), here's an adaptation of his solution:

function copyTextToClipboard(text) {   //Create a textbox field where we can insert text to.    var copyFrom = document.createElement("textarea");    //Set the text content to be the text you wished to copy.   copyFrom.textContent = text;    //Append the textbox field into the body as a child.    //"execCommand()" only works when there exists selected text, and the text is inside    //document.body (meaning the text is part of a valid rendered HTML element).   document.body.appendChild(copyFrom);    //Select all the text!   copyFrom.select();    //Execute command   document.execCommand('copy');    //(Optional) De-select the text using blur().    copyFrom.blur();    //Remove the textbox field from the document.body, so no other JavaScript nor    //other elements can get access to this.   document.body.removeChild(copyFrom); } 
like image 108
Jeff Gran Avatar answered Sep 27 '22 16:09

Jeff Gran


I found that the following works best, as it lets you specify the MIME type of the copied data:

copy: function(str, mimeType) {
  document.oncopy = function(event) {
    event.clipboardData.setData(mimeType, str);
    event.preventDefault();
  };
  document.execCommand("copy", false, null);
}
like image 22
gjuggler Avatar answered Sep 27 '22 15:09

gjuggler


I'm using this simple function to copy any given plaintext to the clipboard (Chrome only, uses jQuery):

// Copy provided text to the clipboard.
function copyTextToClipboard(text) {
    var copyFrom = $('<textarea/>');
    copyFrom.text(text);
    $('body').append(copyFrom);
    copyFrom.select();
    document.execCommand('copy');
    copyFrom.remove();
}

// Usage example
copyTextToClipboard('This text will be copied to the clipboard.');

Due to the fast append-select-copy-remove sequence, it doesn't seem to be necessary to hide the textarea or give it any particular CSS/attributes. At least on my machine, Chrome doesn't even render it to screen before it's removed, even with very large chunks of text.

Note that this will only work within a Chrome extension/app. If you're using a v2 manifest.json you should declare the 'clipboardWrite' permission there; this is mandatory for apps and recommended for extensions.

like image 35
joelpt Avatar answered Sep 27 '22 15:09

joelpt


The Clipboard API is now supported by Chrome, and is designed to replace document.execCommand.

From MDN:

navigator.clipboard.writeText(text).then(() => {
    //clipboard successfully set
}, () => {
    //clipboard write failed, use fallback
});
like image 37
Kartik Soneji Avatar answered Sep 27 '22 15:09

Kartik Soneji


You can copy to clipboard using Experimental Clipboard API, but it is available only in the dev branch of a browser and not enabled by default (more info)..

like image 31
serg Avatar answered Sep 27 '22 16:09

serg


You can't copy a read only bit of text using execCommand("Copy"), it has to be an editable text area. The solution is to create a text input element and copy the text from there. Unfortunately you can't hide that element using display: none or visibility: hidden as that will also stop the select/copy command from working. However, you can 'hide' it using negative margins. Here's what I did in a Chrome Extension popup that obtains a short url. This is the bit of the code that re-writes the popup window with the shorturl (quick and dirty approach ;-)):

document.body.innerHTML = '<p><a href="'+shortlink+'" target="_blank" >'+shortlink+'</a><form style="margin-top: -35px; margin-left: -500px;"><input type="text" id="shortlink" value="'+shortlink+'"></form></p>'
document.getElementById("shortlink").select()
document.execCommand("Copy") 
like image 33
atomicules Avatar answered Sep 27 '22 16:09

atomicules


I read somewhere that there are security restrictions with Javascript that stops you from interacting with the OS. I've had good success with ZeroClipboard in the past (http://code.google.com/p/zeroclipboard/), but it does use Flash. The Bitly website uses it quite effectively: http://bit.ly/

like image 23
pinksy Avatar answered Sep 27 '22 15:09

pinksy


let content = document.getElementById("con");
content.select();
document.execCommand("copy");

The above code works completely fine in every case. Just make sure the field from which you are picking up the content should be an editable field like an input field.

like image 35
webcrawler Avatar answered Sep 27 '22 15:09

webcrawler


Only this worked for me.

document.execCommand doesn't work at all for chrome as it seems to me.

I left execCommand in the code, but probably for one simple reason: So that this shit just was there :)

I wasted a lot of time on it instead of going through my old notes.

    function copy(str, mimeType) {
        document.oncopy = function(event) {
            event.clipboardData.setData(mimeType, str);
            event.preventDefault();
        };
        try{            
            var successful = document.execCommand('copy', false, null);
            var msg = successful ? 'successful' : 'unsuccessful';
            console.log('Copying text command was ' + msg);
            if (!successful){
                navigator.clipboard.writeText(str).then(
                    function() {
                        console.log('successful')
                    }, 
                    function() {
                        console.log('unsuccessful')
                    }
                );
            }
        }catch(ex){console.log('Wow! Clipboard Exeption.\n'+ex)}
    }
like image 33
Garric Avatar answered Sep 27 '22 15:09

Garric