Skip to content
Related Articles

Related Articles

Improve Article
How to use web share API for native share options in Html & JavaScript ?
  • Last Updated : 15 Mar, 2021

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;">GeeksforGeeks</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 occured
                    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:

This method is supported by many browsers that are listed below:

  • Chrome android (61+)
  • Firefox android (79+)
  • Opera android (48+)
  • iOS Safari (12.2+)
  • Samsung Internet (8.0+)

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/share




My Personal Notes arrow_drop_up
Recommended Articles
Page :