Copy selected text to the clipboard WITHOUT using flash - must be cross-browser

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)

Answers:

Answer

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>
   

Answer

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

Answer

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.

Answer

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.

Answer
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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.