62

I want to have a button which selects the text in a textarea and copies it to the clipboard. I can't seem to find any solutions which work in all browsers and don't use flash.

Surely this is doable? I've seen it all over the place but I guess they use flash, which I really want to stay away from if possible as some people don't have it.

This is what I have so far - it just selects the text:

function copyCode() {
  $("#output-code").focus();
  $("#output-code").select();
}

(The focus is not strictly necessary)

Nick Brunt
  • 9,533
  • 10
  • 54
  • 83

6 Answers6

71

execCommand('copy')

There is a very new option. It is cross-browser but it will take time until everyone has updated their browser.

It works by using the document.execCommand('copy'); function. With this function you'll copy the select text. This will not only work with textareas but with every selected text on the webpage (like in span, p, div, etc.).

Available in Internet Explorer 10+, Chrome 43+, Opera 29+ and Firefox 41+ (see execCommand compatibility here).

Example

// Setup the variables
var textarea = document.getElementById("textarea");
var answer  = document.getElementById("copyAnswer");
var copy    = document.getElementById("copyBlock");
copy.addEventListener('click', function(e) {

   // Select some text (you could also create a range)
   textarea.select(); 

   // Use try & catch for unsupported browser
   try {

       // The important part (copy selected text)
       var ok = document.execCommand('copy');

       if (ok) answer.innerHTML = 'Copied!';
       else    answer.innerHTML = 'Unable to copy!';
   } catch (err) {
       answer.innerHTML = 'Unsupported Browser!';
   }
});
<textarea id="textarea" rows="6" cols="40">
Lorem ipsum dolor sit amet, eamsemper maiestatis no.
</textarea><br/>

<button id="copyBlock">Click to copy</button> <span id="copyAnswer"></span>
   
Lonami
  • 5,945
  • 2
  • 20
  • 38
arc
  • 4,553
  • 5
  • 34
  • 43
18

This answer, while accurate in 2011, is now considerably out of date. See arc's answer, or https://stackoverflow.com/a/30810322/489560


You must use the Flash add-in you do not want to use to automatically copy text to the client's clipboard. Browsers are designed like this because a website automatically modifying the client's clipboard without the aid of active-x components is a security concern. Note that active-x components are programs that run on the user's machine and, technically, require the user's consent to be installed. Considering that the Clipboard is an operating system component, be happy that web browsers don't allow websites to highjack it by default.

If the user does not have Flash, has Flash disabled, or has active-x disabled, then he or she probably is paranoid about security and doesn't want you messing with his or her keyboard anyway. At that point, the user would be used to not having much automatic or script-based functionality in websites. It's best to not try to openly defy the wishes of the end user.

Please refer to the following Stack Overflow links:

  1. How do I copy to the clipboard in JavaScript?
  2. Cross Browser Flash Detection in Javascript

The ultimate answer there is to use Zero Clipboard, which is a library that uses a small, invisible Flash movie and JavaScript to use clipboard functionality like you are wanting. The library is available here: https://github.com/zeroclipboard/zeroclipboard The second link shows how to detect if Flash is disabled or not installed, which allows you to display a warning message like you would for JavaScript.

Devin Burke
  • 13,642
  • 12
  • 55
  • 82
  • Good point, if you've disabled flash you probably don't want a site messing with your clipboard. – Abdullah Jibaly Jun 09 '11 at 23:10
  • 1
    I can't exactly see how a button labelled "Select and Copy" below a very distinct textarea is obtrusive or "defying the wishes of the end user"... If they want to do it by hand, there's no obligation to press the button. – Nick Brunt Jun 09 '11 at 23:47
  • @Nick. Right, but how does the client know to discern between you activating a script when the button is pressed versus on page load or arbitrarily? Your method involves user consent, but the browser cannot verify that and so it has been programmed to not automatically allow clipboard manipulation. I'm not calling your button obtrusive; I'm saying Clipboard manipulation is considered a security concern. – Devin Burke Jun 10 '11 at 00:05
  • And as for the wishes of the end user, I meant if the user had his or her settings set to not allow scripting or active-x components, a developer shouldn't try to force it. – Devin Burke Jun 10 '11 at 00:08
  • Yeah I see, it's basically the few people who would do malicious things with that power spoiling it for the rest of us. I'll just settle for selecting the text and leave it to the user to copy it. Thanks for your detailed response. – Nick Brunt Jun 10 '11 at 13:17
  • 48
    Hey, all - instead of giving 100 reasons why this is a bad idea, could someone just answer the question? If it cannot be done, fine, just don't berade folks for wanting to do something a specic way. I have a client who would love a feature like this - as for security, malicious people could always just "bait" someone into clicking something seemingly harmless, so this no-copy approach is really just punishing the majority of people who want the feature for a few who might abuse it... – exoboy Aug 03 '11 at 18:25
  • 1
    Actually, if you are able to use invisible Flash to do the same thing you could do with JS then there is no security :-]. Thankfully the Clipboard API is coming... – Nux Jan 09 '13 at 19:21
