🚀AdvancedReal-Time Communication

Web Share API

Invoke the native OS share sheet from a web page using navigator.share() to share URLs, text, and files to any app on the device.

Overview

The Web Share API lets web pages invoke the device's native share dialog the same share sheet that appears when you share content in native mobile or desktop apps. Users can share a URL, text, or files directly to WhatsApp, Twitter, email, Notes, or any installed app that accepts the shared data type. This replaces the need for custom share buttons per social network with a single native button that adapts to the user's installed apps and preferences. `navigator.share()` returns a Promise that resolves when the user successfully shares, or rejects if they cancel or if sharing fails. `navigator.canShare(data)` checks whether the specified data can be shared before calling `share()`. The API is supported on Android Chrome, Safari (iOS/macOS), Edge, and increasingly on desktop platforms.

Key Points

  • •`navigator.share({ title, text, url })` opens the native OS share dialog
  • •`navigator.share({ files: [file] })` share File objects (images, documents)
  • •`navigator.canShare(data)` check if data is shareable before calling share()
  • •Must be called from a user gesture (click, touch) not from async code that's not user-initiated
  • •Requires HTTPS (secure context)
  • •On unsupported platforms, provide a fallback (clipboard copy or custom share menu)
  • •The promise rejects with `AbortError` if the user cancels not an error, just user choice

Examples

Share a URL with title and text

<button id="share-btn">Share this article</button>

<script>
document.getElementById('share-btn').addEventListener('click', async () => {
  const shareData = {
    title: 'Amazing Article',
    text: 'Check out this interesting article about web development!',
    url: window.location.href,
  };

  if (!navigator.canShare?.(shareData)) {
    await navigator.clipboard.writeText(window.location.href);
    alert('Link copied to clipboard!');
    return;
  }

  try {
    await navigator.share(shareData);
    console.log('Shared successfully');
  } catch (err) {
    if (err.name === 'AbortError') {
      console.log('User cancelled share');
    } else {
      console.error('Share failed:', err);
    }
  }
});
</script>

AbortError when user cancels is expected behavior do not show an error message for it.

Sharing files (images, documents)

<input type="file" id="file-picker" accept="image/*,application/pdf">
<button id="share-file-btn">Share File</button>

<script>
document.getElementById('share-file-btn').addEventListener('click', async () => {
  const input = document.getElementById('file-picker');
  const files = Array.from(input.files);

  if (files.length === 0) {
    alert('Please select a file first');
    return;
  }

  const shareData = { files, title: 'Shared File' };

  if (!navigator.canShare?.(shareData)) {
    alert('Your browser does not support file sharing.');
    return;
  }

  try {
    await navigator.share(shareData);
  } catch (err) {
    if (err.name !== 'AbortError') console.error(err);
  }
});
</script>

navigator.canShare({ files }) must be called to check file sharing support before navigator.share().

Detecting support and providing rich fallback UI

<div id="share-area">
  <button id="native-share" style="display:none">Share</button>
  <div id="custom-share" style="display:none">
    <a id="tweet-btn" href="https://twitter.com/intent/tweet?url=">Twitter</a>
    <button id="copy-link">Copy Link</button>
  </div>
</div>

<script>
const url = encodeURIComponent(window.location.href);
if ('share' in navigator) {
  document.getElementById('native-share').style.display = 'inline-flex';
  document.getElementById('native-share').onclick = () =>
    navigator.share({ url: window.location.href, title: document.title });
} else {
  document.getElementById('custom-share').style.display = 'flex';
  document.getElementById('tweet-btn').href += url;
  document.getElementById('copy-link').onclick = () =>
    navigator.clipboard.writeText(window.location.href);
}
</script>

Common Mistakes

  • Not checking `navigator.canShare(data)` before calling `navigator.share(data)` sharing files without the check throws in browsers that don't support file sharing
  • Calling `navigator.share()` from a non-user-gesture context (e.g., inside setTimeout) browsers block this for security
  • Treating `AbortError` as a real error and showing the user an error message cancelling the share sheet is a valid user action

Note

On mobile Safari, `navigator.share()` for files requires specific types (images, audio, video, text). PDFs may not be shareable on iOS always call `canShare()` first.

Exercises

Write HTML to solve each exercise. Use Preview to see it render in a live iframe, then mark as done.

Loading editor…

Completed: 0 / 5 exercises

Knowledge Check

Question 1 of 4

What does navigator.canShare(data) do?