[javascript] 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?

This question is related to javascript dom clipboard

The answer is


For security reasons, Firefox doesn't allow you to place text on the clipboard. However, there is a work-around 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.

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 it's Google cache)


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

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

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


way too old question but I didn't see this answer anywhere...

Check this link:

http://kb.mozillazine.org/Granting_JavaScript_access_to_the_clipboard

like everybody said, for security reasons is by default disabled. the link above shows the instructions of how to enable it (by editing about:config in firefox or the user.js).

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


From addon code:

In case anyone else was looking for how to do it from chrome code, you can use the nsIClipboardHelper interface as described here: https://developer.mozilla.org/en-US/docs/Using_the_Clipboard


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

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

Thats the one i use to copy and you can set as extra if doesn't support these options you can use :

For Internet Explorer: window.clipboardData.setData(DataFormat, Text) and window.clipboardData.getData(DataFormat)

You can use the DataFormat's Text and Url to getData and setData.

And to delete data:

You can use the DataFormat's File, HTML, Image, Text and URL. PS: You Need To Use window.clipboardData.clearData(DataFormat);

And for other thats not support window.clipboardData and swf flash files you can also use control + c button on your keyboard for windows and for mac its command + c


Building off the excellent answer from @David from Studio.201, this works in Safari, FF, and Chrome. It also ensures no flashing could occur from the 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
    };
})();

In 2017 you can do this (saying this because this thread is almost 9 years old!)

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 copyStringToClipboard('Hello World')

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


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

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

and then if it shows as flash 10, try loading a Shockwave object using javascript. Shockwave can read/write to the clipboard(in all versions) as well using the copyToClipboard() command in lingo.


It is Summer 2015, and with so much turmoil surrounding Flash I thought I'd add a new answer to this question that avoids its use altogether.

clipboard.js is a nice utility that allows copying of text or html data to the clipboard. It's very easy to use, just 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 is also on GitHub


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

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

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


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

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


try creating a memory global variable storing the selection, then the other function can access the variable and do a paste for 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);

}

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

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

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


Use document.execCommand('copy'). Supported in the latest versions of Chrome, Firefox, Edge, and Safari.

_x000D_
_x000D_
function copyText(text){_x000D_
  function selectElementText(element) {_x000D_
    if (document.selection) {_x000D_
      var range = document.body.createTextRange();_x000D_
      range.moveToElementText(element);_x000D_
      range.select();_x000D_
    } else if (window.getSelection) {_x000D_
      var range = document.createRange();_x000D_
      range.selectNode(element);_x000D_
      window.getSelection().removeAllRanges();_x000D_
      window.getSelection().addRange(range);_x000D_
    }_x000D_
  }_x000D_
  var element = document.createElement('DIV');_x000D_
  element.textContent = text;_x000D_
  document.body.appendChild(element);_x000D_
  selectElementText(element);_x000D_
  document.execCommand('copy');_x000D_
  element.remove();_x000D_
}_x000D_
_x000D_
_x000D_
var txt = document.getElementById('txt');_x000D_
var btn = document.getElementById('btn');_x000D_
btn.addEventListener('click', function(){_x000D_
  copyText(txt.value);_x000D_
})
_x000D_
<input id="txt" value="Hello World!" />_x000D_
<button id="btn">Copy To Clipboard</button>
_x000D_
_x000D_
_x000D_


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

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

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

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


Clipboard API is designed to supersede document.execCommand. Safari is still working on support so you should provide a fallback until spec settles and Safari finishes implementation.

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

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


Use modern document.execCommand("copy") and jQuery. See this stackoverflow 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:

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

_x000D_
_x000D_
// JQUERY DOCUMENT_x000D_
;(function ( $, window, document, undefined ) {_x000D_
  _x000D_
  var ClipboardHelper = {_x000D_
_x000D_
    copyElement: function ($element)_x000D_
    {_x000D_
       this.copyText($element.text())_x000D_
    },_x000D_
    copyText:function(text) // Linebreaks with \n_x000D_
    {_x000D_
        var $tempInput =  $("<textarea>");_x000D_
        $("body").append($tempInput);_x000D_
      _x000D_
        //todo prepare Text: remove double whitespaces, trim_x000D_
        _x000D_
        $tempInput.val(text).select();_x000D_
        document.execCommand("copy");_x000D_
        $tempInput.remove();_x000D_
    }_x000D_
};_x000D_
_x000D_
    $(document).ready(function()_x000D_
    {_x000D_
         var $body=$('body');_x000D_
         _x000D_
        $body.on('click', '*[data-copy-text-to-clipboard]', function(event) _x000D_
        {_x000D_
            var $btn=$(this);_x000D_
            var text=$btn.attr('data-copy-text-to-clipboard');_x000D_
            ClipboardHelper.copyText(text);_x000D_
        });_x000D_
      _x000D_
        $body.on('click', '.js-copy-element-to-clipboard', function(event) _x000D_
        {_x000D_
            ClipboardHelper.copyElement($(this));_x000D_
        });_x000D_
_x000D_
    });_x000D_
_x000D_
_x000D_
})( jQuery, window, document );
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<span data-copy-text-to-clipboard=_x000D_
"Hello_x000D_
 World">_x000D_
  Copy Text_x000D_
</span>_x000D_
<br><br>_x000D_
<span class="js-copy-element-to-clipboard">_x000D_
Hello_x000D_
World _x000D_
Element_x000D_
</span>
_x000D_
_x000D_
_x000D_


I've used Github's Clippy for my needs, simple Flash-based button. Works just fine, if one doesn't need styling and is pleased with inserting what to paste on the server-side beforehand.


Online Spreadsheets hook Ctrl+C, Ctrl+V events and transfer focus to a hidden TextArea control and either set its contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.

see also Is it possible to read the clipboard in Firefox, Safari and Chrome using Javascript?


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to clipboard

In reactJS, how to copy text to clipboard? Copy output of a JavaScript variable to the clipboard Leave out quotes when copying from cell How to Copy Text to Clip Board in Android? How does Trello access the user's clipboard? Copying a rsa public key to clipboard Excel VBA code to copy a specific string to clipboard How to make vim paste from (and copy to) system's clipboard? Python script to copy text to clipboard Copy to Clipboard for all Browsers using javascript