Copy array data to the system clipboard with vanilla javascript

A simple technique for outputting array data as a list and then copying the list to the system clipboard.

Last updated on 1 June, 2021, 11:30am by keston

Preface

I'm currently working on a feature for a webapp that allows a user to copy a list to their clipboard. I initially thought this could be done using the clipboard API directly in JS, however I quickly found out that approach requires you to ask the user for permission, which wasn't the desired user experience. 

 

The simple and most browser compatible alternative way to achieve the task, without asking the user for permissions was to create a dom element (textarea) and use document.execCommand, hence the following technique.

 

 

Quick CodePen
                        

See the Pen dyvVKJY by Keston Neunie (@neunie) on CodePen.

How It Works

In this example, a textarea is included in the dom and hidden with CSS. With Javascript we loop through the array and format a string with line breaks. Next, we set the value of the textarea to our string value. Then, we use document.execCommand to select and then copy the contents on the textarea to the clipboard.

 

Note: You might want to dynamically add the textarea to make this solution easier to reuse.

Use Cases

As mentioned earlier, I am using this technique in a webapp to convert some application data into a string that can be pasted into another program.

 

Another potential use could be to build a custom share button.

 

Hope this helps,

Keston