Extending Prototype - Copy to Clipboard

After some researching, I’ve extended the Form.Element.Methods with a copyToClipboard method. An example of usage: $('myinput').copyToClipboard();.

A few quick notes about the clipboard and browsers.

Natively in IE5+, you can gain access to the clipboard via the window.clipboardData object. If you wanted to gain access to the clipboard in Firefox, you have to enable security preferences in your user preferences. I couldn’t find a native solution for Opera or Safari. As a result of Firefox, Opera and Safari not having direct access to the clipboard, Flash presents us with an opportunity to gain access.

Jeffothy provides us with swf (right-click, save link as) to use when copying to the clipboard.

The code below checks to see if the window.clipboardData object is available and will use that to copy the content to the clipboard (IE only). If the clipboardData object isn’t available (all other browsers), we will then create a div as a placeholder for the Flash object. The code uses SWFObject (if available) or will update the placeholder with an embed tag. The interesting part is with the flashvars attribute. This is how we pass the text to copy through the clipboard parameter.

There is an optional parameter (swf) which is used to specify the location of the _clipboard.swf object.

Object.extend(Form.Element.Methods,
{
  // Uses a combination of:
  // http://www.jeffothy.com/weblog/clipboard-copy/
  // http://www.rodsdot.com/ee/cross_browser_clipboard_copy_with_pop_over_message.asp
  copyToClipboard: function(element, swf)
  {
    if (Object.isUndefined(swf)) swf = ‘_clipboard.swf’;
    if (window.clipboardData)
      window.clipboardData.setData(”Text”, element.getValue());
    else
    {
      if(!$(’flash_clipboard_container’))
        $(document.body).insert(new Element(’div’, {id: ‘flash_clipboard_container’}));
 
      var content = encodeURIComponent(element.getValue());
 
      if (!(typeof SWFObject == “undefined”))
      {
        var so = new SWFObject(swf, ‘copy_contents’, ‘0′, ‘0′, ‘4);
        so.addVariable(’clipboard’, content);
        so.write(’flash_clipboard_container’);
      }
      else
      {
        $(’flash_clipboard_container’).update(
          new Element(’embed’,
            {width: 0,
            height: 0,
            flashvars: ‘clipboard=’ + content,
            quality: ‘high’,
            name: ‘copy_contents’,
            id: ‘copy_contents’,
            src: swf,
            type: ‘application/x-shockwave-flash’})
        );
      }
    }
  }
});
 
Element.addMethods();

- Joe

Leave a Reply