How to Use The Native JavaScript Web Share API

Let users share text, links, and files to their installed apps.

The native Web Share API lets you allow users to share text, links, and files to other apps installed on the device in the same way as platform-specific apps. Let’s take a look at how to use this new feature.

How to share links and text with the Web Share API?

This API exposes a share() method on the navigator object. This is a promise-based method that has a required properties object. You need to pass at least one of the following properties:

  • title — The subject of the share, for example, is used as the subject of an e-mail.
  • text — The message’s body text, for example, is used as the e-mail content.
  • URL — The URL you want to share is appended after your body text.
  • files — The file(s) you wish to share, for example, are used as attachments in an e-mail.

The code example below shows how easy it is to use the native share method and bind it to a simple button click:

How to share files with the Web Share API?

In order to share files with the Web Share API, it’s a good idea to add a check using the navigator.canShare() method to test whether the files can be shared.

Then you can add the files as an array in the files property.

Browser Support for the Web Share API

The browser support for the Web Share API is pretty good, there is no support in Firefox, however. It’s also interesting to see that although Chrome supports it on Windows and Chrome OS, it does not support it on macOS or Linux distributions as of now.

Resources

Conclusion

The Web Share API is a nifty feature that can be useful on some sites to provide a user-friendly way to share. It’s simpler to implement than a bunch of custom-sharing links. Additionally, it automatically shows the user options based on their installed apps.

Thanks for reading. If you have thoughts on this, be sure to leave a comment!

And if you want, you can connect with me on LinkedIn or Twitter!

LEAVE A REPLY

Your email address will not be published. Required fields are marked *