brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: navigator.share() opens the phone's own share sheet from a button

Javascript
~/tips/tip-js-navigator-share-sheet

shareButton.addEventListener("click", async () => {

Let visitors share a page to any app they have installed, with a fallback for desktops.

Rows of social media buttons only cover the apps you thought of. navigator.share() opens the operating system’s share menu, which lists the apps the visitor actually uses.

shareButton.addEventListener("click", async () => {
  const data = { title: document.title, url: location.href };

  if (navigator.canShare?.(data)) {
    try {
      await navigator.share(data);
    } catch (err) {
      if (err.name !== "AbortError") console.error(err);
    }
  } else {
    await navigator.clipboard.writeText(data.url);
    shareButton.textContent = "Link copied";
  }
});

You pass a title, text and url (and on some platforms files), and the system takes over. The promise resolves when sharing is done and rejects with an AbortError when the user closes the sheet, which is not an error worth reporting, hence the check.

There are rules. It only works on HTTPS, and only in response to a user action like a click; calling it on page load fails. canShare() tells you if the data can be shared at all.

Support is where the fallback comes in. Safari and Chrome on phones support it, and Chrome on desktop since version 128 according to MDN, but Firefox on desktop only has it behind a flag. So I’d always keep a copy link fallback for when it is missing.

Further reading: MDN: Navigator.share(), MDN: Navigator.canShare()

More Javascript tips node --inspect-brk app.js obj?.prop const filePath = String.raw`C:\Development\profile\about.html`; const observer = new ResizeObserver((entries) => { URL.parse("not a url"); // null All Javascript tips (40) All topics

Link