JavaScript Navigator share() Method

Beginner
⏱️ 11 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
🔒 Secure context
Limited availability

What You’ll Learn

navigator.share() opens the device’s native share sheet for text, URLs, and files. Learn ShareData fields, user-gesture rules, pairing with canShare(), five examples, and try-it labs.

01

Kind

Method

02

Returns

Promise<undefined>

03

Status

Limited (not Baseline)

04

Context

Secure (HTTPS)

05

Needs

User gesture

06

Validate with

canShare()

Introduction

Instead of building your own “Share to Twitter / WhatsApp / Mail” menu, the Web Share API hands off to the OS share sheet. The user picks a target they already trust.

Call await navigator.share({ title, text, url, files }) from a button click. On success the Promise resolves with undefined. If the user cancels, you usually get AbortError.

💡
No Dep / Exp / Non-standard banner

MDN marks Limited availability and a secure context, but not Deprecated, Experimental, or Non-standard. Validate with canShare() before sharing files.

Understanding the share() Method

  • ShareData object — optional url, text, title, files.
  • At least one known field — unknown properties are ignored.
  • User gesture required — call from a click / tap handler.
  • Secure context — HTTPS / localhost.
  • Cancel is normal — catch AbortError quietly.
  • Files — test with canShare({ files }) first.

📝 Syntax

General form of the method:

JavaScript
navigator.share(data)

Parameters

  • data (optional but practically required) — object that may include:
    • url — URL string ("" can mean current page).
    • text — text to share.
    • title — title (may be ignored by the target).
    • files — array of File objects.

Return value

  • A Promise that fulfills with undefined, or rejects with a DOMException.

Common exceptions

  • AbortError — user canceled, or no share targets.
  • NotAllowedError — permission / no user gesture / policy block.
  • TypeError — invalid share data.
  • InvalidStateError — document not fully active, or share already in progress.
  • DataError — problem starting the target or transmitting data.

MDN-style URL share

JavaScript
const shareData = {
  title: "MDN",
  text: "Learn web development on MDN!",
  url: "https://developer.mozilla.org"
};

btn.addEventListener("click", async () => {
  try {
    await navigator.share(shareData);
    console.log("Shared successfully");
  } catch (err) {
    console.log("Error: " + err.name);
  }
});

⚡ Quick Reference

GoalCode
Feature detecttypeof navigator.share === "function"
Share URLawait navigator.share({ url, title, text })
Validate firstnavigator.canShare?.(data)
Share filesawait navigator.share({ files, title, text })
Handle cancelif (err.name === "AbortError") …
Secure context?window.isSecureContext

🔍 At a Glance

Four facts to remember about navigator.share().

Returns
Promise

undefined

Status
Limited

Not Baseline

Context
HTTPS

+ user gesture

Cancel
AbortError

Often normal

📋 share vs canShare

canShare()share()
ResultBoolean (sync)Promise (opens UI)
User gestureNot required to checkRequired to open sheet
Best useValidate data / filesActually share
Beginner flowIf true →then await share()

Examples Gallery

Share must run from a user click. Try It Yourself buttons open the native sheet on supporting browsers (especially mobile). Desktop support varies — always feature-detect and offer a copy-link fallback.

📚 Getting Started

Detect Web Share and share a URL from a button.

Example 1 — Feature Detection

Check share, canShare, and secure context.

JavaScript
const lines = [
  "share: " + (typeof navigator.share === "function" ? "available" : "missing"),
  "canShare: " + (typeof navigator.canShare === "function" ? "available" : "missing"),
  "isSecureContext: " + window.isSecureContext
];
console.log(lines.join("\n"));
Try It Yourself

How It Works

If share is missing, show Copy link / mailto fallbacks instead.

Example 2 — Share a URL (MDN)

Open the native share sheet with title, text, and url from a button click.

JavaScript
const shareData = {
  title: "CodeToFun",
  text: "Learn JavaScript on CodeToFun!",
  url: "https://www.codetofun.com/js"
};

async function sharePage() {
  if (typeof navigator.share !== "function") {
    return "Web Share API not supported";
  }
  try {
    await navigator.share(shareData);
    return "Shared successfully";
  } catch (err) {
    return "Error: " + err.name;
  }
}

// Call sharePage() from a button click handler
Try It Yourself

How It Works

Without a user gesture, browsers reject with NotAllowedError.

📈 Practical Patterns

Validate with canShare, handle cancel, and add a fallback.

Example 3 — canShare Then share

Validate data before opening the sheet (especially useful for files).

JavaScript
async function shareIfPossible(data) {
  if (typeof navigator.share !== "function") {
    return "share missing";
  }
  if (typeof navigator.canShare === "function" && !navigator.canShare(data)) {
    return "canShare returned false";
  }
  try {
    await navigator.share(data);
    return "ok";
  } catch (err) {
    return err.name;
  }
}

// From a click:
// shareIfPossible({ title: "Hi", text: "Hello", url: location.href })
//   .then(console.log);
Try It Yourself

How It Works

Detecting canShare also implies a modern Web Share implementation for many browsers.

Example 4 — Treat AbortError as Cancel

User dismissals should not look like app bugs.

JavaScript
async function shareWithFriendlyErrors(data) {
  try {
    await navigator.share(data);
    return { status: "shared" };
  } catch (err) {
    if (err.name === "AbortError") {
      return { status: "canceled" };
    }
    return { status: "error", name: err.name };
  }
}

