This content originally appeared on Go Make Things and was authored by Go Make Things
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!
Need front-end help but don't need a full-time employee? I now offer subscription front-end engineering. Ship faster and build better systems. Pause or cancel any time.
Cheers,
Chris
This content originally appeared on Go Make Things and was authored by Go Make Things

Go Make Things | Sciencx (2025-05-27T14:30:00+00:00) How to copy stuff to a user’s clipboard with vanilla JavaScript. Retrieved from https://www.scien.cx/2025/05/27/how-to-copy-stuff-to-a-users-clipboard-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.