Last updated: August 28, 2026.
The Clipboard API works in secure contexts and normally requires a user action. Attach it to a real button and handle permission or browser failures.
Copy from a code block
const button = document.querySelector('#copy');
const source = document.querySelector('#code');
const status = document.querySelector('#copy-status');
button.addEventListener('click', async () => {
try {
await navigator.clipboard.writeText(source.textContent);
status.textContent = 'Copied';
} catch (error) {
status.textContent = 'Copy failed. Select the text and copy it manually.';
}
});Make feedback accessible
- Use a button, not a clickable div.
- Place status text in an aria-live region.
- Do not copy without an explicit user action.
- Provide manual selection as a fallback.
Reference: MDN Clipboard writeText reference.