Allow your mobile visitors to easier share your articles with the Web Share API
Tags: webdev, javascript, tutorial, react
Published: 2021-02-14 15:29:35

---
title: Allow your mobile visitors to easier share your articles with the Web Share API
published: true
date: 2021-02-14 00:00:00 UTC
tags: webdev, javascript, tutorial, react
canonical_url: https://phiilu.com/share-articles-on-social-media-with-the-web-share-api
cover_image: https://phiilu.com/images/og/7663cbee3805c7cf820bdbe36004850a.png
---

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](https://www.w3.org/TR/web-share/) 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](https://images.ctfassets.net/hb3id6ag4raq/4aZeQQwhacNZSAuS8J3ka3/90f10885ec016c11639a17d39fcf2ec2/IMG_174065CE3004-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](https://caniuse.com/web-share).

![Can I Use - Web Share API (14. February 2021)](https://images.ctfassets.net/hb3id6ag4raq/2o3mOIgD492EJ3RxpKbjTr/397db663f087f383da61019734eb01d5/web-share-1613305231346.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](https://twitter.com/phiilu) and I will update it!

{% codesandbox web-share-api-sharing-files-8wlrc %}

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

If you are reading this on [my blog](https://phiilu.com/) 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](https://images.ctfassets.net/hb3id6ag4raq/2cER3ladvU5pzLhRnOIcxv/6c0b892ed81d4ccebe0ea1e01d795c4b/RPReplay_Final1613311858.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](https://github.com/phiilu/phiilu.com/blob/main/src/components/Share/Share.js).

```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](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share)
- W3C: [https://www.w3.org/TR/web-share/](https://www.w3.org/TR/web-share/)