---
title: Allow your mobile visitors to easier share your articles with the Web Share API
icon: /images/icons/web-share-api-icon.svg
slug: share-articles-on-social-media-with-the-web-share-api
publishedDate: 2021-02-14
published: true
description: With the Web Share API you can use the native sharing mechanism of the device.
tags: ['javascript', 'web apis', 'react']
---

Sharing websites is a fundamental process of the web and providing a way to make it as easy as possible can allow users to easily share the work you created.

The [Web Share API][1] allows the user to use the native share mechanism of the operating system. You probably already have seen this when you want to share an image or video using a native app.

![iOS Share Sheet](../../assets/images/posts/share-articles-on-social-media-with-the-web-share-api-1.jpeg)

Because this is using the native sharing mechanism of the OS the Web Share API is not available in all browsers and OS. At the time of writing it is only available in Chrome (only Windows and Chrome OS), Edge, Safari, iOS Safari, Chrome for Android, Firefox for Android, and Samsung Internet. You can find an up-to-date list on [caniuse.com][3].

![Can I Use - Web Share API (14. February 2021)](../../assets/images/posts/share-articles-on-social-media-with-the-web-share-api-2.webp)

## Use the Web Share API if it is available

Browsers that support the Web Share API will expose the `share` method on the `navigator` object. There is also a `canShare` method, but this method is not available in all browsers. So the best way to check if it is available would be to check if the `share` method exists.

```javascript
if (window.navigator.share) {
  // Web Share API available
} else {
  // Use a fallback method
}
```

## Share URLs with the Web Share API

Using the Web Share API is very easy. In its basic version, it is just one function that you call and that's it.

```javascript
const data = {
  title: 'Allow your mobile visitors to easier share your articles with the Web Share API',
  url: 'https://phiilu.com/share-articles-on-social-media-with-the-web-share-api',
  text: 'Allow your mobile visitors to easier share your articles with the Web Share API by Florian Kapfenberger (@phiilu)'
};
const sharePromise = window.navigator.share(data);
```

The `share` method takes an object as its first argument. Here you can define what should be prefilled by the share method that will be used later on.

- `title`: The title that should be prefilled (if supported)
- `url`: The website/URL you want to share
- `text`: A custom text which should be prefilled before sharing

## Share files with the Web Share API

By adding a `files` array to the `share` function you can allow the user to share images too.

Unfortunately, I can't get it working with the devices I have. I tested it with an iPhone 12 (iOS 14) and on macOS.

Here is a CodeSandbox if you want to test it on your device. If the code is not quite right, maybe fork it and write me on [Twitter][5] and I will update it!

<iframe
  src="https://codesandbox.io/embed/web-share-api-sharing-files-8wlrc?fontsize=14&hidenavigation=1&theme=dark"
  style="width:100%; height:500px; border:0; border-radius: 4px; overflow:hidden;"
  title="Web Share API - Sharing Files"
  allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
  sandbox="allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts"
></iframe>

## How I added the Web Share API to my blog

If you are reading this on [my blog][6] and you are using a supported device you can test it out right now!

If supported, you should see a button **Share Anywhere**. Try it out :)

![Web Share API - iOS Share](/images/posts/share-articles-on-social-media-with-the-web-share-api-3.gif)

In React I created a new `Share` component. If the `share` method is available I will show the **Share Anywhere** button additional to the "Fallback" share buttons.

You can find the up-to-date file on my [GitHub][8].

```javascript
import * as React from 'react';
import toast from 'react-hot-toast';

import Button from '@components/Button/Button';

function Share({ title, url, onClick }) {
  const [isSareApiAvailable, setIsSareApiAvailable] = React.useState(false);

  React.useEffect(() => {
    setIsSareApiAvailable(!!window.navigator.share);
  }, []);

  function handleSocialShare() {
    try {
      const res = window.navigator.share({
        title,
        text: `${title} by Florian Kapfenberger (@phiilu)`,
        url
      });

      toast.promise(res, {
        loading: {
          title: 'Share the post with the world',
          text: 'Select how you want to share the post',
          dismiss: false
        },
        success: {
          title: 'Shared successfully',
          text: 'Thank you for sharing my post!',
          dismiss: true
        },
        error: {
          title: 'So close',
          text: 'Oh okay.. Maybe next time :)',
          dismiss: true
        }
      });
    } catch (error) {
      // do nothing
    }
  }

  return (
    <ul className="space-y-2 sm:items-start sm:space-x-2 sm:space-y-0 xl:space-y-2 sm:flex xl:space-x-0 xl:block">
      {isSareApiAvailable && (
        <li className="w-full">
          <Button
            tracking={{
              event: 'click',
              value: 'Share Anywhere clicked',
              name: 'Share Anywhere clicked'
            }}
            variant="secondary"
            onClick={handleSocialShare}
          >
            Share Anywhere
          </Button>
        </li>
      )}
      <li className="w-full">
        <Button
          tracking={{
            event: 'click',
            value: 'Share on Twitter clicked',
            name: 'Share on Twitter clicked'
          }}
          variant="twitter"
          onClick={onClick(
            `https://twitter.com/share?text=${title} via @phiilu&url=${url}`,
            'twitter-share',
            'width=550,height=235'
          )}
        >
          Share on Twitter
        </Button>
      </li>
      <li className="w-full">
        <Button
          tracking={{
            event: 'click',
            value: 'Share on Hacker News clicked',
            name: 'Share on Hacker News clicked'
          }}
          variant="hackernews"
          onClick={onClick(
            `https://news.ycombinator.com/submitlink?u=${url}&t=${title}`,
            'hn-share',
            'width=550,height=350'
          )}
        >
          Share on Hacker News
        </Button>
      </li>
    </ul>
  );
}

export default Share;
```

## Conclusion

With just a few lines of code, you can improve the sharing process for your mobile users, and for unsupported browsers, you can provide a fallback method. Hopefully, this will not be needed anymore in the future.

**Sources:**

- MDN: [https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share][9]
- W3C: [https://www.w3.org/TR/web-share/][1]

[1]: https://www.w3.org/TR/web-share/
[3]: https://caniuse.com/web-share
[5]: https://twitter.com/phiilu
[6]: https://phiilu.com/
[8]: https://github.com/phiilu/phiilu.com/blob/867ca7e15c548b003d0cb1d28fa35f1e945f4351/src/components/Share/Share.js
[9]: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share
