Javascript Copy Text To Clipboard

Issues arise when you want to copy text to the clipboard using javascript. Firefox provides a security measure which prevents you from doing it so a workaround has to be made for it to happen. I am using IE7 for my IE testing and in this version, it also has a security feature although less strict than Firefox. Whenever you browse to a new page that has a copy to clipboard function, a popup window prompts you asking if you want to allow the webpage to access your clipboard. Normally, you would choose no. But instances may require you to like if the site you are accessing is yours or related to your needs and you have the utmost trust that the script won’t harm your PC or something. Anyway, to provide copy to clipboard functionality using Javascript, I found this function in this site does the job by using a little .SWF file. You can download the file there or if you want to use Google App Engine, the code function below will do. It also works in Safari, IE, and Opera.

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;
}
No TweetBacks yet. (Be the first to Tweet this post)

Like what you see? Buy me a cup of coffee. Or subscribe to my feeds.


(No Ratings Yet)
 Loading ...

12 Responses to “Javascript Copy Text To Clipboard”

Pages: « 1 [2] 3 » Show All

  1. 6
    Javascript: Copy Text to Clipboard « My Weblog Says:

    [...] This code is posted on the web in many places and in this case it came from here: [...]

  2. 7
    Daniel Says:

    Thank’s for this code.
    I think this code doesn’t work on vista. DO you have a workaround?

    kind regards, Daniel

  3. 8
    tech Says:

    hi daniel, it’s not the os that’s the problem, it’s the browser. which browser are you using and what version? i tried this with ie7 and it was ok. i usually use firefox.

  4. 9
    Brian Says:

    I’ve found recently that this little trick stopped working in Firefox. I am not sure yet if they have closed this “hole” in the recent releases or what the problem is. IE7 still works (w/ a one-time warning), but FF doesn’t.

  5. 10
    Benjamin A. Wendelboe Says:

    Doesn’t work for me.. I’m on Safari 3.1.2/Flash 9.. Too bad.. I’m desperately looking for a solution to this..

Pages: « 1 [2] 3 » Show All

Leave a Reply