DEV Community

Cover image for Allow your mobile visitors to easier share your articles with the Web Share API
Florian Kapfenberger
Florian Kapfenberger

Posted on • Originally published at phiilu.com on

Allow your mobile visitors to easier share your articles with the Web Share API

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 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

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.

Can I Use - Web Share API (14. February 2021)

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.

if (window.navigator.share) {
  // Web Share API available
} else {
  // Use a fallback method
}
Enter fullscreen mode Exit fullscreen mode

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.

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);
Enter fullscreen mode Exit fullscreen mode

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 and I will update it!

How I added the Web Share API to my blog

If you are reading this on my blog 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

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.

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;
Enter fullscreen mode Exit fullscreen mode

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:

Top comments (0)