Copying text into the clipboard with javascript

grink on 2008-08-24T01:30:25

Example of copying text into the clipboard

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

For better or worse, 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/)

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