Copy text to the clipboard
Use the async Clipboard API with a legacy fallback and report success or failure to the user.
- JavaScript
- GreenSnippets
- MIT
async function copyText(text) {
if (navigator.clipboard && window.isSecureContext) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
// permission denied or no user gesture: fall through to the legacy path
}
}
const area = document.createElement("textarea");
area.value = text;
area.setAttribute("readonly", "");
area.style.position = "fixed";
area.style.opacity = "0";
document.body.appendChild(area);
area.select();
try {
return document.execCommand("copy");
} finally {
area.remove();
}
}How it works
navigator.clipboard.writeText is the modern way, but it requires a secure context (HTTPS or localhost) and, in some browsers, a user gesture such as a click. The fallback uses a temporary textarea and document.execCommand("copy") (deprecated but still widely supported).
Always tell the user whether it worked, ideally in an aria-live region so screen-reader users hear the result.
This snippet needs a browser, so it has not been executed in an automated test here.
This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.
Related snippets
- CSS
Respect prefers-reduced-motion
Turn off or shorten animations for users who ask their system for less motion.
- CSS
Accessible focus ring with :focus-visible
Show a clear focus outline for keyboard users without drawing it on mouse clicks.
- HTML
Accessible modal with the dialog element
Use the native dialog element for a modal with built-in focus trapping, Escape to close and a backdrop.
- HTML
Accordion with details and summary
A keyboard-accessible FAQ accordion with no JavaScript, including an exclusive group using the name attribute.

