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.

<img src=“/wp-content/uploads/2011/07/copy.gif" alt="javascript copy to clipboard" />

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.

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com

Leave a Reply

Your email address will not be published. Required fields are marked *

Copyright © 2024 Deluxe Blog Tips. All rights reserved.

My products: Meta Box | Slim SEO