๐Ÿ“‹ JavaScript

Clipboard & Web Share APIs โ€” Copy Buttons and Native Sharing

๐Ÿ“… Jul 4, 2026 โฑ 2 min read

Every code block on this site has a copy button; every good mobile page shares natively. Both are five lines now.

Copy with feedback

btn.addEventListener("click", async () => {
  try {
    await navigator.clipboard.writeText(codeEl.textContent);
    btn.textContent = "โœ“ Copied!";
    setTimeout(() => (btn.textContent = "Copy"), 1500);
  } catch {
    btn.textContent = "Press Ctrl+C";     // clipboard needs HTTPS + permission
  }
});

The feedback swap is not optional โ€” without it users click three times "to be sure". Requires HTTPS (localhost is exempt).

Native share sheet

shareBtn.addEventListener("click", async () => {
  if (navigator.share) {
    await navigator.share({
      title: document.title,
      url: location.href,
    });                    // opens WhatsApp/Telegram/etc. natively on mobile
  } else {
    await navigator.clipboard.writeText(location.href);   // desktop fallback
    toast("Link copied!");
  }
});

For an Indian student audience where sharing means WhatsApp, navigator.share beats a row of social icons โ€” one button, the user's own apps. Files work too: navigator.share({ files: [file] }).

โ† All Articles