navigator.share With canShare Guard

Feature-detect navigator.share, validate payloads with navigator.canShare before calling it, and await the promise the share sheet resolves.

TypescriptResilience

Code

typescriptsnippet
20 lines
// navigator.canShare answers whether the payload shape is shareable on this
// device before navigator.share is called with it.
async function shareReport(): Promise<void> {
  const payload = {
    title: 'Weekly deploy report',
    text: '42 deploys, 3 rollbacks',
    url: 'https://devexamples.com/report',
  };

  if (!navigator.share) {
    console.log('Web Share unsupported here');
    return;
  }
  if (!navigator.canShare?.(payload)) {
    console.log('payload not shareable on this device');
    return;
  }
  await navigator.share(payload); // resolves when the share sheet closes
  console.log('report shared');
}

Under the hood

Everything runs through the single shareReport.

Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.

Points of care

  • Runs on what the toolchain already provides — nothing beyond it.
  • The snippet leans on navigator — browser-only surfaces a bare Node process cannot provide.

Using it

Its main signature reads async function shareReport()

Output lines are prefixed (Web Share unsupported here, payload not shareable on this device, report shared), so each step’s effect is easy to spot.

Key statements

await navigator.share(payload); // resolves when the share sheet closes
console.log('report shared');
if (!navigator.canShare?.(payload)) {
  console.log('payload not shareable on this device');
  return;
}

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything. The file defines `shareReport` at load time.