Javascript: Copy To Clipboard Cross Browser

copy Javascript: Copy To Clipboard Cross Browser

If you use any script for syntax highlighting, you’ll see most of them has “copy to clipboard” feature. This is a fascinating thing done with Javascript. So I want to know more about it: how to implement copy to clipboard in Javascript. I did some searches on Google and found many articles which show various solutions. They’re so interesting and I just want to share a small roundup in this article.

Copy to clipboard is very easy in Internet Explorer

Although I (maybe and you) don’t like Internet Explorer, but in this case, it works very cool. To implement a Javascript function that will copy a text string to clipboard, we can do like this:

function copyToClipboard(s) {
    if (window.clipboardData && clipboardData.setData) {
        clipboardData.setData('text', s);
    }
}

(Thanks to Dynamic Tools)

The function checks for clipboardData variable, that available only in IE, and set data for text attribute. So, you can use this function directly in your HTML code like in example below:

<a href="#" id="copy" onclick="copyToClipboard(document.getElementById('pre').innerHTML)">Copy to clipboard</a>
<pre id="pre">
header{margin-bottom:30px}
header h1{font:italic 30px Georgia,serif;color:#999;text-align:center}

.box{width:100px;height:100px;background:red;border-radius:50px}

footer{margin:15px auto}
</pre>

When you click on the link Copy to clipboard, the text in pre tag will be copied.

Flash solution for other browsers

For other browsers, there is still no common solutions with pure Javascript. I found a pure Javascript solution at Dynamic Tools (where I get the function for IE above) but unfortunately, it doesn’t work for me.

Keep searching in Google, I found some solutions that use Flash for other browsers. All of them uses a small flash file that do the main job: copy a text string to clipboard. This flash file is embed into current page, but it’s invisible by setting width and height to 0, like in this code:

function copyToClipboard(s) {
    // ie
    if (window.clipboardData && clipboardData.setData) {
        clipboardData.setData('text', s);
    }
    // others
    else {
        var flashcopier = 'flashcopier';
        if(!document.getElementById(flashcopier)) {
            var divholder = document.createElement('div');
            divholder.id = flashcopier;
            document.body.appendChild(divholder);
        }
        document.getElementById(flashcopier).innerHTML = '';
        var divinfo = '<embed src="_clipboard.swf" FlashVars="clipboard='+encodeURIComponent(s)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
        document.getElementById(flashcopier).innerHTML = divinfo;
    }
}

(Thanks to Jeffrey Larson.)

This idea is good, and works for almost cases. But a problem appears in Flash 10: for security reason, all action with clipboard needs user interaction. That means the flash file cannot automatically put a text string into clipboard without user’s permission.

This problem occurs because the flash file is written with old version of Flash, when security was not focused. To solve this problem, the simplest solution is updated the flash file, that will check for security. CFCruss has written a simple code for Action 2.0′s fix that you might interested in.

So if you have source code of flash file, just update it to work in Flash 10, then you can use the old Javascript code (above) to copy to clipboard.

Zero Clipboard: A Javascript library for copy to clipboard functionality

Because I don’t have any sources of those flash files, I must find another way to make copy to clipboard functionality works. A good approach is finding a well-developed Javascript library, that’s why I found Zero Clipboard.

Zero Clipboard uses a flash file to copy to clipboard. This flash file works properly with Flash 10. It’s a bit complicated to setup and takes me half an hour just to make a simple example with it.

Suppose that we have a HTML section like this:

<div id="copy">Copy to clipboard</div>
<pre id="pre">
header{margin-bottom:30px}
header h1{font:italic 30px Georgia,serif;color:#999;text-align:center}

.box{width:100px;height:100px;background:red;border-radius:50px}

footer{margin:15px auto}
</pre>

We need to copy the content in pre tag when click to “Copy to clipboard” text (note that this is a plain text, not an A tag).

Now download Zero Clipboard to your computer, extract it and copy 2 files: ZeroClipboard.js and ZeroClipboard.swf to same folder as HTML file. Edit the HTML file to include Zero Clipboard script like this:

<script src="ZeroClipboard.js"></script>

Setup the path to SWF file, and create an instance of Zero Clipboard Client:

<script>
ZeroClipboard.setMoviePath('ZeroClipboard.swf');
var clip = new ZeroClipboard.Client();

To copy when the text “Copy to clipboard” is clicked, we add an event to “mouseDown” action – provided by Zero Clipboard – to set a text that will be copied to clipboard:

clip.setText('');

clip.addEventListener('mouseDown', function(){
 var pre = document.getElementById('pre');
 clip.setText(pre.innerHTML);
});

Note that we have to setup an empty string before add event to “mouseDown”.

Last thing is connecting Zero Clipboard to the text “Copy to clipboard” (which is defined with id=”copy”):

clip.glue('copy');
</script>

So our full Javascript code for Zero copy looks like this:

<script src="ZeroClipboard.js"></script>

<script>
ZeroClipboard.setMoviePath('ZeroClipboard.swf');
var clip = new ZeroClipboard.Client();

clip.setText('');

clip.addEventListener('mouseDown', function(){
    var pre = document.getElementById('pre');
    clip.setText(pre.innerHTML);
    alert('Text copied');
});

clip.glue('copy');
</script>

You can go to Wiki page for more information (there’s another demo, too).

Important: If you try to make your own demo, just remember to do it online, it doesn’t work at local computer at all. This is a security restriction by Adobe Flash Player (yeah, another security reason!).

So you can see, a small functionality that we can find in almost blogs, website, is not very easy to implemented! A bad thing is that there’s no pure cross-browser Javascript solution for this exercise. Flash is the only (and the best) solution now.

There is a jQuery plugin for this job, too (it also uses Flash), but sadly I can’t make it work, even the demo at its homepage.

19 Comments

  1. hello, can someone elp me with my code… I tried copying his code but nothing is happening…
    I’m a noob in html so please be considerate on your comments
    this is the code

    ZeroClipboard.setMoviePath(‘http://shimatester.weebly.com/uploads/2/7/9/7/27977971/zeroclipboard.swf’);
    var clip = new ZeroClipboard.Client();
    clip.setText(”);
    clip.addEventListener(‘mouseDown’, function(){
    var pre = document.getElementById(‘pre’);
    clip.setText(pre.innerHTML);
    alert(‘Text copied’);
    });
    clip.glue(‘copy’);

    Copy to clipboard

    header{margin-bottom:30px}
    header h1{font:italic 30px Georgia,serif;color:#999;text-align:center}
    .box{width:100px;height:100px;background:red;border-radius:50px}
    footer{margin:15px auto}

    Reply
  2. Wow.. excellent.. i’d been looking for such a nice script and only needed for IE.. thanks man!

    Reply
  3. What’s up, its fastidious article on the topic of media print, we all know media is a wonderful source of information.

    Reply
  4. Hi all,
    I use your swf soluce too but I want to do a paste button but I can’t find any soluce and I don’t know what to do..

    $(document).ready(function () {

    ZeroClipboard.setMoviePath('ZeroClipboard.swf');

    var clip = new ZeroClipboard.Client();

    clip.addEventListener('mousedown', function () {
    //it's there that I have to fill the input text but I don't know what to do...
    $('[id$=tbp]').val() = clip.movie. ?????;
    });

    clip.glue('btnpaste');
    });

    thnaks For your answers.

    Reply
  5. Great article. Have to admit, it is a bit too much for me – just going to a simple click to highlight and ask users to copy themselves…

    Reply
  6. Hi Rilwis, long time to talk. And thank you for a nice post.

    I have just one question that how can apply the copy button for all pre tags in case a post has more than 1 pre?

    Reply
  7. This flash item doesn’t work in the latest version of CHROME. I’ve tried your example with no luck…

    Reply
  8. Zero Clipboard demo doesn’t work in Chrome (latest build) and the Wiki gives access denied, LOL

    Reply
  9. This is a great post; it was very informative. I look forward in reading more of your work. Also, I made sure to bookmark your website so I can come back later. I enjoyed every moment of reading it.

    Reply
  10. Hi,

    I decided that for me, for non IE users the best option is just to make the text I want highlighted appear in a textarea and then select it. The user has to manually copy still but at least they don’t have to steer the mouse.

    I do not like the flash ideas because they are fragile and can break with a flash update.

    Example in action -

    http://www.eroticaplexus.net/Documentation/XMLAuthoring

    (page gives adult content warning but that particular page has no adult content)

    The js -

    http://www.eroticaplexus.net/js/common.js

    Reply

Leave a Reply