Start codelab

Codelab Flow

What you will learn

L W Web Share API

In this codelab you will learn how to use the Web Share API which allows you easily trigger the native Android share dialog, passing either a URL or text or both to share.

Setting up the API

It is important to note the following checklist for the Web Share API to work;

  1. You must be served over HTTPS
  2. You can only invoke the API in response to a user action, such as a click
  3. You can also share any URL, not just URLs under your website's current scope
  4. And you may also share text without a URL

To add Web Share to your existing Progressive Web App then create an empty js file called webShare.js in a ./scripts folder as shown below.


Next thing to do is to copy the code below to the empty webShare.js.

This code allows you to use the Web Share API for your PWA. In the code snippet, we have comments explaining what each line of the code does. Read through.
Once invoked, it will bring up the native picker (as in the demo pwa on your phone) and allow you to share the data with the app (whatsapp, facebook, twitter, etc) chosen by the user.
// select the share button with the class 'share-button'
const share = document.querySelector('.share-button');
    // listen to a click event and fire share
    share.addEventListener('click', () => {
        // check if web share is supported
        if (navigator.share) {
                // title of what to share
                title: 'Developer Resources by',
                // text to share
                text: 'Here are resources to learn how to build Progressive Web Apps',
                // url to share
                url: '',
                .then(() => console.log('Successful share'))
                .catch((error) => console.log('Error sharing', error));
        } else {
            console.log(`Web share not supported on desktop...`);

Add to your App

In your page, add the following code at the bottom just before the end of the body tag

<script src="assets/js/webShare.js"></script>

Add a Share button

Add the Share button or icon on your page after configuring the webShare.js file above to fit your web app needs. We need to create a button with its class as share-button.

Add the code below to your page to define the Button for your Progressive Web App and save.

<button class="share-button">Share</button>

Yay! Done! Visit your web app on your phone now and click the your share button. You should see the native picker which allows you to share your PWA with the app (whatsapp, facebook, twitter, etc) you choose.

While on your phone, click the button below to demo our Web Share add-on!