Search code examples
javascriptjqueryweb-share

If web share API is supported it should show up native share dialog else it should go to the URL defined in href of the anchor tag


Below code works well on devices where web share API is supported and shows the native share dialog but throughs "Uncaught (in promise) DOMException: Share canceled" error where web share API is not supported and do not goes to the URL defined in href of the anchor tag.

<a href="https://example.com?utm_source=btn_share" class="btn-share" target="_blank">
    Share on Facebook
</a>


<script type="text/javascript">
    $(".btn-share").click(function(e){
        // Web Share API
        if (navigator.share){
            e.preventDefault();
            navigator.share({
                title: 'This is example website',
                url: 'https://example.com'
            });
        }
    });
</script>

Remove the error so that it should go to the URL defined in href of the anchor tag if web share API is not supported on the device.


Solution

    1. You need to catch the error as navigator.share() is a Promise,

    2. Promise returns "AbortError" If the user chose to cancel the share operation(mostly on mobile devices) or if there are no share targets available (it occurs mostly on desktop devices). So differentiating the "AbortError" on mobile devices and on desktop computer needs some extra mechanism. Reference: https://www.w3.org/TR/web-share/

    The best solution to your problem at the moment is:

    https://jsfiddle.net/g19but5o/2/

    <a href="https://example.com" class="btn-share" target="_blank">
        Share on Facebook
    </a>
    
    $(".btn-share").click(function(clickEvent){
        var self = $(this);
        // Web Share API
        if (navigator.share){
            clickEvent.preventDefault();
            navigator.share({
                    title: 'This is example website',
                    url: 'https://example.com'
                })
                .then(function() {
                    console.log('Successful share');
                })
                .catch(function(error) {
                  console.log('Error sharing:', error);
                  window.open($(self).attr('href'), '_blank');
                });
        }
    });