92

I found many solutions for copying to the clipboard, but they all either with flash, or for websites side. I'm looking for method copy to clipboard automatically, without flash and for user side, it's for userscripts and of course cross-browser.

Julien Kronegg
  • 4,968
  • 1
  • 47
  • 60
Black_Sun
  • 921
  • 1
  • 6
  • 7
  • Haven't found any, been looking for same thing. Did want to use Flash either thus removed this feature prior creation. – eugeneK Jun 15 '11 at 08:59
  • 2
    duplicate http://stackoverflow.com/questions/400212/how-to-copy-to-clipboard-in-javascript – wizztjh Jun 15 '11 at 09:00
  • 1
    Without using FLASH I doubt you can get it done in various browsers. But there are concrete solution available that can help you get the solution [zeroclipboard](http://code.google.com/p/zeroclipboard/) – Rakesh Sankar Jun 15 '11 at 09:01
  • Rakesh - your "concrete solution" is based on Flash. It wont work in any browser I use. – RobG Jun 15 '11 at 09:04
  • 1
    @wizztjh method in http://stackoverflow.com/questions/400212/how-to-copy-to-clipboard-in-javascript is for site side not for user side @Rakesh zeroclipboard is good but i want to find method completely without Flash – Black_Sun Jun 15 '11 at 09:05
  • I have heard that support for zeroclipboard has been dropped, so it's most likely a new solution will come up – Roland Jun 02 '12 at 18:20
  • Try this: https://clipboardjs.com/ – Andres SK Feb 10 '16 at 14:29

8 Answers8

31

Without flash, it's simply not possible in most browsers. The user's clipboard is a security-relevant resource since it could contain things like passwords or credit card numbers. Thus, browsers rightly don't allow Javascript access to it (some allow it with a warning shown that the user has confirm, or with signed Javascript code, but none of that is cross-browser).

Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
  • 21
    So maybe pages shouldn't be able to read from the clipboard, but why not write to it? =/ – Ajedi32 Feb 14 '14 at 15:00
  • 5
    But then why allow it to happen through an hidden flash that involves zero user notification and feedback? – Eric Grange Aug 13 '14 at 15:40
  • 3
    @EricGrange: Because back in the mid 1990s someone at Netscape decided that for performance reasons, browser plugins would be native binaries and thus able to do pretty much anything. The online world was a far simple place back then, and security not that much of a concern. – Michael Borgwardt Aug 14 '14 at 07:26
  • 4
    While this answer was true in 2011, browsers have come a long way in the fight to kill flash. Please see my answer below. – Hovis Biddle Nov 19 '15 at 00:13
26

I had tryed the flash solution and I don't liked too. Too complex and too slow. What I did was to create a textarea, put the data into that and use the browser "CTRL + C" behavior.

The jQuery javascript part:

// catch the "ctrl" combination keydown
$.ctrl = function(key, callback, args) {
    $(document).keydown(function(e) {
        if(!args) args=[]; // IE barks when args is null
        if(e.keyCode == key && e.ctrlKey) {
            callback.apply(this, args);
            return false;
        }
    });
};

// put your data on the textarea and select all
var performCopy = function() {
    var textArea = $("#textArea1");
    textArea.text('PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.');
    textArea[0].focus();
    textArea[0].select();
};

// bind CTRL + C
$.ctrl('C'.charCodeAt(0), performCopy);

The HTML part:
<textarea id="textArea1"></textarea>

Now, put what do you want to copy in 'PUT THE TEXT TO COPY HERE. CAN BE A FUNCTION.' area. Works fine for me me. You just have to make one CTRL+C combination. The only drawback is that you are going to have an ugly textarea displayed in you site. If you use the style="display:none" the copy solution will not work.

Timo Tijhof
  • 10,032
  • 6
  • 34
  • 48
Julio Saito
  • 410
  • 5
  • 9
  • 6
    This seems to only bind the function of Ctrl+C to a javascript function and not place the data in the OS clipboard. – Ishmael Apr 04 '12 at 16:19
  • sure, thats the idea. Make the browser copy for you. There is a similar solution here: http://knockoutjs.com/examples/clickCounter.html . When you double-click they create a text-area by javascript with the content. – Julio Saito Apr 05 '12 at 17:02
  • did not work for me on osx so I added `e.metaKey` in the keydown comparison, but for some reason, copy action isn't triggered. See this fiddle: http://jsfiddle.net/gableroux/gta67/1/ – GabLeRoux Aug 14 '13 at 21:48
  • 2
    @GabLeRoux the copy function in safari is only enabled when text is selected. This did work previously but an update to safari recently has stopped it. It seems that selecting the text after the key down event is called just doesn't cut it in that browser any more. Still works fine in chrome however. Oh well, might have to fall back to using flash just for that browser.... – Aran Mulholland Oct 30 '13 at 22:55
  • Like this. When you can't hide (for any reason) a element that you don't need to see, you can always put far away from start, like padding-bottom: -1000. – m3nda Nov 30 '14 at 17:49
  • Please check for http://jsfiddle.net/fbgkc3p1/. This script does NOT that you say. Just copies a text into a field, but not into clipboard. Im doing something wrong? – m3nda Nov 30 '14 at 19:39
  • @erm3nda this post is old. it seems that no longer works, indeed. :( – Julio Saito Jan 30 '15 at 18:35
  • @julioS Yes, finally i've succesfull used zClip. Thx. – m3nda Feb 01 '15 at 06:21
16

clipboard.js has just been released to copy to clipboard without the need of Flash

See it in action here > http://zenorocha.github.io/clipboard.js/#example-action

malditojavi
  • 1,074
  • 2
  • 14
  • 28
10

It's finally here! (As long as you don't support Safari or IE8... -_- )

You can now actually handle clipboard actions without Flash. Here's the relevant documentation:

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

https://developers.google.com/web/updates/2015/04/cut-and-copy-commands?hl=en

https://msdn.microsoft.com/en-us/library/hh801227%28v=vs.85%29.aspx#copy

Hovis Biddle
  • 879
  • 9
  • 14
3

While waiting impatiently for Xbrowser support of the Clipboard API...


This will work beautifully in **Chrome, Firefox, Edge, IE**

IE will only prompt the user once to access the Clipboard.
Safari (5.1 at the time of writing) does not support execCommand for copy/cut

/**
 * CLIPBOARD
 * https://stackoverflow.com/a/33337109/383904
 */
const clip = (val) => {  
  const area = document.createElement("textarea");
  area.value = val;
  document.body.appendChild(area);
  area.select();
  if(document.execCommand('copy')) console.log("Copied to clipboard");
  else prompt("Copy to clipboard:\nSelect, Cmd+C, Enter", cont); // Saf, Other
  area.remove();
};


[...document.querySelectorAll(".clip")].forEach(el => {
  el.addEventListener("click", (evt) => {
    evt.preventDefault();
    clip(evt.currentTarget.textContent);
  });
});
<a class="clip" href="#!">Click an item to copy</a><br>
<a class="clip" href="#!"><i>Lorem</i></a><br>
<a class="clip" href="#!"><b>IPSUM</b></a><br>

<textarea placeholder="Paste here to test"></textarea>

All browsers (except Firefox which is able to only handle mime type "plain/text" as far as I've tested) have not implemented the Clipboard API. I.e, trying to read the clipboard event in Chrome using

var clipboardEvent = new ClipboardEvent("copy", {
  dataType: "plain/text",
  data: "Text to be sent to clipboard"
});

throws: Uncaught TypeError: Illegal constructor

The best resource of the unbelievable mess that's happening among browsers and the Clipboard can be seen here (caniuse.com) (→ Follow the comments under "Notes").
MDN says that basic support is "(YES)" for all browsers which is inaccurate cause one would expect at least the API to work, at all.

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
1

You can use a clipboard local to the HTML page. This allows you to copy/cut/paste content WITHIN the HTML page, but not from/to third party applications or between two HTML pages.

This is how you can write a custom function to do this (tested in chrome and firefox):

Here is the FIDDLE that demonstrates how you can do this.

I will also paste the fiddle here for reference.


HTML

<p id="textToCopy">This is the text to be copied</p>
<input id="inputNode" type="text" placeholder="Copied text will be pasted here" /> <br/>

<a href="#" onclick="cb.copy()">copy</a>
<a href="#" onclick="cb.cut()">cut</a>
<a href="#" onclick="cb.paste()">paste</a>

JS

function Clipboard() {
    /* Here we're hardcoding the range of the copy
    and paste. Change to achieve desire behavior. You can
    get the range for a user selection using
    window.getSelection or document.selection on Opera*/
    this.oRange = document.createRange();
    var textNode = document.getElementById("textToCopy");
    var inputNode = document.getElementById("inputNode");
    this.oRange.setStart(textNode,0);
    this.oRange.setEndAfter(textNode);
    /* --------------------------------- */
}

Clipboard.prototype.copy = function() {
    this.oFragment= this.oRange.cloneContents();
};

Clipboard.prototype.cut = function() {
    this.oFragment = this.oRange.extractContents();
};

Clipboard.prototype.paste = function() {
    var cloneFragment=this.oFragment.cloneNode(true)
    inputNode.value = cloneFragment.textContent;
};

window.cb = new Clipboard();
mrBorna
  • 1,757
  • 16
  • 16
  • Hey mtBrona. Is there a way u will attach some jsfiddle for this one? Cannot seems to activate it – neoswf Aug 09 '13 at 00:57
  • Can we pass string here in place of elemnt – Uday A. Navapara Mar 03 '15 at 11:49
  • This works only is you're inside the same `window`. It's **not an actual Clipboard** available to the OS and another browser tab. Also the selection can be easily done using `select()` and than simply `window.getSelection()` – Roko C. Buljan Oct 26 '15 at 01:57
0

document.execCommand('copy') will do what you want. But there was no directly usable examples in this thread without cruft, so here it is:

var textNode = document.querySelector('p').firstChild
var range = document.createRange()
var sel = window.getSelection()

range.setStart(textNode, 0)
range.setEndAfter(textNode)
sel.removeAllRanges()
sel.addRange(range)
document.execCommand('copy')
odinho - Velmont
  • 20,922
  • 6
  • 41
  • 33
-2

There is not way around, you have to use flash. There is a JQuery plugin called jquery.copy that provided cross browser copy and paste by using a flash (swf) file. This is similar to how the syntax highlighter on my blog works.

Once you reference the jquery.copy.js file all you need to do to push data into the clipboard is run the following:

$.copy("some text to copy");

Nice and easy ;)

Talha Ahmed Khan
  • 15,043
  • 10
  • 42
  • 49