Web Share API is a JavaScript API that allows websites to share text/URL/file through device’s native share dialog by integrating with the OS. It works only with mobile devices and limited browsers. It was first introduced in Chrome 61 for android.
Features of web share API:
- Capable of sharing URL, plain text or files.
- Native, user-friendly and user-customized share dialogs.
- Less code and OS managed UI. (Developer doesn’t need to handle dialog manually)
- Wide range of sharing options. (Developer doesn’t have to worry about.)
Limitations of web share API:
- Supported only on specific browsers and devices. (Advised to add a fallback to prevent compatibility issues)
- Available only via HTTPS.
- To prevent mishandling, It can be triggered only in response to some user action e.g. click
Note: Web share API is not supported on desktops and over non-HTTPS protocols. Hence, it is necessary to serve webpages over HTTPS in order to use it.
Example:
HTML
<!DOCTYPE html> < html > < head > < title > How to use web share API for native share options in HTML and JavaScript? </ title > </ head > < body style = "text-align: center;" > < h1 style = "color: green;" >neveropen</ h1 > < h2 >Web Share API Demonstration</ h2 > < button id = "shareBtn" >Share</ button > < script > document.querySelector('#shareBtn') .addEventListener('click', event => { // Fallback, Tries to use API only // if navigator.share function is // available if (navigator.share) { navigator.share({ // Title that occurs over // web share dialog title: 'GeeksForGeeks', // URL to share url: 'https://geeksforgeeks.org' }).then(() => { console.log('Thanks for sharing!'); }).catch(err => { // Handle errors, if occurred console.log( "Error while using Web share API:"); console.log(err); }); } else { // Alerts user if API not available alert("Browser doesn't support this API !"); } }) </ script > </ body > </ html > |
Output:
Reference: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share