JavaScript Snippet

Copy Text to the Clipboard

Difficulty: Easy

Every dashboard, share modal, and code-block UI eventually needs a copy button. The modern path is `navigator.clipboard.writeText`, but it requires a secure context and a user gesture, so a robust helper falls back to a hidden `<textarea>` when the API is unavailable. This snippet covers the modern call, the legacy fallback, and a copy-with-toast helper that wraps both behind a single async function.

Code Snippets
/

Copy Text to the Clipboard

Copy Text to the Clipboard

Every dashboard, share modal, and code-block UI eventually needs a copy button. The modern path is `navigator.clipboard.writeText`, but it requires a secure context and a user gesture, so a robust helper falls back to a hidden `<textarea>` when the API is unavailable. This snippet covers the modern call, the legacy fallback, and a copy-with-toast helper that wraps both behind a single async function.

JavaScript
Easy
3 snippets
js-web-apis
js-dom
utility
code-template

290 views

4

navigator.clipboard.writeText is the modern, async, permission-aware path. It only works in secure contexts (HTTPS or localhost) and inside a user gesture (click, keypress), so the call must run from an event handler, not a side effect on mount. The promise rejects with a NotAllowedError if either condition fails, which gives you a clear branch for falling back. Always wrap calls in try/catch: a thrown error here usually means the user denied the prompt or the page is in an iframe without clipboard-write permission.