Copy text to the clipboard

Use the async clipboard API with a fallback for older browsers.

javascript beginner #clipboard#dom#ux
在游乐场中打开
js-copy-to-clipboard.js
async function copyText(text) {
  if (navigator.clipboard && window.isSecureContext) {
    await navigator.clipboard.writeText(text);
    return true;
  }
  const area = Object.assign(document.createElement("textarea"), { value: text });
  area.style.position = "fixed"; area.style.opacity = "0";
  document.body.appendChild(area);
  area.select();
  const ok = document.execCommand("copy");
  area.remove();
  return ok;
}

copyText("Hello from PandaDev").then((ok) => console.log("copied:", ok));