Skip to content
All writing

Nov 2026

Making a copy button work inside Messenger

Why navigator.clipboard fails in Facebook's in-app browser, and the small fallback that fixed KASLCODM's loadout codes.

The main feature of KASLCODM is a button. Tap it, and a Call of Duty: Mobile loadout code is on your clipboard, ready to paste into the game.

CODM players share links in Facebook groups and Messenger chats, so a lot of people open the site inside Facebook's in-app browser instead of Chrome or Safari. That's where a plain copy button stops being reliable.

The problem

The modern way to copy is navigator.clipboard.writeText(). In in-app browsers it can be missing or denied, so the call throws and nothing reaches the clipboard.

The fix

Try the modern API first. If it throws, fall back to the old method: put the text in a hidden textarea, select it, and run document.execCommand("copy").

export async function copyText(text: string) {
  try {
    await navigator.clipboard.writeText(text);
    return;
  } catch {
    // Missing or denied (e.g. Messenger/Facebook webview): fall through to the legacy path.
  }
  const el = document.createElement("textarea");
  el.value = text;
  el.setAttribute("readonly", "");
  el.style.position = "fixed";
  el.style.opacity = "0";
  document.body.appendChild(el);
  el.select();
  const ok = document.execCommand("copy");
  el.remove();
  if (!ok) throw new Error("copy failed");
}

A few details matter:

  • The textarea is readonly, so phones don't open the keyboard when it gets selected.
  • It's position: fixed and invisible, so selecting it doesn't scroll the page.
  • execCommand returns false when it fails, so the function throws and the button can say the copy failed instead of pretending it worked.

execCommand is deprecated, but it still works in these webviews, and here it only runs after the modern API has already failed.

The takeaway

Test where your users actually open your site. For a site shared in group chats, that's an in-app browser, not a desktop browser with a fresh profile.