Zeno Rocha has released Clipboard.js, a JavaScript library solely devoted to copying text from a webpage to the local computer's clipboard.
On every GitHub repository page, there's a widget in the sidebar that displays the repo's HTTPS clone URL. There's a button next to it that, when clicked, copies the repo's URL into the user's clipboard. GitHub uses a library called ZeroClipboard. The problem is that this is done using an invisible Flash movie and Flash is getting the cold shoulder from browser vendors.
Earlier this year, Firefox blocked Flash by default, requiring users to explicitly approve the use of Flash to copy something to the clipboard.
An article appeared on the Mozilla Hacks that demonstrated the use of the document.execCommand()
API. According to MDN, execCommand
"allows one to run commands to manipulate the contents of the editable region." Until version 41 of Firefox, the "cut" and "copy" commands were disabled.
Rather than let any JavaScript code copy text to the user's clipboard at will, browsers restrict such events to user initiated actions. If the code attempts to copy text without the user's explicit action, the call fails.
Rocha took the idea of using execCommand a step further and integrated the Selection API as well. By combining these technologies, Clipboard.js offers a multi-purpose, lightweight JavaScript library, with a useful API for developers. To connect a button to the library, developers declare what elements should fire the clipboard:
var clipboard = new Clipboard('.btn');
While the library is supported on a majority of browsers, Safari does not yet support the cut and copy commands.
Developers of ZeroClipboard have discussed switching to this method for their library, falling back to Flash where the API isn't supported. James Green, contributor to ZeroClipboard said of Clipboard.js, "It's a good light option but I know there will definitely still be a need to make ZeroClipboard support HTML5 but fallback to Flash for many consumers out there."
The HTML5 Clipboard API is still a work in progress and enjoys only partial support on most browsers.