How to copy stuff to a user's clipboard with vanilla JavaScript
Today, we’re going to look at how to copy stuff to a user’s clipboard with vanilla JavaScript… which you probably already knew because that’s the title of the article.
Let’s dig in!
The basics
This technique uses the navigator.clipboard API, which works basically everywhere except Node.js.
Let’s create a copyToClipboard() function.
This navigator.clipboard methods are asynchronous, so we’ll use the async operator with this one. That will let us use await inside our function.
We’ll also accept the text to copy to the clipboard as an argument.
/**
* Copy text to the user's clipboard
* @param {String} text The text to copy
*/
async function copyToClipboard (text) {
// ...
}
Inside our function, we’ll use the navigator.clipboard.writeText() to actually save the text to the user’s clipboard.
This is an asynchronous function, so we’ll await it before continuing.
/**
* Copy text to the user's clipboard
* @param {String} text The text to copy
*/
async function copyToClipboard (text) {
// Copy the text
await navigator.clipboard.writeText(text);
}
Of course, something could go wrong, so we’ll also want to try...catch() our code and log the error.
/**
* Copy text to the user's clipboard
* @param {String} text The text to copy
*/
async function copyToClipboard (text) {
try {
// Copy the text
await navigator.clipboard.writeText(text);
} catch (error) {
console.warn('Unable to copy.', error);
}
}
You would run it like this…
copyToClipboard('๐ Hey there, friend!');
And generally, it has to be done in response to a user interaction like clicking something.
Making this a Web Component
The challenge with our current code is that it doesn’t really notify the user that anything has happened.
In an ideal world, you’ll want to display a status notification of some kind that tells the user the text has been copied. You also probably want to have some sort of button that the user can interact with and makes it clear what will happen when they do.
Tomorrow, we’ll look at how to do exactly that with an HTML Web Component!