// shareWithFriendlyErrors({ url: location.href, title: document.title })
//   .then((r) => console.log(JSON.stringify(r)));
Try It Yourself

How It Works

Show a toast only for real errors; stay silent (or say “Share canceled”) on AbortError.

Example 5 — Safe Share + Clipboard Fallback

Progressive enhancement: native share when available, otherwise copy the URL.

JavaScript
async function shareOrCopy(data) {
  if (!window.isSecureContext) {
    return { ok: false, reason: "insecure-context" };
  }
  if (typeof navigator.share === "function") {
    try {
      if (typeof navigator.canShare === "function" && !navigator.canShare(data)) {
        return { ok: false, reason: "cannot-share-data" };
      }
      await navigator.share(data);
      return { ok: true, reason: "shared" };
    } catch (err) {
      if (err.name === "AbortError") {
        return { ok: true, reason: "canceled" };
      }
      return { ok: false, reason: err.name };
    }
  }
  try {
    await navigator.clipboard.writeText(data.url || location.href);
    return { ok: true, reason: "copied" };
  } catch (err) {
    return { ok: false, reason: "clipboard-" + err.name };
  }
}

// Call from a button:
// shareOrCopy({ title: document.title, url: location.href, text: "Check this out" })
//   .then((r) => console.log(JSON.stringify(r)));
Try It Yourself

How It Works

One helper keeps Share buttons working across mobile (native sheet) and desktop (copy).

🚀 Common Use Cases

  • Article share buttons — send title + URL to Messages / social apps.
  • Product pages — share a deep link with short marketing text.
  • Photo galleries — share selected images after canShare({ files }).
  • Invite flows — share a referral URL from a confirmed tap.
  • Progressive enhancement — fall back to copy / mailto when Web Share is missing.

🧠 How navigator.share() Works

1

User clicks Share

Transient activation unlocks the API.

Gesture
2

Optional canShare check

Validate URL / files before opening the sheet.

Validate
3

Native share UI

OS lists targets (Messages, Mail, apps, …).

Sheet
4

Promise settles

Resolves on success, or rejects (often AbortError on cancel).

📝 Notes

  • Limited availability (not Baseline) — feature-detect always.
  • Not Deprecated, Experimental, or Non-standard — no status banner required.
  • Requires HTTPS and a user gesture; gated by web-share permission policy.
  • Pair with canShare() for files.
  • Related: canShare(), taintEnabled(), setAppBadge(), sendBeacon().

Limited Browser Support

navigator.share() is part of the Web Share API and is not Baseline. Support is strongest on mobile Chromium and Safari. Many desktop browsers lack a native sheet — always feature-detect and provide a copy-link fallback.

Limited · Not Baseline

Navigator.share()

Promise → open the native OS share sheet for URL / text / files.

Limited Not Baseline
Google Chrome Strong on Android; desktop varies
Limited
Microsoft Edge Follow Chromium / Windows share UI
Limited
Apple Safari iOS / macOS Web Share where available
Supported
Opera Follow Chromium where available
Limited
Mozilla Firefox Limited / platform-dependent — feature-detect
Limited
Internet Explorer No Web Share API
Unavailable
share() Limited

Bottom line: Detect share on HTTPS, call it from a button click, validate with canShare for files, treat AbortError as cancel, and fall back to clipboard when needed.

Conclusion

navigator.share() is the Web Share API way to open a native share sheet. Call it from a user gesture on HTTPS, validate with canShare() when needed, and keep a copy-link fallback for browsers without Web Share.

Continue with taintEnabled(), canShare(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Call share() from a button click
  • Feature-detect and use HTTPS
  • Validate files with canShare()
  • Handle AbortError as cancel
  • Provide a copy-link fallback

❌ Don’t

  • Open share from timers / page load
  • Assume desktop always has a share sheet
  • Ignore invalid URL / empty ShareData
  • Treat cancel as a hard crash
  • Skip permission-policy / gesture errors

Key Takeaways

Knowledge Unlocked

Five things to remember about share()

Limited Web Share API — native sheet for URL, text, and files.

5
Core concepts
📊 02

Support

Limited

Not Baseline
👋 03

Needs

user gesture

+ HTTPS
04

Validate

canShare()

Especially files
🚫 05

Cancel

AbortError

Normal

❓ Frequently Asked Questions

It opens the device’s native share UI so the user can send title, text, a URL, and/or files to apps like Messages, Mail, or social targets.
No. MDN does not mark it Deprecated, Experimental, or Non-standard. It is Limited availability (not Baseline) and requires a secure context. No status banner is required.
The API requires transient activation (a recent user gesture). Scripts cannot open the share sheet arbitrarily.
canShare(data) returns true if share(data) should succeed. Use it especially before sharing files, then call share from the same click handler.
The Promise is typically rejected with AbortError. Treat cancel as a normal outcome, not a hard failure.
Yes. The Web Share API is a secure-context feature (HTTPS or localhost) in supporting browsers.
Did you know?

On Windows the Promise may resolve when the share popup opens, while on Android it often resolves after data is handed to the chosen target. Always design UX around success / cancel rather than assuming identical timing.

Explore taintEnabled() Next

Learn the legacy always-false JavaScript 1.2 tainting stub.

taintEnabled() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful