[ACCEPTED]-Copy / Put text on the clipboard with FireFox, Safari and Chrome-clipboard

Accepted answer
Score: 50

For security reasons, Firefox doesn't allow 5 you to place text on the clipboard. However, there 4 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 3 only disadvantage is that this requires 2 Flash to be enabled.

The source is currently 1 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)

Score: 22

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

document.execCommand('copy');

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

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

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

For 6 security reasons, browsers will only allow 5 you copy if a user takes some kind of action 4 (ie. clicking a button). One way to do this 3 would be to add an onClick event to a html 2 button that calls a method which copies 1 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>
Score: 13

Online spreadsheet applications hook Ctrl + C and 5 Ctrl + V events and transfer focus to a hidden 4 TextArea control and either set its contents 3 to desired new clipboard contents for copy 2 or read its contents after the event had 1 finished for paste.

See also Is it possible to read the clipboard in Firefox, Safari and Chrome using JavaScript?.

Score: 10

It is summer 2015, and with so much turmoil 6 surrounding Flash, here is how to avoid 5 its use altogether.

clipboard.js is a nice utility that 4 allows copying of text or html data to the 3 clipboard. It's very easy to use, just 2 include the .js and use something like this:

<button id='markup-copy'>Copy Button</button>

<script>
document.getElementById('markup-copy').addEventListener('click', function() {
  clipboard.copy({
    'text/plain': 'Markup text. Paste me into a rich text editor.',
    'text/html': '<i>here</i> is some <b>rich text</b>'
  }).then(
    function(){console.log('success'); },
    function(err){console.log('failure', err);
  });

});
</script>

clipboard.js 1 is also on GitHub.

Score: 9

As of 2017, you can do this:

function copyStringToClipboard (string) {
    function handler (event){
        event.clipboardData.setData('text/plain', string);
        event.preventDefault();
        document.removeEventListener('copy', handler, true);
    }

    document.addEventListener('copy', handler, true);
    document.execCommand('copy');
}

And now to copy 3 copyStringToClipboard('Hello, World!')

If you noticed the setData line, and wondered if 2 you can set different data types, the answer 1 is yes.

Score: 8

Firefox does allow you to store data in 10 the clipboard, but due to security implications 9 it is disabled by default. See how to enable 8 it in "Granting JavaScript access to the clipboard" in the Mozilla Firefox knowledge 7 base.

The solution offered by amdfan is the 6 best if you are having a lot of users and 5 configuring their browser isn't an option. Though 4 you could test if the clipboard is available 3 and provide a link for changing the settings, if 2 the users are tech savvy. The JavaScript 1 editor TinyMCE follows this approach.

Score: 5

The copyIntoClipboard() function works for 5 Flash 9, but it appears to be broken by 4 the release of Flash player 10. Here's 3 a solution that does work with the new flash 2 player:

http://bowser.macminicolo.net/~jhuckaby/zeroclipboard/

It's a complex solution, but it does 1 work.

Score: 4

I have to say that none of these solutions 23 really work. I have tried the clipboard solution 22 from the accepted answer, and it does not 21 work with Flash Player 10. I have also 20 tried ZeroClipboard, and I was very happy 19 with it for awhile.

I'm currently using 18 it on my own site (http://www.blogtrog.com), but I've been noticing 17 weird bugs with it. The way ZeroClipboard 16 works is that it puts an invisible flash 15 object over the top of an element on your 14 page. I've found that if my element moves 13 (like when the user resizes the window and 12 i have things right aligned), the ZeroClipboard 11 flash object gets out of whack and is no 10 longer covering the object. I suspect it's 9 probably still sitting where it was originally. They 8 have code that's supposed to stop that, or 7 restick it to the element, but it doesn't 6 seem to work well.

So... in the next version 5 of BlogTrog, I guess I'll follow suit with 4 all the other code highlighters I've seen 3 out in the wild and remove my Copy to Clipboard 2 button. :-(

(I noticed that dp.syntaxhiglighter's 1 Copy to Clipboard is broken now also.)

Score: 3

Check this link:

Granting JavaScript access to the clipboard

Like everybody said, for 9 security reasons, it is by default disabled. The 8 page above shows the instructions of how 7 to enable it (by editing about:config in Firefox or 6 the user.js file).

Fortunately, there is a plugin 5 called "AllowClipboardHelper" which 4 makes things easier with only a few clicks. however 3 you still need to instruct your website's 2 visitors on how to enable the access in 1 Firefox.

Score: 3

Use the modern document.execCommand("copy") and 1 jQuery. See this Stack Overflow answer.

var ClipboardHelper = { // As Object

    copyElement: function ($element)
    {
        this.copyText($element.text())
    },
    copyText:function(text) // Linebreaks with \n
    {
        var $tempInput =  $("<textarea>");
        $("body").append($tempInput);
        $tempInput.val(text).select();
        document.execCommand("copy");
        $tempInput.remove();
    }
};

How to call it:

ClipboardHelper.copyText('Hello\nWorld');
ClipboardHelper.copyElement($('body h1').first());

// jQuery document
;(function ( $, window, document, undefined ) {

    var ClipboardHelper = {

        copyElement: function ($element)
        {
           this.copyText($element.text())
        },
        copyText:function(text) // Linebreaks with \n
        {
            var $tempInput =  $("<textarea>");
            $("body").append($tempInput);

            //todo prepare Text: remove double whitespaces, trim

            $tempInput.val(text).select();
            document.execCommand("copy");
            $tempInput.remove();
        }
    };

    $(document).ready(function()
    {
        var $body = $('body');

        $body.on('click', '*[data-copy-text-to-clipboard]', function(event)
        {
            var $btn = $(this);
            var text = $btn.attr('data-copy-text-to-clipboard');
            ClipboardHelper.copyText(text);
        });

        $body.on('click', '.js-copy-element-to-clipboard', function(event)
        {
            ClipboardHelper.copyElement($(this));
        });
    });
})( jQuery, window, document );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<span data-copy-text-to-clipboard=
    "Hello
     World">
    Copy Text
</span>

<br><br>
<span class="js-copy-element-to-clipboard">
    Hello
    World
    Element
</span>
Score: 2

I've used GitHub's Clippy for my needs and is 4 a simple Flash-based button. It works just 3 fine if one doesn't need styling and is 2 pleased with inserting what to paste on the server-side 1 beforehand.

Score: 1

A slight improvement on the Flash solution 6 is to detect for Flash 10 using swfobject:

http://code.google.com/p/swfobject/

And 5 then if it shows as Flash 10, try loading 4 a Shockwave object using JavaScript. Shockwave 3 can read/write to the clipboard (in all 2 versions) as well using the copyToClipboard() command 1 in Lingo.

Score: 1

http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp works with Flash 10 and all Flash enabled 7 browsers.

Also ZeroClipboard has been updated 6 to avoid the bug mentioned about page scrolling 5 causing the Flash movie to no longer be 4 in the correct place.

Since that method "Requires" the 3 user to click a button to copy this is a 2 convenience to the user and nothing nefarious 1 is occurring.

Score: 1

Try creating a memory global variable storing 3 the selection. Then the other function can 2 access the variable and do a paste. For 1 example,

var memory = ''; // Outside the functions but within the script tag.

function moz_stringCopy(DOMEle, firstPos, secondPos) {

    var copiedString = DOMEle.value.slice(firstPos, secondPos);
    memory = copiedString;
}

function moz_stringPaste(DOMEle, newpos) {

    DOMEle.value = DOMEle.value.slice(0, newpos) + memory + DOMEle.value.slice(newpos);
}
Score: 1

If you support Flash, you can use https://everyplay.com/assets/clipboard.swf and use 13 the flashvars text to set the text.

https://everyplay.com/assets/clipboard.swf?text=It%20Works

That’s 12 the one I use to copy and you can set as 11 extra if it doesn't support these options. You 10 can use:

For Internet Explorer:

window.clipboardData.setData(DataFormat, Text) and 9 window.clipboardData.getData(DataFormat)

You 8 can use the DataFormat's Text and URL to 7 getData and setData.

And to delete data:

You 6 can use the DataFormat's File, HTML, Image, Text 5 and URL. PS: You need to use window.clipboardData.clearData(DataFormat);.

And for other 4 that’s not support window.clipboardData 3 and swf Flash files you can also use Control + C button 2 on your keyboard for Windows and for Mac 1 its Command + C.

Score: 1

From addon code:

For how to do it from Chrome code, you can 2 use the nsIClipboardHelper interface as 1 described here: https://developer.mozilla.org/en-US/docs/Using_the_Clipboard

Score: 1

Use document.execCommand('copy'). It is supported in the latest versions 1 of Chrome, Firefox, Edge, and Safari.

function copyText(text){
  function selectElementText(element) {
    if (document.selection) {
      var range = document.body.createTextRange();
      range.moveToElementText(element);
      range.select();
    } else if (window.getSelection) {
      var range = document.createRange();
      range.selectNode(element);
      window.getSelection().removeAllRanges();
      window.getSelection().addRange(range);
    }
  }
  var element = document.createElement('DIV');
  element.textContent = text;
  document.body.appendChild(element);
  selectElementText(element);
  document.execCommand('copy');
  element.remove();
}


var txt = document.getElementById('txt');
var btn = document.getElementById('btn');
btn.addEventListener('click', function(){
  copyText(txt.value);
})
<input id="txt" value="Hello World!" />
<button id="btn">Copy To Clipboard</button>
Score: 1

Clipboard API is designed to supersede document.execCommand. Safari is still 7 working on support, so you should provide 6 a fallback until the specification settles 5 and Safari finishes implementation.

const permalink = document.querySelector('[rel="bookmark"]');
const output = document.querySelector('output');
permalink.onclick = evt => {
  evt.preventDefault();
  window.navigator.clipboard.writeText(
    permalink.href
  ).then(() => {
    output.textContent = 'Copied';
  }, () => {
    output.textContent = 'Not copied';
  });
};
<a href="https://stackoverflow.com/questions/127040/" rel="bookmark">Permalink</a>
<output></output>

For security 4 reasons clipboard Permissions may be necessary to read 3 and write from the clipboard. If the snippet 2 doesn't work on Stack Overflow give it a 1 shot on localhost or an otherwise trusted domain.

Score: 1

Building off the excellent answer from David from Studio.201, this works 3 in Safari, Firefox, and Chrome. It also 2 ensures no flashing could occur from the 1 textarea by placing it off-screen.

// ================================================================================
// ClipboardClass
// ================================================================================
var ClipboardClass = (function() {

    function copyText(text) {
        // Create temp element off-screen to hold text.
        var tempElem = $('<textarea style="position: absolute; top: -8888px; left: -8888px">');
        $("body").append(tempElem);

        tempElem.val(text).select();
        document.execCommand("copy");
        tempElem.remove();
    }


    // ============================================================================
    // Class API
    // ============================================================================
    return {
        copyText: copyText
    };
})();

More Related questions