SnippetJavaScript
Copy text to the clipboard
The modern clipboard write with the execCommand fallback older embeds still need — returns whether the copy actually happened.
Last updated
Snippetjavascript
async function copyText(text) {
try {
await navigator.clipboard.writeText(text);
return true;
} catch {
// Older browsers, or a non-secure context: fall back to execCommand.
const el = document.createElement("textarea");
el.value = text;
el.setAttribute("readonly", "");
el.style.position = "fixed";
el.style.opacity = "0";
document.body.appendChild(el);
el.select();
const ok = document.execCommand("copy");
el.remove();
return ok;
}
}How it works
navigator.clipboard.writeText is the modern path — asynchronous, permission-aware, and the only one that works inside newer sandboxed contexts. The try/catch treats every possible refusal (no permission, insecure origin, an old engine) identically: fall back rather than interrogate.
The fallback creates an invisible readonly textarea, selects it, and uses the deprecated-but-everywhere execCommand. position:fixed stops the page from scrolling to the element on focus, which is the classic visible glitch in naive versions.
Edge cases to know
- →The clipboard API requires a secure context (https or localhost) — on plain http you will always be on the fallback path.
- →Both paths must run inside a user gesture (a click handler); calling on page load fails silently in most browsers.
- →execCommand is formally deprecated: keep it as the fallback, never the primary, and expect it to disappear from engines eventually.