brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: navigator.clipboard.writeText copies text, with rules about when it may

Javascript
~/tips/tip-javascript-navigator-clipboard-writetext

button.addEventListener("click", async () => {

Writes a string to the clipboard from JavaScript, as long as the page and the moment are allowed.

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

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link