Copying text into the clipboard with JavaScript in Firefox, Safari, IE, Opera, ...

Update: The method may not work with recent browser/Flash configurations. Flash Player 10 requires requires that the clipboard copy operation be initiated by a user click event inside the Flash movie. To work around this issue, use Zero Clipboard. You can also see my latest post on the topic

Firefox won't allow copying text into the clipboard via javascript for a variety of reasons.

You can get around this problem with a little .swf (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 above trick will also work in Safari, IE, and Opera.

Download clipboard.swf

Alternatively, you can use the Google App Engine hosted version at
http://appengine.bravo9.com/copy-into-clipboard/clipboard.swf

(Originally adapted from http://www.jeffothy.com/weblog/clipboard-copy/)


Blog comments powered by Disqus