Copy & Paste on your web app? Well there is an API for that…

Photo by Museums Victoria on Unsplash

Often in OutSystems applications we need to handle copy or paste events programmatically.

Having a copy button on a page that copies exactly what you want without having the user select it first or pasting an image into the app without having the user to upload a file.

The Clipboard Web API was created for this exact purpose.

The Clipboard API provides the ability to respond to clipboard commands (cut, copy, and paste) as well as to asynchronously read from and write to the system clipboard. Access to the contents of the clipboard is gated behind the Permissions API: The clipboard-write permission is granted automatically to pages when they are in the active tab. The clipboard-read permission must be requested, which you can do by trying to read data from the clipboard.

This API is designed to supersede accessing the clipboard using document.execCommand().

So let’s implement this in OutSystems…

This simple method just call the writeText() API and it writes a text to the clipboard

This one is also straightforward, just call the readText() API and grab the promise resolution. Don’t forget to handle the permissions gracefully.

This one is a bit more complex because the read() method outputs a JS Blob. So I’m going to get a blobToBase64 JS method from stack overflow. This will also break if the blog has multiple mime types. For now we’ll implement the simplest use case.

This one has two interesting aspects.

First I had to find a method to convert from base64 to JS Blob. This is necessary because in OutSystems the JS node automatically converts a binary input into a base64 and the JS Blob requires an actual binary.

The second one is that all the examples I’ve found to construct the clipboardItem object were in ES6 which OutSystems does not support.

So this:

new ClipboardItem({
[blob.type]: blob

Translates to:

var obj = {};
obj[blob.type] = blob;
var clipboardItem = new ClipboardItem(obj);

If you ever find yourself stuck between ES6 and OutSystems you might want to check out BabelJS or ES6Console.

The Clipboard API can be found on the forge. Go check it out and keep building those apps.

Developer Advocate @