Skip to content

Web Share API

This lesson explains Web Share API with clear examples, use cases, and best practices so you can use HTML5 APIs confidently in real web applications.

HTML5 Web Share API Overview

The HTML5 Web Share API allows web applications to invoke the device's native sharing interface. Instead of building custom share menus, developers can let users send links, text, and files to installed apps such as messaging tools, email clients, and social platforms.

The API is especially useful on mobile devices where users expect a familiar system share sheet. It must be called from a secure context and is typically triggered by a user action such as a button click or tap.

Feature Description
API Name Web Share API
Main Method navigator.share()
Support Check navigator.canShare()
Shareable Data Title, text, URL, and files
User Gesture Required for most share calls
Common Uses Articles, products, images, invitations, and links

Basic Web Share Example

<button id="shareButton" type="button">
  Share this page
</button>
const shareButton =
  document.getElementById("shareButton");

shareButton.addEventListener("click", async () => {
  if (!navigator.share) {
    alert("Web Share is not supported.");
    return;
  }

  try {
    await navigator.share({
      title: "HTML5 Web Share API",
      text: "Learn how to use the Web Share API.",
      url: window.location.href
    });

    console.log("Shared successfully.");
  } catch (error) {
    if (error.name !== "AbortError") {
      console.error("Share failed:", error.message);
    }
  }
});

This example opens the native share sheet with a title, message, and current page URL. The promise resolves when sharing succeeds and rejects if the user cancels or the browser blocks the action.

How Web Share API Works

The browser validates the share request, checks whether the data can be shared, and then displays the system share UI. The user chooses a target app, and the selected app receives the shared content.

Step Description Example Syntax
User Action Start sharing from a click or tap. button.addEventListener("click", ...)
Check Support Verify the browser exposes the API. if (navigator.share)
Validate Data Confirm the payload can be shared. navigator.canShare(data)
Open Share Sheet Invoke the native share dialog. navigator.share(data)
Handle Result Resolve on success or catch cancellation. try / catch
Provide Fallback Copy link or show custom UI when unsupported. navigator.clipboard.writeText()

Web Share Data Properties

Property Type Description
title String The title of the shared content.
text String A short message or description.
url String A link to share with other apps.
files Array of File One or more files such as images or PDFs.

Share a Blog Post or Product Link

async function shareArticle(article) {
  const shareData = {
    title: article.title,
    text: article.summary,
    url: article.url
  };

  if (!navigator.share) {
    return false;
  }

  if (navigator.canShare && !navigator.canShare(shareData)) {
    return false;
  }

  await navigator.share(shareData);
  return true;
}

shareArticle({
  title: "Modern CSS Grid Layouts",
  summary: "A practical guide to responsive grid design.",
  url: "https://example.com/css-grid"
});

Articles, tutorials, and product pages are common Web Share use cases. Include a clear title and short description so the shared preview looks useful in messaging and social apps.

Share Files with Web Share API

<input
  id="imageInput"
  type="file"
  accept="image/*" />

<button id="shareImageButton" type="button">
  Share Image
</button>
const imageInput =
  document.getElementById("imageInput");

const shareImageButton =
  document.getElementById("shareImageButton");

shareImageButton.addEventListener("click", async () => {
  const file =
    imageInput.files[0];

  if (!file) {
    alert("Choose an image first.");
    return;
  }

  const shareData = {
    title: "Shared Image",
    text: "Check out this image.",
    files: [file]
  };

  if (!navigator.canShare || !navigator.canShare(shareData)) {
    alert("File sharing is not supported.");
    return;
  }

  await navigator.share(shareData);
});

File sharing is useful for photos, screenshots, PDFs, and exported reports. Always validate the payload with navigator.canShare() before calling navigator.share().

Handle Share Errors and Cancellation

async function safeShare(shareData) {
  try {
    await navigator.share(shareData);
    return { status: "shared" };
  } catch (error) {
    if (error.name === "AbortError") {
      return { status: "cancelled" };
    }

    if (error.name === "NotAllowedError") {
      return { status: "not-allowed" };
    }

    console.error("Share error:", error);
    return { status: "failed" };
  }
}

