How to implement the Web Share API on your website

Week 201 was posted by Charanjit Chana on 2021-08-30.

I first looked at making share sheets available so that I could easily jump from pages on SITEJOY and kick off a Shortcut with the necessary info sent across. Works brilliantly on mobile and Web Share API is fairly well supported on that platform.

Why call share sheets from JavaScript?

It's a good question, for me it was an evolution of my sharing strategy. For this site, at the base of each article/notable item is a list of sharing options. They're the same each time and ordered in a way that is probably meaningful to me but not necessarily to you.

By using native share sheets, I can present a share option that then brings up a sheet with your preferred options. For iOS this means that you get a list of compatible apps followed by a list of compatible actions and shortcuts.

screenshot of the iOS share sheet with only the relevant apps, actions and shortcuts available for handling a URL

Because the share sheet will only reveal compatible items, the example above shows how much easier it is for me to run some common actions that I have for URLs.

Basic requirements

You'll need JavaScript to invoke the share option, so I opted to only include the button on pages on SITEJOY if the option is supported by the browser. If it's not, then you can fall back to the URL bar or the browser's global share sheet.

How to implement the Web Share API

There are two parts to it, first you need to specify the options that will be used to prepare the eventual share sheet options. You can specify the title, text and url like so:

const shareOpts = {
    title: 'Bringing the Web Share API to your website ',
    text: 'A look at how to bring native share sheets to your website using the Web Share API',
    url: '',

Secondly, you call the API. Here I've wrapped it up to make sure it's supported but the most important part is in bold.

// Web Share API supported?
const supported=('share' in navigator);
// if it is supported
if(supported) {
    // get the element
    let shareButton = document.getElementById('web-share');
    // add a click event listener
    shareButton.addEventListener('click', () => {

Try the Web Share API on this page

If you want to see it in action, simply click the button below.

More resources

The W3 Web Share page has lots of documentation and examples on how to handle post-share sheet events in the event of success or failure.

Tags: css, development

Tweet WhatsApp Keep Upvote Digg Tumblr Pin Blogger LinkedIn Skype LiveJournal Like