# Web Share API

The Web Share API allows web applications to share text, links, and other content to an arbitrary destination of the user's choice (like social media apps, email, or system clipboard) using the device's native sharing mechanism.

## 1. The Concept

Traditionally, web apps had to implement separate buttons for Facebook, Twitter, Email, etc. The Web Share API invokes the native sharing dialog of the operating system (Android, iOS, Windows, macOS), providing a seamless and familiar experience.

## 2. Basic Usage

The API is accessed via `navigator.share()`. It returns a Promise.

```javascript
const shareButton = document.querySelector('#share-btn');

shareButton.addEventListener('click', async () => {
  try {
    await navigator.share({
      title: 'Web Share API Demo',
      text: 'Check out this amazing API!',
      url: 'https://developer.mozilla.org',
    });
    console.log('Content shared successfully');
  } catch (err) {
    console.error('Error sharing:', err);
  }
});
```

## 3. Requirements and Limitations

*   **HTTPS:** The page must be served over HTTPS (or localhost).
*   **User Gesture:** `navigator.share()` can only be called in response to a user action, such as a click event. You cannot call it on page load.
*   **Support:** Not all browsers support it (mostly mobile browsers and Safari on desktop). Always check for support.

## 4. Checking Support

Before showing a share button, you should check if the API is supported.

```javascript
if (navigator.share) {
  // Show share button
} else {
  // Fallback to custom share links or clipboard copy
}
```

You can also check if specific data can be shared using `navigator.canShare()`.

```javascript
const shareData = { title: 'MDN', url: 'https://developer.mozilla.org' };

if (navigator.canShare && navigator.canShare(shareData)) {
  // Safe to share
}
```

## 5. Sharing Files

You can also share files (like images or PDFs).

```javascript
if (navigator.canShare && navigator.canShare({ files: filesArray })) {
  navigator.share({
    files: filesArray,
    title: 'Images',
    text: 'Photos from my trip'
  });
}
```

[[programming/javascript/vanilla/javascript]]
[[programming/javascript/vanilla/events]]
[[programming/javascript/vanilla/promises-async-await]]
[[programming/javascript/vanilla/file-api]]