Users often cancel the share sheet, which throws an AbortError. Treat that as normal behavior instead of showing an error message.

Fallback When Web Share Is Unsupported

async function shareOrCopyLink(shareData) {
  if (navigator.share) {
    try {
      await navigator.share(shareData);
      return;
    } catch (error) {
      if (error.name === "AbortError") {
        return;
      }
    }
  }

  if (navigator.clipboard && shareData.url) {
    await navigator.clipboard.writeText(shareData.url);
    alert("Link copied to clipboard.");
    return;
  }

  prompt("Copy this link:", shareData.url);
}

Desktop browsers and older devices may not support Web Share. Provide a clipboard fallback or custom share UI so users can still distribute content easily.

Feature Detection

function supportsWebShare() {
  return typeof navigator.share === "function";
}

function canShareData(data) {
  if (!supportsWebShare()) {
    return false;
  }

  if (typeof navigator.canShare === "function") {
    return navigator.canShare(data);
  }

  return true;
}

if (supportsWebShare()) {
  console.log("Web Share API supported.");
} else {
  console.log("Web Share API not supported.");
}

Check both API availability and payload compatibility before showing a share button. Hide or replace the button when sharing is not possible on the current device.

Common Web Share API Methods

Method Description Common Use
navigator.share() Opens the native share sheet. Share links, text, and files.
navigator.canShare() Checks whether the payload can be shared. Validate files before sharing.

Common Web Share API Use Cases

  • Sharing blog posts, tutorials, and documentation pages.
  • Sending product links from ecommerce applications.
  • Sharing event invitations and meeting details.
  • Distributing images, screenshots, and exported PDF files.
  • Letting users forward quiz results or achievement summaries.
  • Providing mobile-friendly share actions in progressive web apps.

Web Share API Best Practices

  • Trigger sharing only from explicit user actions such as button clicks.
  • Check support with feature detection before showing share UI.
  • Use navigator.canShare() when sharing files or complex payloads.
  • Keep shared text short, clear, and relevant to the destination app.
  • Handle AbortError quietly when the user cancels sharing.
  • Provide clipboard or custom fallback options on unsupported browsers.
  • Hide the share button when sharing is not available.

Security and UX Considerations

  • Web Share generally requires a secure context such as HTTPS.
  • Do not auto-share content without direct user interaction.
  • Avoid sharing sensitive personal data unless the user clearly intends to.
  • Validate file types and sizes before attempting file sharing.
  • Test on real mobile devices because desktop support is limited.
  • Remember that available share targets depend on installed apps.

Common Web Share API Mistakes

  • Calling navigator.share() without a user gesture.
  • Assuming file sharing works on every browser that supports links.
  • Showing error alerts when the user simply cancels the share sheet.
  • Not providing a fallback on desktop or unsupported browsers.
  • Sharing very long text that gets truncated in target apps.
  • Forgetting to use navigator.canShare() for file payloads.
  • Displaying a share button even when the API is unavailable.

Web Share API vs Custom Share UI

Feature Web Share API Custom Share UI
User Experience Uses the native system share sheet. Requires custom buttons and styling.
Installed Apps Automatically includes device apps. You must link to each platform manually.
Browser Support Strong on mobile, limited on desktop. Works everywhere with manual links.
Maintenance Less code for common sharing flows. More control but more upkeep.

Key Takeaways

  • The Web Share API opens the device's native share sheet from the browser.
  • Use navigator.share() with title, text, URL, or files.
  • Sharing must usually be triggered by a direct user action.
  • navigator.canShare() helps validate file and data payloads.
  • Feature detection, quiet cancellation handling, and fallbacks are essential in production.

Pro Tip

Build one reusable shareContent() helper that checks support, validates data, handles cancellation, and falls back to copying the link. This keeps share buttons consistent across your entire application.