Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Sun May 07 2023

How to copy text to the clipboard in JavaScript

In this short guide we will share two approaches on how to copy a text to the clipboard in JavaScript. And also cover some of the browser support and permissions that it may need.

then() and catch()

The function returns a promise, and needs to be handled accordingly.

const copyText = () => { navigator.clipboard .writeText("My text") .then(() => { console.log("Copied!"); }) .catch((error) => { console.log(error); }); }; <button onClick={copyText}>Copy</button>;

Async/await

And as with all promises, we can use async/await as well to make the code slimmer

const copyText = async () => { try { await navigator.clipboard.writeText("My text"); } catch (err) { console.log(err); } }; <button onClick={copyText}>Copy</button>;

Permissions and browser support

All major browsers support navigator.clipboard, however, the permissions vary between them. Some of the browsers only supports it when it is through https and some needs permissions from the user. Read full browser availablility here.

Outro

In this guide we covered how to copy text to clipboard using the Web API Clipboard. I hope you enjoyed this post, and thanks for reading.

All the best,

signatureSun May 07 2023
See all our articles