DEV Community

Cover image for Web Share API: how to use device native share
Lucas Menezes
Lucas Menezes

Posted on • Edited on

Web Share API: how to use device native share

Hey Dev,

Did you know that Web apps can also use the system provided share UI, as native apps do?

Yes, you can! Using the navigator.share() method of the Web Share API in any Web application.

Let's see how!

Code

var btn = document.getElementById("webshareapiButton");

btn.addEventListener("click", function () {
  navigator.share({
    url: document.URL,
    title: document.title,
    text: "Lorem ipsum..."
  });
});
Enter fullscreen mode Exit fullscreen mode

It's very simple! But have some requirements to works...


Requirements

  • Works only on websites running over HTTPS. But works on local development (localhost) for tests.
  • Works only in response to some user action (such as a "click" event). To prevent abuses.

Demo

I made a simple demo code comparing common social media share buttons (links based) and a button calling Web Share API.

Note that some Desktops devices (like Windows, Linux and macOS) have no native share UI. Please, try to click on the button bellow using your Mobile device, to view the native share UI.

Don't forget to include a fallback logic to unsupported devices, like this:

if (navigator.share) {
  // Web Share API is supported, include code here
} else {
  // fallback code
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Now you know how to use Web Share API on any Web application.

To know more details about the Web Share API, like the current Browsers compatibility, see the links bellow.

References


I hope you enjoy it!

Follow me on Twitter
Sponsor my open source projects on GitHub

Top comments (1)

Collapse
 
matiasmasca profile image
Matías Mascazzini

Thank you! the web share API works perfectly