How can I copy text to clipboard with JavaScript?
JavaScript, Browser · Jan 11, 2022

Asynchronous Clipboard API
A very common need when building websites is the ability to copy text to clipboard with a single button click. If you only need to support modern browsers, it's highly recommended to use the asynchronous Clipboard API. It's supported in all modern browsers and provides an easy and secure way to update the clipboard's contents.
All you have to do is ensure Navigator
, Navigator.clipboard
and Navigator.clipboard.writeText
are truthy and then call Clipboard.writeText()
to copy the value to clipboard. In case anything goes wrong, you can use Promise.reject()
to return a promise that rejects immediately and keep the return type consistent.
const copyToClipboard = str => {
if (navigator && navigator.clipboard && navigator.clipboard.writeText)
return navigator.clipboard.writeText(str);
return Promise.reject('The Clipboard API is not available.');
};
This is pretty much how the copyToClipboardAsync snippet is implemented and should work across all modern browsers.
Document.execCommand('copy')
While support for the Clipboard API is pretty high across the board, you might need a fallback if you have to support older browsers. If that's the case, you can use Document.execCommand('copy')
to do so. Here's a quick step-by-step guide:
- Create a
<textarea>
element to be appended to the document. Set its value to the string you want to copy to the clipboard. - Append the
<textarea>
element to the current HTML document and use CSS to hide it to prevent flashing. - Use
HTMLInputElement.select()
to select the contents of the<textarea>
element. - Use
Document.execCommand('copy')
to copy the contents of the<textarea>
to the clipboard. - Remove the
<textarea>
element from the document.
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
el.select();
document.execCommand('copy');
document.body.removeChild(el);
};
Bear in mind that this method will not work everywhere, but only as a result of a user action (e.g. inside a click
event listener), due to the way Document.execCommand()
works.
There are a couple of other considerations, such as restoring the user's previous selection on the document, which can be easily handled with modern JavaScript. You can find the final code with these improvements implemented in the copyToClipboard snippet.
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.