📋 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