Wednesday, May 30, 2012

JavaScript : Copy text to the clipboard, without Flash and securely (Updated!)

Github (Alexa: #348), Kickstarter (Alexa: #774), and many other major web-sites are increasingly using a flash-based button to facilitate one-click-copying of text, an otherwise disallowed action. Put aptly, by several stackoverflow-users, this method is 'overkill'. Basically a translucent flash applet is overlayed on a button-graphic to perform a clipboard-copying action, upon clicking the applet. Questionable security behavior is thus proxied to the flash applet, as the post-flash era draws near. Some browsers support document.execCommand('copy') ,which allows placing content, marked editable, into the Clipboard. However, the methodology dates back to the IE-5 era, which is more than a decade past, and execCommand is only loosely supported, yielding mixed results.
Jarek Milewski provides a better solution , which can be seen in action here.
By invoking a dialog-prompt as follows, window.prompt('Dialog text', refvariable); , a native-UI modal-input dialog is shown, with preselected text. The user is then offered the choice to click CTRL+C and hit ENTER.

Demo:

Click on the file-path below to copy and paste the selected text into the file-dialog below, thus allowing quick navigation to a specific file.

► Implementation #1 ( window -prompt):
c:\Windows\System32\restore\MachineGuid.txt

► Implementation #2 (preselected textbox):
c:\Windows\System32\restore\MachineGuid.txt

► Implementation #3 (direct textbox):


► Implementation #3 ( using an input -tag set to readonly; inspired by goo.gl ):




Conclusion:
Copying cannot be straightforward, as the Browser is obliged to uphold an encapsulated, sandboxed environment, with many security considerations at play. Prompting the user before performing a clipboard action, offers currently the best measure which is effective whilst less obtrusive than other methods. Given the increasing spreading of flash-based clipboard copying, the issue should not be neglected and alternative fully HTML5 / DOM compliant methods should be pursued.

0 comments:

Post a Comment