andyMatthews.net

Copying text to the system clipboard in Javascript AIR applications

As I'm researching adding features to Shrinkadoo, a jQuery / ColdFusion powered AIR application, I'm learning all sorts of new things about the most excellent AIR framework. One of those things is the ability read to / write from the system clipboard. The ability to copy items to the clipboard is so ubiquitous that it's hard NOT to include it in your app. So let's take a quick peek at how to accomplish this in JavaScript based AIR applications.

The first thing we need to do is to create a new reference to the clipboard. In AIR, there are two types of clipboard: the system clipboard, and the AIR clipboard. We'll only concern ourselves with the system clipboard for now.


// create a new clipboard object, a static value
var cb = air.Clipboard.generalClipboard;

Now that we have a new clipboard object, we need to import the available clipboard formats. There are currently 6 static values, but again we'll only be concerning ourselves with one of them...TEXT_FORMAT


// retrieve the value for text formatted clipboard values
var cbFormat = air.ClipboardFormats.TEXT_FORMAT;

Finally, we set our string to the clipboard


// set the string data into the clipboard
cb.setData(cbFormat,myString);

It's a pretty simple process


// the original string
var myString = 'AIR is great!';
// create a new clipboard object, a static value
var cb = air.Clipboard.generalClipboard;
// retrieve the value for text formatted clipboard values
var cbFormat = air.ClipboardFormats.TEXT_FORMAT;
// set the string data into the clipboard
cb.setData(cbFormat,myString);

Look for more one-off AIR tips as I work through adding features to Shrinkadoo. Also, make sure to check out copy and paste in Shrinkadoo, coming soon.