copyText

tcmts.share.copyText · #ilq6lm62 · term · runs in the browser

uses navigator

Put some text on the clipboard: by the Clipboard API, or, where a page may not use it (an embedded browser, a page without the permission), by copying a selection of it, as browsers always have. Fails if neither is allowed.

export async function copyText(text: string): Promise<void> {
  try {
    await navigator.clipboard.writeText(text);
    return;
  } catch {}
  const area = document.createElement("textarea");
  area.value = text;
  area.setAttribute("readonly", "");
  area.style.position = "fixed";
  area.style.opacity = "0";
  document.body.append(area);
  area.select();
  const copied = document.execCommand("copy");
  area.remove();
  if (!copied) throw new Error("the browser didn't allow copying");
}

used by