← Tous les articles

A JavaScript copy-to-clipboard button that actually works

Promo codes, referral links, API keys, code snippets: the Copy button looks trivial until it silently fails. HTTPS, user gestures, iframes, Safari and accessibility, plus the version we ship in production.

A JavaScript copy-to-clipboard button that actually works

Key points

  • navigator.clipboard.writeText() only exists on HTTPS (or localhost) and must follow a user action.
  • Keep a fallback, and always tell the user whether the copy worked.
  • Don’t wait on the network between the click and the copy: Safari will refuse the write.

A Copy button is one of those features you build in five minutes and debug for an hour. It works on the developer’s machine; then a customer reports that nothing happens on their iPhone, or inside the third-party tool where your widget is embedded, or on the staging site they’re reviewing. And the button matters: it’s often what hands over a promo code, a referral link or an API key, so a silent failure turns straight into a support request. The Clipboard API is small, but it has firm rules. Here’s how to build a reliable button, and the cases that caught us out.

What the Clipboard API requires

First, navigator.clipboard only exists in a secure context, meaning HTTPS or localhost. On a staging server served over plain HTTP it’s simply undefined, which is why “Cannot read properties of undefined (reading ‘writeText’)” keeps showing up in QA when everything worked locally.

Second, the write has to come from a user gesture such as a click or key press. A copy triggered on page load or from a timer gets refused.

Third, and easy to forget: inside a cross-origin iframe, Chrome needs the parent page to allow it with allow="clipboard-write" on the <iframe> tag. If you ship an embeddable widget, put that in your integration docs.

Reading the clipboard is far more locked down than writing to it, with permission prompts depending on the browser. A Copy button only ever needs to write, which keeps things simpler.

A copy function with a fallback

We try the modern API first, then fall back to the old approach: a temporary textarea that gets selected and copied. execCommand('copy') is deprecated, yet still worth keeping as a safety net for when the API is missing or rejected:

async function copyText(text) {
  if (navigator.clipboard && window.isSecureContext) {
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch (e) {
      // Rejected (iframe, unfocused document...): try the old way
    }
  }
  return legacyCopy(text);
}

function legacyCopy(text) {
  const area = document.createElement('textarea');
  area.value = text;
  area.setAttribute('readonly', '');
  area.style.position = 'fixed';
  area.style.opacity = '0';
  document.body.appendChild(area);
  area.select();
  let ok = false;
  try {
    ok = document.execCommand('copy');
  } catch (e) {}
  area.remove();
  return ok;
}

Two details in the fallback matter. readonly stops the on-screen keyboard from popping up on mobile when the text is selected, and the fixed position keeps the page from jumping to the bottom when the textarea is added. The function also always resolves to a boolean, so the interface can respond either way instead of leaving a rejected promise unhandled.

Visible, accessible feedback

A button that copies silently leaves people unsure: they click three times, then select the text by hand anyway. So announce the result, screen readers included, with an aria-live region:

<p>
  Your code: <code id="promo-code">WELCOME10</code>
  <button type="button" data-copy="#promo-code">Copy</button>
  <span class="status" aria-live="polite"></span>
</p>
document.addEventListener('click', async (e) => {
  const button = e.target.closest('[data-copy]');
  if (!button) return;

  const source = document.querySelector(button.dataset.copy);
  const status = button.parentElement.querySelector('.status');
  const ok = await copyText(source.textContent.trim());

  status.textContent = ok ? 'Copied!' : "Couldn't copy: please select the text.";
  clearTimeout(button._timer);
  button._timer = setTimeout(() => { status.textContent = ''; }, 2500);
});

One listener on document handles every Copy button on the page, including ones added after load. The timer resets on each click so the message doesn’t vanish early after a double click. And the failure message tells people what to do next, which saves a support ticket.

The Safari trap: nothing between click and copy

The bug that cost us the most time was a Share button that asked the server for a link and then copied it. Chrome let it through; Safari refused. Waiting on the network breaks the connection to the original click, so Safari decides the user never asked for the copy.

The simplest fix is to have the text ready before the click: generate the link when the page loads or when the share panel opens. If that really isn’t possible, navigator.clipboard.write() accepts a ClipboardItem whose content is a promise, so the copy is started during the click and completed when the response arrives:

button.addEventListener('click', () => {
  const content = fetch('/api/share-link', { method: 'POST' })
    .then((r) => r.json())
    .then(({ url }) => new Blob([url], { type: 'text/plain' }));

  // write() is called during the click; the promise resolves later
  navigator.clipboard
    .write([new ClipboardItem({ 'text/plain': content })])
    .then(() => show('Link copied'))
    .catch(() => show("Couldn't copy"));
});

Test this on a real iPhone or iPad. Responsive mode in a desktop browser doesn’t reproduce Safari’s rules.

Worked example: a Copy button on every code block

On a technical blog or documentation site, a button on each code block is a real convenience for readers. There’s no need to touch the content: add the buttons on load, reusing copyText():

document.querySelectorAll('pre > code').forEach((code) => {
  const button = document.createElement('button');
  button.type = 'button';
  button.className = 'copy-code';
  button.textContent = 'Copy';
  button.addEventListener('click', async () => {
    const ok = await copyText(code.innerText);
    button.textContent = ok ? 'Copied' : 'Failed';
    setTimeout(() => { button.textContent = 'Copy'; }, 2000);
  });
  code.parentElement.style.position = 'relative';
  code.parentElement.append(button);
});

innerText is used instead of textContent so line breaks match what’s on screen, which matters when a syntax highlighter has split the code into many elements. In CSS, pin the button to the top right with position: absolute, and check it doesn’t hide the end of long lines.

FAQ

Can I copy something other than plain text?

Yes. navigator.clipboard.write() takes ClipboardItem objects for HTML or PNG images. Support for other formats varies between browsers, so test rich content everywhere you need it and provide a plain-text version too.

Why not just use a library?

Clipboard libraries were invaluable before this API existed. Today the twenty-odd lines above cover the same ground with no extra dependency to load or keep updated.

Small interface details like this are what your users notice. We build sites and applications that are polished down to the buttons, and tested on the browsers and devices your customers really use.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →