Tuesday, June 29, 2010

Copying text to Clipboard using JavaScript

While developing a while back I needed a way to use programming to copy text to a user's clipboard without using Flash (recent versions of Flash restrict this anyway). The solution was pretty easy and handled by JavaScript.

Problem: Needed to copy text to clipboard in Chrome without using Flash and when a user clicked a link. Chrome (and most likely other browsers) restrict this copying to prevent malicious activity. While this is helpful to user's it can also be unhelpful to programmers.

Solution: To accomplish this I started out testing what could be copied and found that only text inside a form input control could be copied using execCommand. This helped me to understand that my first objective was to create a form input and copy the text inside it. Once I was able to do this, I decided to create the input field with JavaScript, then set the value of it with JavaScript, then run my execCommand function. This worked. The last thing I needed to do was to hide the form input control so that the user didn't see it popup every time they copied something. Using CSS I was able to make the form input mostly unnoticeable. CSS is not required for the solution to work, but helped to make things less noticeable.

When all was said and done, my script works fine in Chrome. I will test it in other browsers and see how it performs.

Note: Making a form input hidden with CSS will prevent JavaScript from selecting it to add it to the clipboard. As you will notice in my solution, I always kept the input visible. My code is shown using jQuery but can be easily done without it.

$("<input />") // Create the element
      .attr('id','custom_input') // this may be unnecessarily -- the CSS below helps to hide the input
      .css({width:'1px', height:'1px', border:'none', backgroundColor:'#FFF', 'position':'absolute'})
      .prependTo($(t).parent()) // in my case this is document root -- this may

document.execCommand("copy", false, null);

If you have questions regarding implementing this code or non-jQuery versions, do let me know.

Best of luck.

No comments: