The Web Share API

Another day, another Web API! The Web Share API is meant to help developers implement sharing functionality into their apps or websites, but using the device’s native sharing capabilities instead of having to resort to scripts from the individual social platforms and DIY implementations.

The API surface is a simple as it gets. You can even read the entire current spec in just a few minutes. In keeping with that spirit, this post will be a short and sweet one.

Usage

A few notes to help you get started:

  • Your site or web app has to be served over HTTPS in order for the API to work. When developing, running over localhost also works.
  • The navigator.share method has to be called following a user gesture like a button click. It can’t simply be called on page load for example. That’s in place to help prevent abuse.

First, you’ll want to detect if the browser supports the Web Share API. You can simply check to see if navigator.share is defined:

if (navigator.share) {
  // we can use web share!
} else {
  // provide a fallback here
}

The API is promise-based and is as simple to use as passing-in an object to the navigator’s share method. The object should have at least a text or url key, and the title can also be passed-in.

Here’s a simple example. Notice that our logic is inside of a click event handler, to satisfy the requirement that the share be initiated from a user gesture:

const shareBtn = document.querySelector('.share-btn');

shareBtn.addEventListener('click', () => {
  if (navigator.share) {
    navigator.share({
      title: 'My awesome post!',
      text: 'This post may or may not contain the answer to the universe',
      url: window.location.href
    }).then(() => {
      console.log('Thanks for sharing!');
    })
    .catch(err => {
      console.log(`Couldn't share because of`, err.message);
    });
  } else {
    console.log('web share not supported');
  }
});

You may want to grab the page’s title and use the canonical URL if the page has one. Here’s a more complete example that includes just that:

const shareBtn = document.querySelector('.share-btn');
const ogBtnContent = shareBtn.textContent;
const title = document.querySelector('h1').textContent;
const url = document.querySelector('link[rel=canonical]') &&
            document.querySelector('link[rel=canonical]').href ||
            window.location.href;

shareBtn.addEventListener('click', () => {
  if (navigator.share) {
    navigator.share({
      title,
      url
    }).then(() => {
      showMessage(shareBtn, 'Thanks! 😄');
    })
    .catch(err => {
      showMessage(shareBtn, `Couldn't share 🙁`);
    });
  } else {
    showMessage(shareBtn, 'Not supported 🙅‍');
  }
});

function showMessage(element, msg) {
  element.textContent = msg;
  setTimeout(() => {
    element.textContent = ogBtnContent;
  }, 2000);
}

In that example, our share button’s text changes for 2 seconds to indicate if the share was successful, if there was an error sharing or if the Web Share API is not supported at all.

If your using a browser that has support, you can try it out by clicking the button below:


A touch of JavaScript trivia for you

The statement used in the example to grab the url may be confusing at first glance:

const url = document.querySelector('link[rel=canonical]') &&
            document.querySelector('link[rel=canonical]').href ||
            window.location.href;

Here’s some food for thought that will help you understand:

55 && 777; // 777
55 && 777 || 999; // 777
55 && 0 || 999; // 999

In other words, the logical operators && and || work in a way that may be surprising. They don’t return a boolean but rather return either of the lefthand side expression or the righthand side expression depending on the truthiness of the expressions. Refer to this MDR article for more details.

We check if the <link rel=”canonical”> exists, and if so, we grab the value of its href property. Otherwise, we just grab the href from window.location.

You may have also noticed that we use a shorthand in our object literal, which is possible because the variables passed-in have the same names as the object keys.

Web Share API Browser Support

As you can see if you click the Browser Support button below, support for the Web Share API is pretty dismal at this time.

It’s currently only available in Chrome and used to only be available as an origin trial, but as of Chrome 61 it can be used right out of the box.

🍹 Here's to hoping that support gets better soon!

Browser Support

Can I Use web-share? Data on support for the web-share feature across the major browsers from caniuse.com.

  Tweet It
✖ Clear

🕵 Search Results

🔎 Searching...