Translation: Crazy geek

Original text: css-tricks.com/how-to-use-…

Reproduced without permission

The Web Share API seems to have fallen out of the spotlight since it was first introduced in Chrome 61 for Android. Essentially, it provides a way to trigger the native share dialog on the device (or if you’re using the Safari desktop) when content (such as links or contact cards) is shared directly from a website or Web application.

While users can already share content from a web page locally, they have to find that option in a browser menu, and even then they have no control over what they share. The introduction of this API allows developers to add sharing capabilities to apps or websites by taking advantage of native content sharing capabilities on users’ devices.

Compared with traditional methods, this method has many advantages:

  • Users are provided with a variety of options for sharing content.
  • You can improve page load times by removing third-party scripts from each social platform.
  • No need to add a series of buttons for different social media sites and emails. A single button is sufficient to trigger the device’s native sharing options.
  • Users can customize their preferred sharing targets on their own devices, rather than being limited to pre-defined options.

About Browser Support

Before we dive into how the API works, we need to address browser support issues. To be honest, browser support is not very good at the moment. It only works with Chrome on Android and Safari on desktop and iOS.

The browser support data below comes from Caniuse and contains more details. The number indicates that the browser supports functions of this version or a later version.

desktop

Chrome Opera Firefox IE Edge Safari
No No No No No 12.1

Phone/tablet

iOS Safari Opera Mobile Opera Mini Android Android Chrome Android Firefox
12.2 No No No 74 No

But don’t let that stop you from using the API on your own site. As you can see, it’s easy to implement an alternative on unsupported browsers.

Some requirements for using it

To use this API in your own Web projects, there are two things to note:

  • Your site must be accessed via HTTPS. To facilitate local development, the API can also run when your site is running on localhost.
  • To prevent abuse, only when responding to certain user actions (e.gclickEvent) triggers the API.

Here’s an example

To demonstrate how to use this API, I’ve prepared a demo that works essentially the same as it does on my site. Here’s how it looks like:

To demonstrate how to use this API, I have prepared a demo that works in much the same way as on my website. This is what it looks like:

Codepen. IO/AyoISAIAH/P…

WebShare API Demo – Start
@ayoisaiah
CodePen

When you click the Share button, a dialog box pops up showing some options for sharing content. Here’s the part of the code that helps us achieve this:

shareButton.addEventListener('click', event => { 
  shareDialog.classList.add('is-open'); 
});
Copy the code

Let’s change to using the Web Share API based on this example transfer. First check if the user’s browser supports the API, as shown below:

if (navigator.share) { 
  // Web Share API is supported 
} else { 
  // Fallback 
}
Copy the code

Using the Web Share API is as simple as calling the navigator.share() method, passing an object containing at least one of the following fields:

  • url: a string representing the URL to share. Usually, but not necessarily, the URL of the page. You can Share any URL through the Web Share API.
  • title: A string representing the title to share, usuallydocument.title.
  • text: Any text you want to include.

Here’s how it looks in practice:

shareButton.addEventListener('click', event => { 
  if (navigator.share) { 
    navigator.share({ 
      title: 'WebShare API Demo'.url: 'https://codepen.io/ayoisaiah/pen/YbNazJ' 
    }).then((a)= > { 
      console.log('Thanks for sharing! '); 
    }) 
    .catch(console.error); 
  } else { 
    // fallback }});Copy the code

At this point, once the share button is clicked in a supported browser, the native selector pops up all possible targets with which the user can share data. The target can be a social media application, email, instant messaging, SMS, or other registered shared target.

The API is based on promises, so you can attach a.then() method that might display a success message if the share is successful, with.catch() for error handling. In a real world scenario, you might want to get the page title and URL like this:

const title = document.title; 
const url = document.querySelector('link[rel=canonical]')?document.querySelector('link[rel=canonical]').href : document.location.href;
Copy the code

For urls, we first check if the page has a canonical URL, and if so, use that URL. Otherwise get the href from document.location.

It’s a good idea to offer alternatives

In browsers that do not support the Web Share API, we need to provide alternate mechanisms so that users on those browsers can still get some sharing options.

In our example, there is a dialog box that brings up some options to share content, and the button in the demo isn’t actually linked anywhere because it’s just a demo. But if you want to learn how to create your own links to share web pages without third-party scripting, Adam Coti’s article gives you a great idea.

What we want to do is display the alternate dialog box on the browser without supporting the Web Share API. This is as simple as moving the code to open the shared dialog to the else block:

shareButton.addEventListener('click', event => { 
  if (navigator.share) { 
    navigator.share({ 
      title: 'WebShare API Demo'.url: 'https://codepen.io/ayoisaiah/pen/YbNazJ' 
    }).then((a)= > { 
      console.log('Thanks for sharing! '); 
    }) 
    .catch(console.error); 
  } else { 
    shareDialog.classList.add('is-open'); }});Copy the code

Now, no matter which browser you use, you can cover all users. Here’s a comparison of the shared button behavior on two mobile browsers, one that supports the Web Share API and the other that doesn’t:

Test a shared button that supports this feature on an Android device. Pressing the share button triggers Android’s native share option. The second test shows that the contribute button was clicked on an Android device that does not support this feature. This results in backup sharing options that are manually added.

Go to CodePen and use a browser that supports and does not support Web Share to try it out! (codepen. IO/ayoisaiah/p…

WebShare API Demo – End
@ayoisaiah
CodePen

conclusion

This article has covered almost everything about the Web Share API. By adding it to your site, visitors can more easily share your content across more social networks through contacts or other native apps.

It is worth noting that if your Web application meets the installation criteria for progressive Web applications, you can add it to the user’s home screen as a shared target. This is a feature of the Web Share Target API that you can read about at Google Developers.

There are many supported browsers, but it’s easy to implement fallbacks, so I see no reason why you shouldn’t do it this way. If you want to learn more about this API, you can read the specification here.

Have you ever used the Web Share API? Please share in the comments.

## Welcome to the front end public account: Front End Pioneer, get the front end engineering practical toolkit.