Menu

On the Web Share API

October 5th, 2020

I think the Web Share API is very cool. In a nutshell, it taps into the native sharing features on whatever platform you’re on if that platform supports it.

I like this:

On the Web Share API
Web Share API activated on iOS

A heck of a lot more than these things:

On the Web Share API
This is just an image, don’t try to click them. You clicked them didn’t you?

Why?

  • The Web Share API is just a couple of lines of code. Easy! No images, no weighty JavaScript or iframes, no chance of going out of date (cough, Google+).
  • The UI that users see is customized to their platform and perhaps even customized by them to have the things they want in it.

Good job, web standards.

But it’s not supported everywhere. For example, I’m writing this blog post in Chrome, and it doesn’t work in desktop Chrome. But it does work in desktop Safari!

On the Web Share API

So if I’m going to use it, I’d rather test for support before plunking the button on a page. It’s very easy:

if (navigator.share) {

}

Here’s an example where I plop a <button> onto an article, should that API be supported:

That JavaScript does a little fancy dancing to grab the title and first paragraph of the post to use in the API. I like how Jeremy Keith does it at the page level:

if (navigator.share) {
  navigator.share(
    {
      title: document.querySelector('title').textContent,
      text: document.querySelector('meta[name="description"]').getAttribute('content'),
      url: document.querySelector('link[rel="canonical"]').getAttribute('href')
    }
  );
}

You could just pass in strings to those values too. This is just showing off how you might do things dynamically that work on any page.

Jeremy has also been on a kick advocating for a JavaScript-optional version of the Web Share API, which he thinks could work like this:

<button type="share">

And then, for specifying title and text:

<button type="share" value="title,text">

That feels a little funky to me, with the comma. What if the title has a comma in it? And what about specifying the URL? Could we split them all up into attributes? I think I know what Jeremy would say: this is a simple declarative version. If you’d like to change the default behavior, that’s what JavaScript is for.

But also, should it be there at all if the browser doesn’t support it? Well sure, if you polyfill it:

This polyfill turns the button into a mailto: experience if not supported. That’s pretty clever. I think if I was production-bound, I’d probably only slip the button in when the feature is truly supported.

The original post On the Web Share API.