October 12, 2008

Copy to Clipboard


                                Copying text to clipboard with JavaScript
                       

                       

                       
               
               
               
               

                       
                        Here is a simple way to place small bits of text upon the user’s clipboard.



Normally restricted by browser security, the clipboard is freely open to flash.

this function uses a simple flash app to dump to the clipboard.

It avoids any kind of user warning or confirmation regarding the clipboard that characterize JavaScript-only solutions.





Thus, it requires flash to be installed.




       
Code:

       
function copy(str) {
  var D=document;
    if(!copy.div) { copy.div = D.createElement('div'); D.body.appendChild(copy.div);  }

flashVar = "Q1dTB3kAAAB4nKtgYI1nYOBfwMDAw8jgzPT//3975lAGBoYOdQYWhu\
SczIKk/MSiFIac1Lz0kgyG4MriktRchuLUEme41DQmBg4GGRDJ6Cc0l4l  BAibCzsDO\
CDSJgwksyRwkzuAA5AIAd7oY/w==";

copy.div.innerHTML =  '<embed src="'+flashVar+'" FlashVars="clipboard='+encodeURIComponent(str) +
    '" width="0" height="0" type="application/x-shockwave-flash"></embed>';
}



Example:


       
Code:

       
  copy("Hello World!");

  -Run above then press <CRTL>+<V> in a text area.

  -It should say Hello World!



It is limited in the amount of data it can copy, about 2-4kb.

It also cannot read the clipboard at all, so don’t bother to try.



Despite it’s shortcomings, i still find it very useful, and hope you might as well.