A “copy” button is the easiest nice thing you can add to a code block. The API is one line, and the rules around it are where the bug reports come from.
button.addEventListener("click", async () => {
try {
await navigator.clipboard.writeText("Copied text");
} catch (error) {
console.error(error.message);
}
});
writeText returns a promise that resolves once the clipboard is updated. If writing is not allowed it rejects with a NotAllowedError, which is why the try block is there.
It is limited to secure contexts, so HTTPS or localhost. MDN also says browsers may require transient user activation, meaning a recent interaction such as a click. Call it from a click handler and that is satisfied everywhere. Chromium also accepts a granted clipboard-write permission, but Firefox and Safari do not support that permission, so do not build on it.
Inside a cross-origin iframe, Chromium needs allow="clipboard-write" on the iframe.
The caveat is that it fails quietly on pages loaded over plain HTTP, where navigator.clipboard does not exist at all, and on calls made from a timer or on page load. Always handle the rejection and tell the person that copying failed. MDN lists the method as widely available since March 2020.
Further reading: MDN: Clipboard.writeText(), MDN: Clipboard API, security considerations