Copy and paste
navigator.clipboard.writeText()
Baseline newly available
Chrome76
Edge79
Firefox127
Safari13.1
Features it needs
- Async clipboardNewly available
These libraries wrap document.execCommand("copy"), a deprecated, synchronous API that needed a hidden textarea and a selection hack to work at all. The async Clipboard API writes text directly and returns a promise, with no DOM element required to hold the value first.
When this applies
Copying text to the clipboard on a button click or similar user action.
The native approach
async function copyText(text) {
await navigator.clipboard.writeText(text);
}When the dependency is still right
An answer that always says "the platform covers it" is worse than no answer. These are the cases where this one does not hold.
- You support Firefox below 63 or Safari below 13.1, where writeText landed later than in Chrome.
- You read from the clipboard as well as writing to it. navigator.clipboard.read() and ClipboardItem arrived years after writeText and are still the part with the thinner support.
- You need to read arbitrary clipboard formats rather than plain text. Reading needs a permission prompt in some browsers and is more restricted than writing.
- You're running without focus or without a secure origin (HTTPS). The API rejects in both cases, so you still need a fallback path for that error.