How to implement the Web Share API with a fallback

Table of contents

  1. ​Main function and detection
  2. Web Share API
  3. Fallback
  4. Calling the function
  5. Results

Main function and detection

<script language="JavaScript"> openShare = async () => { if (navigator && navigator.share) { await shareNative(); } else { await shareFallback(); } }; </script>

MDN web docs

The Navigator.share() method of the Web Share API invokes the native sharing mechanism of the device.

Web Share API

function async shareNative() { await navigator.share({ text: 'How to implement the Web Share API and a fallback', url: 'https://deckdeckgo.com', }); }

Fallback

A Web Component I developed with Stencil 😉

Load with Unpkg (for example)

<script type="module" src="https://unpkg.com/web-social-share@latest/dist/websocialshare/websocialshare.esm.js"></script> <script nomodule src="https://unpkg.com/web-social-share@latest/dist/websocialshare/websocialshare.js"></script>

We could also import some icons, why not some Web Components 😇

<script src="https://unpkg.com/ionicons@latest/dist/ionicons.js"></script>

Declaration

<web-social-share show="false"> <ion-icon name="logo-twitter" ariaLabel="Twitter" slot="twitter" style="color: #00aced;"> </ion-icon> <ion-icon name="mail" slot="email" ariaLabel="Email" style="color: #ff8ea3;"> </ion-icon> <ion-icon name="logo-whatsapp" ariaLabel="WhatsApp" slot="whatsapp" style="color: #25D366;"> </ion-icon> </web-social-share>

Never heard of slots?

Check out my practical introduction to the subject 😁

Implementation

function shareFallback() { const webSocialShare = document.querySelector('web-social-share'); const shareUrl = 'https://deckdeckgo.com'; const share = { displayNames: true, config: [{ twitter: { socialShareUrl: shareUrl, socialSharePopupWidth: 300, socialSharePopupHeight: 400 } },{ email: { socialShareBody: shareUrl } }, { whatsapp: { socialShareUrl: shareUrl } }] }; webSocialShare.share = share; webSocialShare.show = true; }

Calling the function

<button onClick="openShare()">Share</button>

Results

Cherry on the cake 🍒🎂

Open source example implemented in our starter kit 🚀

Get my slides now 🔥

Author

David Dal Busco

Freelancer by day | Creator of DeckDeckGo by night
TwitterDevGitHubWeb