Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy / Put text on the clipboard with FireFox, Safari and Chrome

In Internet Explorer I can use the clipboardData object to access the clipboard. How can I do that in FireFox, Safari and/or Chrome?

like image 289
GvS Avatar asked Sep 24 '08 13:09

GvS


People also ask

How do I put text in my clipboard?

Select the text or graphics you want to copy, and press Ctrl+C. Each selection appears in the Clipboard, with the latest at the top. Optionally, repeat step 2 until you've copied all the items you want to use.

How do I give Firefox access to clipboard?

Chosen solution Firefox currently doesn't allow web pages to access the clipboard via JavaScript, so your only option would be to use the keyboard.


2 Answers

For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a workaround available using Flash.

function copyIntoClipboard(text) {      var flashId = 'flashId-HKxmj5';      /* Replace this with your clipboard.swf location */     var clipboardSWF = 'http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf';      if(!document.getElementById(flashId)) {         var div = document.createElement('div');         div.id = flashId;         document.body.appendChild(div);     }     document.getElementById(flashId).innerHTML = '';     var content = '<embed src="' +         clipboardSWF +         '" FlashVars="clipboard=' + encodeURIComponent(text) +         '" width="0" height="0" type="application/x-shockwave-flash"></embed>';     document.getElementById(flashId).innerHTML = content; } 

The only disadvantage is that this requires Flash to be enabled.

The source is currently dead: http://bravo9.com/journal/copying-text-into-the-clipboard-with-javascript-in-firefox-safari-ie-opera-292559a2-cc6c-4ebf-9724-d23e8bc5ad8a/ (and so is its Google cache)

like image 165
ine Avatar answered Sep 28 '22 16:09

ine


There is now a way to easily do this in most modern browsers using

document.execCommand('copy'); 

This will copy currently selected text. You can select a textArea or input field using

document.getElementById('myText').select(); 

To invisibly copy text you can quickly generate a textArea, modify the text in the box, select it, copy it, and then delete the textArea. In most cases this textArea wont even flash onto the screen.

For security reasons, browsers will only allow you copy if a user takes some kind of action (ie. clicking a button). One way to do this would be to add an onClick event to a html button that calls a method which copies the text.

A full example:

function copier(){    document.getElementById('myText').select();    document.execCommand('copy');  }
<button onclick="copier()">Copy</button>  <textarea id="myText">Copy me PLEASE!!!</textarea>
like image 33
pythonHelpRequired Avatar answered Sep 28 '22 18:09

pythonHelpRequired