Tommaso Negri

March 10, 2021

Web Share API

As a user I value products which respect my privacy. For the same reason as a designer and developer I try to respect the privacy of my users as much as I can. Of course as a freelancer I don't have always 100% control over the direction of the product but I do my best.

Sharing functionalities are one of the main pain points when it comes to privacy on a website. Embedding social media buttons usually means opening the door for cross site tracking and other unknown problems.

That's why some time ago I looked for alternatives. For sure the best solution is building your own sharing buttons using social's APIs or custom URLs. However, this process easily becomes tedious, may need maintenance and in general seems a bit hacky. There is a way better alternative for small/medium, the Web Share API.

The Web Share API is an easy access to native sharing functionalities. Unfortunately the support is lacking on the desktop realm but is almost 100% on mobile. In my opinion it is not a problem for the majority of use cases, if you think about it on desktop is easier to just grab the link...

You can get it up and running in just 5 minutes. From the MDN Dock:

const shareData = {
  title: 'MDN',
  text: 'Learn web development on MDN!',
  url: 'https://developer.mozilla.org',
}

const btn = document.querySelector('button');
const resultPara = document.querySelector('.result');

// Must be triggered some kind of "user activation"
btn.addEventListener('click', async () => {
  try {
    await navigator.share(shareData)
    resultPara.textContent = 'MDN shared successfully'
  } catch(err) {
    resultPara.textContent = 'Error: ' + err
  }
});

You can also check if the browser support the API before the action with:

navigator.canShare()

You can also use the same method for conditionally display the share button. In the end is just another piece of a progressive web app.

web-share-api.png


I love this API, it's the way to go for all my personal projects and all my clients willing to make a small sacrifice for respecting the privacy of their users.


———————————

Tommaso Negri
Designer and Developer

www.tommasonegri.com
tommaso@hey.com