46

I know this kind of question has been asked here for many times, including: How do I copy to the clipboard in JavaScript? or How to copy text to the client's clipboard using jQuery?, I'm narrowing the scope:

Condition:

  1. works fine in Google Chrome (would be nice if cross-browser, but not necessary)
  2. with no flash

Is there such a solution or workaround?

3
  • copying with no flash ?? what do you mean ???? Commented Apr 22, 2014 at 5:25
  • @C-link using embed flash is just a overkill but really cross-browser trick:stackoverflow.com/a/3953655/1299675
    – Sam Su
    Commented Apr 22, 2014 at 5:29
  • 2
    There is a copy command in chrome. let a = 'Foo Bar'; copy(a); Then 'Foo Bar' will be in your clipboard.
    – Lex
    Commented Jun 6, 2018 at 1:06

8 Answers 8

32

You can use either document.execCommand('copy') or addEventListener('copy'), or a combination of both.

1. copy selection on custom event

If you want to trigger a copy on some other event than ctrl-c or right click copy, you use document.execCommand('copy'). It'll copy what's currently selected. Like this, on mouseup for example:

elem.onmouseup = function(){
    document.execCommand('copy');
}

EDIT:

document.execCommand('copy') is supported only by Chrome 42, IE9 and Opera 29, but will be supported by firefox 41 (scheduled for september 2015). Note that IE will normally asks for permission to access the clipboard.

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

2. copy custom content on copy triggered by user

Or, you can use addEventListener('copy'), this will interfere with copy event and you can put the content you want there. This suppose user triggers copy.

EDIT:

On Chrome, Firefox and Safari the event has the clipboardData object with setData method. On IE, the clipboardData object is a window property. So this can work on all major browsers provided you validate where is clipboardData.

 elem2.addEventListener('copy', function (e) {
    e.preventDefault();
    if (e.clipboardData) {
        e.clipboardData.setData('text/plain', 'custom content');
    } else if (window.clipboardData) {
        window.clipboardData.setData('Text', 'custom content');
    }

});

https://developer.mozilla.org/en-US/docs/Web/API/ClipboardEvent/clipboardData https://msdn.microsoft.com/en-us/library/ms535220(v=vs.85).aspx

3. a bit of both

Using a combination, you can copy custom content on wanted events. So the first event triggers execCommand, then the listener interferes. For example, put custom content on click on a div.

  elem3.onclick = function () {
        document.execCommand('copy');
    }

   elem3.addEventListener('copy', function (e) {

    e.preventDefault();
    if (e.clipboardData) {
        e.clipboardData.setData('text/plain', 'custom content from click');
    } else if (window.clipboardData) {
        window.clipboardData.setData('Text', 'custom content from click');
    }

});

Using this last one supposes that both approach are supported, as of July 2015, it works only on Chrome 43 (maybe 42 I couldn't test) and IE at least 9 and 10. With Firefox 41 supporting execcommand('copy'), it should work as well.

Note that for most of these methods and properties are declared as either experimental (or even deprecated for IE), so it's to be used carefully, but it looks like it's more and more supported.

Fiddle with all examples: https://jsfiddle.net/jsLfnnvy/12/

2
  • 1
    And be aware that it only works fine in Chrome 43+. See here : developers.google.com/web/updates/2015/04/…
    – Sam Su
    Commented Jul 23, 2015 at 12:23
  • 1
    This worked for me in Chrome 80 except I had to hook copy on document, not on elem3 (which in my case was an input type="button"). But your elem3 (a div) works in the fiddle. Commented Mar 4, 2020 at 15:24
16

I just find another amazing repo on Github.

Modern copy to clipboard. No Flash. Just 3kb gzipped

https://github.com/zenorocha/clipboard.js

Browser Support:

2
  • the thing I don't like about that library is that it just doesn't provide you a javascript function to call, I don't know if it's because of any limitation, but I don't want bootstrap like event binding as it may clash with my JS Framework (think angularJS, knockout, etc) Commented Dec 7, 2017 at 10:22
  • Simple and easy to use. Don't forget to initialize with 'new ClipboardJS('.btn')'. Commented Aug 4, 2019 at 22:28
12

If you don't mind IE/Safari, you can use following (new) API:

var promise = navigator.clipboard.writeText(newClipText)

Read the docs here

11

Variable string can copy to clipboard using below js code.

var text = 'text to copy';
var copyFrom = $('<textarea/>');
copyFrom.css({
 position: "absolute",
 left: "-1000px",
 top: "-1000px",
});
 copyFrom.text(text);
 $('body').append(copyFrom);
 copyFrom.select();
 document.execCommand('copy');
9

Actually for those figuring this out i got it to work in chrome based on @JulianGregoire s answer.

I rewrote the code to make it a bit better in my opinion:

el.onclick = function () {
    var copy = function (e) {
        e.preventDefault();
        console.log('copy');
        var text = "blabla"
        if (e.clipboardData) {
            e.clipboardData.setData('text/plain', text);
        } else if (window.clipboardData) {
            window.clipboardData.setData('Text', text);
        }
    }
    window.addEventListener('copy', copy);
    document.execCommand('copy');
    window.removeEventListener('copy', copy);
}
1
  • Worked perfect! Thanks
    – Aravind
    Commented Mar 7, 2019 at 6:39
1

Beware: I tried the exact same script of Julien Grégoire, however it wasn't triggering the oncopy event listener. The reason, I had user-select CSS for the body-tag.

So make sure you remove it, or set it to initial on the element the event listener is attached to.

Example: https://jsfiddle.net/faimmedia/jsLfnnvy/80/

0

If you're using knockout, like me (for some reason I still am), you'll want to take a look at this question/answer:

How to make KnokoutJS and ClipboardJS work together?

-6
function copyToClipboard(s) {
    if (window.clipboardData && clipboardData.setData) {
        clipboardData.setData('text', s);
    }
}

Then call the function with the text and that should work.

1
  • 4
    This doesn't exist in latest Chrome release as of today (Chrome 39)
    – aikeru
    Commented Nov 24, 2014 at 15:16

Not the answer you're looking for? Browse other questions tagged or ask your own question.