Before anything else, here is a sample demonstration of what I am discussing in this blog post. Enter some text in the textbox, and click the Flash’s Copy icon below. You should have the text on your system clipboard. The .swf file for the same is attached with the post. Feel free to use it anywhere you like.
This is one of those topics, that has been blogged and written about furiously on the web. So, when I myself needed this functionality, I expected to find something useful on the web easily. And I thought I immediately hit the jackpot when a quick Google search threw up tons of pages for exactly what I was looking. However, it was not to be so, as I found out later.
Almost every solution that the Google search revealed worked, but the problem was only on Internet Explorer, not on other browsers and certainly not on Firefox. Some more research into the issue led me to pages like this, this and this, which clearly mention that FF considers it a security issue for Clipboard to be accessible to a web page. The crux of the matter was that you either need to explicitly enable Clipboard access to web pages in Firefox, or install add-ons that enable Clipboard access to web pages. As can be seen, none of these was a viable approach, as you do not expect the audience at large to configure settings or install add-ons on a page’s request.
I was almost desperate that someone should have found a cross-browser solution of implementing this, as the problem is way too common. The tons of links I searched and followed took me no-where, everyone worked on IE but not on FF out-of-the-box.
I was wondering whether it is at all feasible to accomplish this, when something different struck my mind. Remember, Syntax Highlighter, the good old and wonderful syntax highlighting plugin from from Alex Gorbatchev (that it used on this site also for making the code stand-out and readable). The plugin put a toolbar on every piece of code, that had along with others a Copy button to copy the code. And as far as I knew, it worked on every browser, I had tested it on. Finally, I felt a way out here.
I immediately began debugging my own site’s markup through Firebug to see how Syntax Highlighter handled Clipboard copying. And I was immediately stumped to see that it uses Flash for this purpose. Some more research revealed that it uses the Flash’s System.setClipboard method for access to Clipboard.
Having figured out this, it should have been easy from here on. But again, it was not so. I immediately created a Flash movie, and enabled it to interact with javascript through Flash’s ExternalInterface. What I thought of achieving was to embed a 1×1 pixel Flash movie into a page, and call a Flash javascript exported method from javascript to access Clipboard.
It did not take much time to assemble code, but the code did not work. I tried everything, from tweaking markup to browser settings to ActionScript code, but it simply did not work. Then I came across this post on adobe.com, which clearly spelt out that explicit user interaction is required in Flash 10 for successful access to clipboard (I tried bypassing this by manually raising Click Event on a button, and accessing Clipboard in the handler, needless to say, it failed).
So, in the end, it boiled down to this. The Flash movie itself required to have a UI against which User action would allow me to access clipboard. It was better than having nothing at all.
Now coming on to the coding part, you simple need to embed the Flash movie normally into a web page. Here’s how I do it on this page:
<object id='clipboard' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0' width='16' height='16' align='middle'> <param name='allowScriptAccess' value='always' /> <param name='allowFullScreen' value='false' /> <param name='movie' value='clipboard.swf' /> <param name='quality' value='high' /> <param name='bgcolor' value='#ffffff' /> <param name='wmode' value='transparent' /> <param name='flashvars' value='callback=f1' /> <embed src='clipboard.swf' flashvars='callback=f1' quality='high' bgcolor='#ffffff' width='16' height='16' wmode='transparent' name='clipboard' align='middle' allowscriptaccess='always' allowfullscreen='false' type='application/x-shockwave-flash' pluginspage='http://www.adobe.com/go/getflashplayer' /> </object>
There are 2 important things above. One, the Flash has been granted script access vis allowScriptAccess=”true”. Second, the content for copying normally would come from your page, and the movie is not aware of the content to place in clipboard. Therefore, you specify a callback method in the flashvars for the movie. This should be a fully-qualified reference to a method name in your javascript that should return a string which would be copied onto the clipboard. Here’s the javascript method used on this page:
{syntaxhighlighter brush: jscript;fontsize: 100; first-line: 1; }function f1() {
var s = document.getElementById(‘text1’).value;
var div = document.createElement(‘div’);
div.innerText = ‘”‘ + s + ‘” copied to clipboard.’;
document.body.appendChild(div);
if (window.clipboardData)
window.clipboardData.setData(‘text’, s);
else
return (s);
}
{/syntaxhighlighter}
What you should particularly note above is that IE provides out-of-the box window.clipboardData.setData method for putting data on the clipboard, which has been used. The Flash approach is used for all other browsers which do not support this. The user interaction still has to be through the Flash movie by clicking against it for everything to be able to work in a cross-browser fashion.
Use the comment form below to discuss any issue you face using this approach. I have tested it on IE, FF & Chrome, and it works!!
The html file attached below together with the clipboard Flash movie was used to create the example on the page above.
UPDATE:
- Oct 24, 2010 – I later needed to pass custom parameters to the callback function also. So, enhanced the clipboard flash movie to support another flashvar called: callbackArg. You can use this to pass a string to the flash movie which the movie forwards to the javascript callback method when you click on the movie. Here’s a sample code html for the same:
<object id='clipboard' codebase='http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0' width='16' height='16' align='middle'> <param name='allowScriptAccess' value='always' /> <param name='allowFullScreen' value='false' /> <param name='movie' value='../resources/flash/clipboard.swf' /> <param name='quality' value='high' /> <param name='bgcolor' value='#ffffff' /> <param name='flashvars' value='callback=f1&callbackArg=MyCallbackArg' /> <embed src='../resources/flash/clipboard.swf' flashvars='callback=f1&callbackArg=MyCallbackArgument' quality='high' bgcolor='#ffffff' width='16' height='16' name='clipboard' align='middle' allowscriptaccess='always' allowfullscreen='false' type='application/x-shockwave-flash' pluginspage='http://www.adobe.com/go/getflashplayer' /> </object>
If you need to have multiple parameters for the callback method, or non-string argument, you can easily serialize those parameters as json, url encode them, and then set them as the callbackArg for the movie. then in your callback method, you would first url decode them and then deserialize them from json.
For Json serialization, you can pick code from here or here, and for url encoding/decoding, you can use the browser’s native encodeURIComponent and decodeURIComponent methods.
thank’s for sharing
i wonder, if i want to use it without click the copy button,
but directly attach listener on html tag
like <a href=’some text to copy’ >clipboard</a>
how can i deal with it ?
Is there a cross-browser approach to CLEAR the clipboard with javascript (without user interaction) ?
Greetings,
Martin
The Netherlands
Thanks for the tutorial. Quite detailed and easy to follow.
I am, however, running into problems when I try to pass the id of a textarea field as a parameter for the callback function. In IE, everything works as expected, but in Firefox the value doesn’t get copied to the clipboard.
This is how I pass the parameter (which is also specified in the embed tag):
<param name=’flashvars’ value=”callback=f1(‘MyTextareaId’)” />
Again, the return value from the f1 function is correct (I checked using an alert box), but it’s just not copying to the clipboard. Any idea what I might be doing wrong?
Thanks in advance,
Tony
Hi,
I’ve been postponing this for a while, but I can’t seem to do it no longer. So when i found your examples working I was really happy. However, when I started implementing it in my environment I can’t seem to get it to work.
I need to copy ExtJS grid data as in you other blog, but went back to your original examples after having some problems. Also in this case I can not get it to work in my environment even tough ot works fine from you’re site.
I’ve done the following:
Saved the htm and the swf to my local disk. Opened the htm file in the same browser that succesfully ran you’re demo (FF 3.5.9). The page is shown fine, but when clicking the copy icon nothing new is inserted to the clipboard.
If inserting an alert in the f1 script, nothing is displayed when clicking the copy icon. Any ideas as to what I’m missing here?
BR
Roger
Can I get the source file for “clipboard.swf”.
Thanks
Anandhi
Hello rahul
Thank you for usefull post,
I used your code and it’s worked succesfully but i have to use it without icon of copy that you use it, i mean i want to connect the function to work on link button in my page so could you please tell me how register the function on link even i try the following
<asp:LinkButton ID=”lnkCopy” Text=”Copy To Clip Board” OnClientClick=”f1(); return false;” runat=”server”></asp:LinkButton>
It’s work on IE but not working on firefox (working on firefox just on your icon)
Hi Rahul,
First of all, thanks a lot for your tutorial ! As you said, the issue of “javascript copy to clipboard” is often tackled but at the end of the day, there are very few good posts about this…!
I’m not used to flash at all so my question may seem stupid. I just want to know how I can easily convert a gif or png icon into a swf movie “icon” (like the 2 sheets of paper you used).
Thanks again for the tutorial ^^
Hello, and thank you for this. It is exactly what I was looking for and it works great for what I need it to do.
The only problem, is that I need to create a different button and I have very little experience with creating Flash or writing javascript. I do own Flash CS4 and was able to create a button that works for me and have exported it as clipboard.swf. But it doesn’t show up on my webpage and the tiny clickable area does not trigger the function.
From my reading of your post, what is needed is to “enabled it to interact with javascript through Flash’s ExternalInterface.”
I have been looking for a tutorial on how to do this and I have found several but they all assume the reader knows more about Flash than I do.
Can you either point me to a resource for learning how to do this or could you give those of us who are ignorant the steps needed to impliment this for ourselves?
Any help you offer will be greatly appreciated!
I have made a button that works. I was able to do it by importing into Flash CS4 the clipboard.fla file you uploaded here for another commenter. Using that as the basis, I swapped out your graphic for mine. Exported as a .swf. And changed the size dimentions in your html to my file size. And Wah Lah! It works and LOOKS great
Thanks again for doing this for us.
Is it possible to get the clipboard data in FF.
Hi Rahul,
I tried creating a flash button in Adobe Flash CS3, but somehow its not calling the function f1.
When I try to open the swf file that you had posted, its not opening in Flash CS3.
Can you please specify if there are any special publish setting for this.
If there are any special requirements please let me know.
Thanks,
Arf`a
Ok,
Everything is working great, but.
How do I put it together so that there is predefined text in the form. The Init Val.
I do not want to enter the text to be copied, I want the text already there and then I just hit copy and it copys the text. Know what I mean. I do not want to have to enter the text to be highlighted and copied. I want it already in the form.
Can you please attach the .swf and .html that I would need to accomplish this.
Pleeeeese.
~Ben
Vancouver, BC, Canada.
Hello,
Thank You for this post, it’s amazing.
I just have a small problem, to get it working localy… I’m beginner with programing, so i started simply: I downloaded atachments from this post (htm and swf), put them into one folder on my Win7 desktop and open htm file in my browser.
In IE7 it is working (so I dodn’t copied it wrong).
In Maxthon3 (WebKit) it is not working… I see the button, but after clicking nothing happend.
When i open your attachment directly (without saving it localy) it’s working in WebKit just fine…
Any idea how to solve it?
many many thanks for sharing this knowledge – it is exactly what i have been trying to do – unsuccessfully – with JS
thank you !!!
Hi Rahul!
thanks for sharing your geniality!
(I was searching for this 1 month… seems like Google is out of date :] )
Now i have a fresh question (I have read all the comments.) cause i’m not so good with JS. 🙁
I have lots of <imput> fields with predef. value, and for each a ‘copy to clipboard’ icon.
NOw, how to rearrange your great script so that I don’t have to always copy the huge flash code, and also
how to create an undefined
var s = document.getElementById(”).value; or something like this that will make the icon-ID call the relevant imput-ID to be copyed-
so that I’ll don’t have to populate the Jscript with all the ID names (cause I have it a lot).
(I hope you understood the mess above.. 😉
Thanks in advance Rahul (and anyone with answers)!
Greetz from Croatia!
Hi Rahul, I have downloaded the samples and integrated your solution in my environment…
I have changed the function names and so on and everything seemed to be working… (Icon is showing and whenever I click the Icon it runs the script) However when the copy script runs in Firefox (I am debugging with FireBug) the window.Clipboard is undefined… An I missing something?
Thanks,
John
This is awesome stuff. I have multiple text fields i need to copy from and i couldn’t figure out a way to do it correctly. Only copies the most recent, any ideas?
Thanks in advance !
ROR
Thanks for the quick re! I took your advice and (kinda) and fixed it. However, my way is ugly, and prob noobish.
I made a function for each text field call. You can see the fruits of our labors here
Hi Rahul,
I have two different tabs in Ext JS. I am attaching the copy functionality to both tabs in the form of a copy button. However when I try to use the functionality from 2 tabs and pass it the call back argument it always passes the same one although I am passing different arguments which are my data grid names. When I use one tab and remove the functionality from the second one everything works fine.
Do you have any idea why this happens?
Thanks,
John
Hey Rahul,
Great script and working well, but noticed there a javascript error in IE when leaving the webpage whenever this copytoclipboard is called. It always says “Object Required” and is contained in this function:
function __flash__removeCallback(instance, name) {
instance[name] = null;
Any clue on how to handle this?
Hi. This is great info. thanks.
I have a requirement to copy an entire page to the clipboard.
My application will allow the user to choose a portion of a page of data
Things are displayed in a monthly calendar, and they can choose to copy one day, one week, or the entire month. Once they have selected, I will construct another page with only the desired data, and then they must be a ble to copy that entire page to the clipboard.
I can use the browser “select all”, “copy” capability, or I can use your suggested approach.
But with your approach, how would I pass it the entire page to the swf ?
Thanks
Hi Rahul,
I must say, you are king among man’s.
this what exactly i required and the solution was at my finger tips
thx
Thanks for the excellent write up. This is exactly what I needed.
Hello Rahul, thank you very much for this detailed guide,
I have a question though..
I’m working on a script, where i get values from a database and want to display your copy button next to each result i get from the database.
How can I pass a value from what textbox is the text going to get copied to the javascript function ‘h1’ ?
Michael Schinis
Hi rahul,
Thanks for the excellent writeup. Im facing some problem when trying to replace the Fam Silk icon for a custom one. The extra parameters callbackArg do not get passed. I tried compiling it in CS3 and CS4. I do see above that someone has done the same. COuld you please help me regarding this?
There seems to be a problem with chrome.
I get this error, “The callback parameter is not defined”
Thats a bit wierd if you take into account that it works in firefox..Any ideas?
Does anyone know how to do this as cross browser paste from clipboard?
Hi, I think this should be petty easy. User can press Ctrl+V to paste it in the desired textbox on the web page. Other than that, you can provide a paste button on the page. Then you would continuously monitor the currently active textbox/textarea on page (a global focus listener to set the last active textfield) and append/insert text into the last active textfield when your custom paste button is clicked.
Good job, clear write up, thanks!
I red others trying to use this with multiple sources that need to be coppied.
I think it could be done without mutliple copies of the flash object and using a onmouseover function on the source elements.
This mouse over function would transfer the data to the <input> that is being used by the flash callback. And position the flash object right under the mouse. This way the user would be able to click the flash object and the data will be prefilled from the onmouseover event.
However, I’m not well versed (yet) in how to position the flash object under the mouse during the onmouseover event.
I wanted to thank you for providing the easy to follow explanation of your solution to a problem that has been frustrating me. My dilemma is a little bit different because I would like to copy an image to the clipboard so that it can be pasted somewhere else.
I almost gave up and just provided instructions to “right click” on the image and select copy but once I found you solution now I’m trying again. I was able to make the swf and code you provided work on my site now it is just a matter of making it copy an image instead of text.
Thank you again for what you have provided.
Jeff
AKA – Mr. Sharp
Any reason you couldn’t add a listener for speciak keys and copy on CTRL + C?
Respect! Professional & Elegant. Thank for the .fla
Hi i’m using cakephp framework. I couldn’t embed the above flash script with my site. Please help me how to embed this script in cakephp.
Hi,
I’m having problem on the new line.
Eg. I have a textarea which have data
line 1
line 2
when i copy it and paste to note pade it become
line 1line 2
pls help
Hi,
I have tried this excellent solution and it still works perfectly for copy when you have the data available.
The problem I have is that I need to ask my server for the data to be copied (it’s not a very standard type of application). If I could get the data through a synchronous call it would work fine but that isn’t exactly to JS way of doing things…
I assume the security model won’t allow me to call the flash later on (would demand a change of the fla code ofc) and delaying the return of the callback would result in other nasty problems in the browser so I’m a bit stuck here :-(.
Any ideas on how to solve this?
Hello,
Please help me to know how to take flow of these content.
1) .aspx page
2) clipboard.swf file
Is there any need to install Flash S/W on my PC ?
Many Thanks !!!
Regards,
Yuvraj
Hi Rahul,
Just wanted to applaud your generosity of information and say thanks to you or the ideas on this post. You’ve been so kind and patient in systematically responding to all of these viewers for their assorted questions, well beyond what most folks do. I look forward to trying some of your tips out and just wanted to say how impressed I’ve personally been with this blog. May God richly bless you and yours 🙂
Rick
Hi Rahul,
i want pass parameter in f1 function then tell me how do it.