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

clipboard, dom, javascript

Solution

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>

Problem

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

Original source

Related problems