How to copy text to the clipboard
Short answer
navigator.clipboard.writeText() copies a string and returns a promise:
await navigator.clipboard.writeText('Hello from the clipboard');A copy button
Copy the text of an element on click and show a short confirmation:
<code id="promo">SUMMER25</code>
<button id="copy">Copy</button>
<script>
const button = document.getElementById('copy');
button.addEventListener('click', async () => {
const text = document.getElementById('promo').textContent;
try {
await navigator.clipboard.writeText(text);
button.textContent = 'Copied!';
} catch {
button.textContent = 'Copy failed';
}
setTimeout(() => (button.textContent = 'Copy'), 1500);
});
</script>Reading from the clipboard
readText() reads the clipboard. The browser asks the user for permission first:
const text = await navigator.clipboard.readText();
input.value = text;Common mistake
The clipboard works only on secure pages (https or localhost) and only after a user action such as a click. A call right when the page loads is rejected, so always handle the error.
navigator.clipboard.writeText('text').catch((error) => {
showMessage('Press Ctrl+C to copy');
});Functions used in this recipe
- await — Waits for a promise and returns its value.
- try...catch — Catches errors so the program does not stop.