CodeWithAavi › Blog › Copy and WhatsApp share buttons in JavaScript

JavaScript 8 min read

Copy to Clipboard and WhatsApp Share Buttons in JavaScript

A Copy button and a WhatsApp share button are the two most useful buttons on a content site. This tutorial builds both with plain JavaScript, no libraries. You get a live demo to try first, the full code to copy, a fallback that works on older browsers, and the mistakes that make these buttons fail on phones.

Updated: October 2026

Try it first

Edit the text, then press the buttons. Copy puts the text on your clipboard (paste it anywhere to check) and Share opens WhatsApp with the text ready to send.

The HTML

index.html
<textarea id="text">Hello! Copy or share this message.</textarea>

<button type="button" id="copyBtn">Copy text</button>
<button type="button" id="shareBtn">Share on WhatsApp</button>
<span id="msg" role="status"></span>

The JavaScript: copy with a fallback

The modern way is navigator.clipboard.writeText(). It returns a Promise and only works on HTTPS pages (or localhost) and normally only inside a click or tap handler. For older browsers and plain HTTP pages we add a fallback that selects a hidden textarea and calls document.execCommand('copy').

script.js
const textBox = document.getElementById('text');
const msg = document.getElementById('msg');

function showMessage(text) {
  msg.textContent = text;
  setTimeout(() => (msg.textContent = ''), 2000);
}

function legacyCopy(text) {
  const helper = document.createElement('textarea');
  helper.value = text;
  helper.setAttribute('readonly', '');
  helper.style.position = 'fixed';
  helper.style.opacity = '0';
  document.body.appendChild(helper);
  helper.select();
  helper.setSelectionRange(0, text.length); // needed on iOS Safari
  let ok = false;
  try { ok = document.execCommand('copy'); } catch (e) { ok = false; }
  document.body.removeChild(helper);
  return ok;
}

async function copyText(text) {
  if (navigator.clipboard && window.isSecureContext) {
    try {
      await navigator.clipboard.writeText(text);
      return true;
    } catch (e) {
      // permission denied or not allowed: try the fallback
    }
  }
  return legacyCopy(text);
}

document.getElementById('copyBtn').addEventListener('click', async () => {
  const ok = await copyText(textBox.value);
  showMessage(ok ? 'Copied!' : 'Could not copy. Please copy it manually.');
});

The JavaScript: WhatsApp share

WhatsApp accepts a link in the form https://wa.me/?text=YOUR_TEXT. The text must be URL-encoded, and encodeURIComponent() does that, including line breaks. Open the link inside the click handler, otherwise the browser's pop-up blocker may stop it.

script.js
function shareOnWhatsApp(text) {
  const url = 'https://wa.me/?text=' + encodeURIComponent(text);
  window.open(url, '_blank', 'noopener');
}

document.getElementById('shareBtn').addEventListener('click', () => {
  shareOnWhatsApp(textBox.value + '\n\nhttps://www.example.com/');
});

Adding your page link after the text turns every share into a visit back to your site.

Bonus: use the phone's native share sheet

On most phones the Web Share API opens the system share sheet, so people can pick WhatsApp, Telegram, Instagram or anything else. It needs HTTPS and a tap, and it is not available on every desktop browser, so keep the WhatsApp link as a fallback:

script.js
async function shareSmart(text, pageUrl) {
  if (navigator.share) {
    try {
      await navigator.share({ text, url: pageUrl });
      return;
    } catch (e) {
      if (e.name === 'AbortError') return; // user closed the sheet
    }
  }
  shareOnWhatsApp(text + '\n\n' + pageUrl);
}

Why these buttons fail (and how to fix them)

  • Nothing happens on an HTTP page. navigator.clipboard needs a secure context. Serve the page over HTTPS, or rely on the fallback above.
  • Copy works on desktop but not on iPhone. Safari needs the text selected with setSelectionRange and the call made directly in the tap handler.
  • The WhatsApp window is blocked. Call window.open directly in the click handler. If you wait (for example with setTimeout) the browser no longer treats it as a user action and may block it.
  • Line breaks vanish. Always pass text through encodeURIComponent() so new lines become %0A.
  • The button feels broken. Always show feedback such as "Copied!". Silent buttons look like they did nothing.

Where we use this

These are the same two buttons that sit under every shayari on ShayariGarden. Open any shayari page to see them in action. For more copy-and-paste code, browse our free projects.

Frequently asked questions

How do I copy text to the clipboard with JavaScript?

Call navigator.clipboard.writeText(text) inside a click handler on an HTTPS page. It returns a Promise. For older browsers, select a hidden textarea and call document.execCommand('copy') as a fallback.

Why does navigator.clipboard not work on my website?

It only works in a secure context (HTTPS or localhost) and usually only in response to a user action such as a click. Test on your live HTTPS address, not on a file opened from your computer.

How do I add a WhatsApp share button to my website?

Create a link or button that opens https://wa.me/?text= followed by your text passed through encodeURIComponent(). Open it with window.open inside the click handler so pop-up blockers allow it.

What is the Web Share API and should I use it?

It opens the device's own share sheet, so people can choose any app. It is supported on most phones but not on every desktop browser, so use it when navigator.share exists and fall back to a WhatsApp link otherwise.

Can I put the page link in the WhatsApp message?

Yes. Add the address after the text, for example text + '\n\n' + 'https://www.example.com/'. People who tap the link in the chat land on your page.