Javascript: Copy Text to Clipboard
Update: this method no longer works. For details: http://cthayer.wordpress.com/2009/02/26/javascript-copy-text-to-clipboard-not-anymore/
So, today we’re thinking that our users could benefit from some areas of our site auto-copying text to their clipboards so that they can just click and paste instead of copy, click, and paste.
IE has the handy window.clipboardData object which allows javascript direct access to the clipboard. However, Mozilla/Firefox disables this functionality by default because of security concerns. So, while the IE method works in Safari and Opera, it fails in Mozilla/Firefox and therefore we needed another way.
Turns out that while javascript is not allowed to access the clipboard, flash is. So, by using flash and a little ajax magic you can create a copyToClipboard function in javascript that works in all browsers that support flash and ajax.
This code is posted on the web in many places and in this case it came from here:
function copyToClipboard(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; }
1 comment so far
Leave a reply
[...] – Not anymore Posted February 26, 2009 Filed under: Uncategorized | In a previous post (Javascript: Copy Text to Clipboard), I described a method for using Javascript to copy text to a user’s [...]