9

Now we have Clipboard.js by @zenorocha

To use it, download and call the script on your page.html (or install with bower or npm)

<script src="path_to_script/clipboard.min.js"></script>

Instantiate a new trigger on your script.js

new Clipboard('.trigger');

And go there to see some examples of usage: http://zenorocha.github.io/clipboard.js/#usage

9
function copyTextToClipboard(text) {
    var textArea = document.createElement("textarea");
    textArea.style.position = 'fixed';
    textArea.style.top = 0;
    textArea.style.left = 0;  
    textArea.style.width = '2em';
    textArea.style.height = '2em'; 
    textArea.style.padding = 0;  
    textArea.style.border = 'none';
    textArea.style.outline = 'none';
    textArea.style.boxShadow = 'none';   
    textArea.style.background = 'transparent';
    textArea.value = text;
    textArea.id = 'ta';
    document.body.appendChild(textArea);
    //textArea.select();
    var range = document.createRange();
    range.selectNode(textArea);
    textArea.select();
    window.getSelection().addRange(range);
    try {
        var successful = document.execCommand('copy');
    } catch (err) {
         alert('Oops, unable to copy');
    }
    document.body.removeChild(textArea);
    return successful;
}

I Hope this is helpfull

Liam
  • 27,717
  • 28
  • 128
  • 190
Iyappan
  • 91
  • 1
  • 1
  • 1
    It'd be more helpful if you explained what you'd actually done above? – Liam Sep 02 '16 at 15:16
  • 1
    It creates a hidden element in the DOM, puts the text that came as an argument in the function, copies the content (the text) of the element to the clipboard and removes the element. Simply put, it's a function that allows you to pass a text and it adds it to the clipboard. Quite clever! – Filipe Melo Dec 14 '16 at 13:17
2

This is a pretty late response but for those searching in the future and having trouble with implementing the execCommand('copy') event to work for both desktop and mobile devices.

Cross browser, Mobile friendly and No need to have outside sources or programs

function CopyString(){
    var StringToCopyElement = document.getElementById('YourId');
    StringToCopyElement.select();

    if(document.execCommand('copy')){
        StringToCopyElement.blur();     
    }else{
        CopyStringMobile();
    }
}

function CopyStringMobile(){
    document.getElementById("YourId").selectionStart = 0;
    document.getElementById("YourId").selectionEnd = 999;
    document.execCommand('copy');

    if (window.getSelection) {
      if (window.getSelection().empty) {  // Chrome
        window.getSelection().empty();
      } else if (window.getSelection().removeAllRanges) {  // Firefox
        window.getSelection().removeAllRanges();
      }
    } else if (document.selection) {  // IE?
      document.selection.empty();
    }
}

Set the CopyString() function to a click event on whatever you're looking to fire the event. This is available to be used on both mobile and desktop operating systems.

Explanation

You need to have two different ways of going about selecting the string to copy because as of today, the method for doing so via desktop will not work for mobile devices. I have an if then function to catch if the desktop method worked and if not, to fire the code that will work for a mobile device. This method requires no downloads or links needed. Both methods highlight the text you're looking to copy then fires the copy command to your clipboard, being followed by un-selecting the string you're attempting to copy. You can mix up the code to your liking but this is the way of doing so.

MattOlivos
  • 221
  • 2
  • 7
0

I use the clipboard property within the navigator (broswer).

const text = "THE CONTENT THAT YOU WANT TO COPY TO CLIPBOARD";

// check if navigator has the clipboard property
if(navigator.clipboard){
await navigator.clipboard.writeText(text);
}