Copying text with navigator.clipboard.writeText() is cleaner, asynchronous, and promise-based compared to the older document.execCommand("copy") approach. Because clipboard access affects user data, browsers require a secure context (HTTPS or localhost) and typically a user gesture like a click.
1. Basic writeText() Implementation with Error Handling
Attach a click handler to a button, await navigator.clipboard.writeText(), and wrap the call in try...catch so permission or environment errors are handled cleanly:
const copyBtn = document.querySelector("#copy-snippet-btn");
const statusText = document.querySelector("#copy-status");
copyBtn.addEventListener("click", async () => {
const textToCopy = "npm install vitest -D";
if (!navigator.clipboard?.writeText) {
statusText.textContent = "Clipboard API unavailable in this browser context.";
return;
}
try {
await navigator.clipboard.writeText(textToCopy);
statusText.textContent = "Copied to clipboard.";
} catch (err) {
statusText.textContent = "Failed to copy text.";
console.error("Clipboard write failed:", err);
}
});
2. Copying Dynamic Content from the DOM or State
Pull live text or formatted output right when the user clicks so they always get the current value:
async function copyElementText(selector) {
const el = document.querySelector(selector);
if (!el) return false;
const value = el.textContent.trim();
await navigator.clipboard.writeText(value);
return true;
}
3. Requirements and Edge Cases to Watch Out For
- HTTPS or
localhostrequired:navigator.clipboardis only exposed in secure contexts—plainhttp://sites on non-localhost domains will not havenavigator.clipboardavailable. - User activation and focus: Calling
writeText()outside a user gesture or when the document/tab is unfocused can reject with aNotAllowedError. - Fallback for older or restricted environments: If you still support legacy browsers or non-secure embeds, keep a small fallback helper around using a temporary
<textarea>anddocument.execCommand("copy")inside atry...catch.
TL;DR: Use await navigator.clipboard.writeText(text) inside a click handler with try...catch, verify navigator.clipboard?.writeText exists, and remember it requires HTTPS (or localhost) plus user interaction.
Are you copying static code snippets, dynamic UI values, or adding a legacy fallback for older browsers?
