Javascript Web Share API

With this API, you can show the native sharing screen on your mobile pages and PWA applications and understand whether it is shared or not.

There are points you need to pay attention to while doing this process.

  • The page you are using must be HTTPS.
  • The process needs to be triggered by the user. So for example it can be used with a click event.
  • With the date of January 2021, the browser support looks good enough.

Now let's first understand if this is supported.

if (navigator.share){
    // supported
} else {
    // not supported
}

We can now share a link.

<button id="share-btn">Share</button>
<script>
    const button = document.getElementById('share-btn');
    button.addEventListener('click', e => {
        e.preventDefault();
        if (navigator.share){
            const shareData = {
                title: 'phpExample',
                text: 'There are very good content on this site',
                url: 'http://phpexample.net'
            }
            navigator.share(shareData)
                .then(() => {
                    alert('Shared successfully')
                })
                .catch(e => {
                    alert('Error occurred while sharing: ' + e)
                });
        }
    });
</script>

You can test this example in your mobile browser in an environment that meets the above conditions.

For more details: https://web.dev/web-share/

Comments

There are no comments, make the firs comment