Copy text to the clipboard in JavaScript
Intermediate · 4 min read
"Copy" buttons save people from selecting text by hand: next to a booking code, a coupon, a share link or a code sample. The browser's Clipboard API does the copying in one line. The line can fail, though, and a copy leaves nothing on screen, so a button that fails silently looks exactly like one that worked.
In this tutorial you will copy the text from an input to the clipboard when a button is pressed, tell the user whether it worked, and give them another way when it didn't. You should have used addEventListener and try/catch, and seen async and await.
navigator.clipboard.writeText
navigator.clipboard.writeText(text) puts text on the clipboard. It returns a promise, an object that later resolves (the copy worked) or rejects (it didn't). With await inside an async function, a rejection becomes an error you can catch.
When copying is refused
The browser refuses the copy if:
- the page isn't secure (it must be
httpsorlocalhost), - it isn't happening during a real user action, such as a click. A copy started from a timer is refused.
- the page has been blocked from using the clipboard, as can happen inside some embedded frames.
When it refuses, the error's name is usually 'NotAllowedError'.
Here is the page:
<input id="box" value="LAG-441-XA">
<button id="copy" type="button">Copy</button>
<span id="status" role="status"></span>
role="status" asks screen readers to announce the span's text when it changes, without moving focus away from the button.
For this lesson, navigator.clipboard is a small stand-in that records what was copied.
Here is the exercise. Try it yourself first, or read on and we will build it together.
20 Copy a text box to the clipboard
fairCopy an input's contents to the clipboard when a button is pressed, and tell the user whether it worked.
Stuck? Three hints, smallest first
- 1.
navigator.clipboard.writeText(text)returns a promise, so it can fail. - 2. It only works from a user gesture and a secure context. Calling it on a timer is rejected.
- 3. Always confirm visibly. A silent copy is indistinguishable from a broken button.
Step 1: copy and confirm
const box = document.getElementById('box');
const status = document.getElementById('status');
await navigator.clipboard.writeText(box.value);
status.textContent = 'Copied.';
console.log(status.textContent); // Copied.
console.log(await navigator.clipboard.readText()); // LAG-441-XA
readText() reads the clipboard back, which proves the copy happened. (In a real browser, reading the clipboard may ask the user for permission first, so it's mostly useful for checking your work.) Showing "Copied." matters as much as the copy itself: it's the only sign the user gets.
Step 2: catch a refusal
Here's a pretend clipboard that always refuses, so we can see the failure path:
const status = document.getElementById('status');
const refused = {
writeText: async () => { throw new DOMException('Write permission denied.', 'NotAllowedError'); },
};
try {
await refused.writeText('LAG-441-XA');
status.textContent = 'Copied.';
} catch (error) {
status.textContent = `Could not copy (${error.name}). Select it and press Ctrl+C.`;
}
console.log(status.textContent); // Could not copy (NotAllowedError). Select it and press Ctrl+C.
DOMException is the kind of error browser APIs throw, with a message and a name. When the copy fails, the message says what happened and what to do instead. "Select it and press Ctrl+C" is more use than "Copy failed".
Step 3: put it in a function
Pass the clipboard in as an argument. The page passes the real one, and a test can pass the refusing one, so both paths can be checked.
const box = document.getElementById('box');
const status = document.getElementById('status');
function wireCopy(clipboard) {
return async () => {
const text = box.value;
if (text.trim() === '') { status.textContent = 'Nothing to copy.'; return 'empty'; }
try {
await clipboard.writeText(text);
status.textContent = 'Copied.';
return 'copied';
} catch (error) {
status.textContent = `Could not copy (${error.name}). Select it and press Ctrl+C.`;
return 'failed';
}
};
}
const copyAllowed = wireCopy(navigator.clipboard);
console.log(await copyAllowed()); // copied
box.value = ' ';
console.log(await copyAllowed(), status.textContent); // empty Nothing to copy.
wireCopy returns a new function that does the copying. It also refuses to copy an empty box, or a box of only spaces, and says so. It returns a short word describing what happened, which makes it easy to check.
Step 4: connect the button
const copy = document.getElementById('copy');
box.value = 'LAG-441-XA';
copy.addEventListener('click', wireCopy(navigator.clipboard));
copy.dispatchEvent(new Event('click'));
await new Promise((resolve) => setTimeout(resolve, 0));
console.log(status.textContent); // Copied.
The click handler is the function wireCopy returned. It's async, so the status updates a moment after the click. The setTimeout line just waits for that before we look.
Inside the handler, the copy is the first slow thing that happens. If you await other work first, such as a fetch, the browser may decide the click is over by the time you ask to copy, and refuse. Copy first, then do anything else.
The full solution
The full solution uses two stand-in clipboards, one that allows the copy and one that refuses, and passes each to wireCopy. Its checks confirm a copy reports success, reaches the clipboard and tells the user, a refusal doesn't throw, names the error and offers Ctrl+C, empty and space-only boxes copy nothing, a changed value copies the new text, writeText returns a promise, and the status is announced. Press Run. The live demo uses the real clipboard, so you may see either message, depending on what the frame is allowed to do.
allow-scripts only, so it cannot reach this page.const box = el('input', { id: 'box', value: 'LAG-441-XA' });
const status = el('span', { id: 'status', role: 'status' });
const copy = el('button', { id: 'copy', type: 'button' }, 'Copy');
document.body.appendChild(el('p', {}, [box, copy, status]));
// Passed in, so both the allowed and the refused case can be exercised.
function wireCopy(clipboard) {
return async () => {
const text = box.value;
if (text.trim() === '') { status.textContent = 'Nothing to copy.'; return 'empty'; }
try {
await clipboard.writeText(text);
status.textContent = 'Copied.'; // always confirm
return 'copied';
} catch (error) {
// Refused, insecure context, or no user gesture. Give a way forward.
status.textContent = `Could not copy (${error.name}). Select it and press Ctrl+C.`;
return 'failed';
}
};
}
const allowed = makeClipboard();
const refused = makeClipboard({ kind: 'denied' });
const copyAllowed = wireCopy(allowed);
const copyRefused = wireCopy(refused);
console.log('before:', JSON.stringify(status.textContent));
console.log('result:', await copyAllowed());
console.log('status:', status.textContent, '| clipboard now holds:', allowed.written);
console.log('refused:', await copyRefused());
console.log('status :', status.textContent);
box.value = ' ';
console.log('empty :', await copyAllowed(), '|', status.textContent);
box.value = 'LAG-441-XA';
Output
15 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 15 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('a successful copy reports success', await copyAllowed(), 'copied');
test('and the text reached the clipboard', allowed.written.at(-1), 'LAG-441-XA');
test('and the user is told', status.textContent, 'Copied.');
test('reading it back gives the same text', await allowed.readText(), 'LAG-441-XA');
test('a refusal does not throw at the caller', await copyRefused(), 'failed');
test('the message names the error', status.textContent.includes('NotAllowedError'), true);
test('and offers a manual route', status.textContent.includes('Ctrl+C'), true);
test('nothing was written on refusal', refused.written.length, 0);
test('an empty box copies nothing', (() => { box.value = ''; return true; })() && await copyAllowed() === 'empty', true);
test('and says so', status.textContent, 'Nothing to copy.');
test('a box of only spaces is also empty', (() => { box.value = ' '; return true; })() && await copyAllowed() === 'empty', true);
test('and neither attempt touched the clipboard: still just the demo copy and the one above', allowed.written.length, 2);
test('copying a changed value copies the new one', (() => { box.value = 'ABJ-772-KM'; return true; })() && (await copyAllowed(), allowed.written.at(-1)), 'ABJ-772-KM');
test('writeText returns a promise', typeof allowed.writeText('x').then, 'function');
test('the status element is announced', status.getAttribute('role'), 'status');
Adapted: a stand-in clipboard, so both the allowed and the refused path are asserted. The demo uses the real API, and if the sandboxed frame is not permitted to use it you will see the error path — which is the half worth seeing.
writeText returns a promise and it genuinely fails: it requires a secure context, and it requires being called during a real user gesture. Calling it from a setTimeout, or after an await that outlives the gesture, is rejected. So await it inside a try/catch, and do the copy first in the handler rather than after other asynchronous work.
Two interface points. Confirm visibly — a copy leaves no trace on screen, so without a message the button is indistinguishable from a broken one. And when it fails, say what to do instead: "select it and press Ctrl+C" is more use than "copy failed". role="status" on the message makes it announced without stealing focus.
Common mistakes
- Not awaiting
writeText. Withoutawaitinsidetry, a refusal is never caught, and "Copied." shows even when nothing was copied. - Copying silently. With no message, a working button and a broken one look the same.
- Copying from a timer, or after other
awaits. The browser only allows it during the user's action. Copy first.
Try it yourself
- Clear the status message 2.5 seconds after it appears, with
setTimeout. - Change the button's own text to "Copied!" for a moment, then back to "Copy".
- Add a second input with a share link, and make one
wireCopy-style function work for both by passing the input in too.