Skip to content
GreenSnippets

Copy text to the clipboard

Use the async Clipboard API with a legacy fallback and report success or failure to the user.

JavaScript
async function copyText(text) {
  if (navigator.clipboard && window.isSecureContext) {
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch {
      // permission denied or no user gesture: fall through to the legacy path
    }
  }
  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();
  try {
    return document.execCommand("copy");
  } finally {
    area.remove();
  }
}

How it works

navigator.clipboard.writeText is the modern way, but it requires a secure context (HTTPS or localhost) and, in some browsers, a user gesture such as a click. The fallback uses a temporary textarea and document.execCommand("copy") (deprecated but still widely supported).

Always tell the user whether it worked, ideally in an aria-live region so screen-reader users hear the result.

This snippet needs a browser, so it has not been executed in an automated test here.

This snippet has been reviewed but was not executed by an automated test. Test it in your own environment before relying on it.