Web Share API

The Web Share API allows to easily share content from the web app to other apps or services on the user's device. This API enables users to share text, URLs, images, and other media with just a few taps or clicks.

Here is the JavaScript code that will handle the sharing functionality:

if (navigator.share) {
    navigator.share({
        title: 'Web Share API Tutorial',
        text: 'Learn how to use Web Share API',
        url: window.location.href
    })
    .then(() => {
        console.log('Content shared successfully.');
    })
    .catch((error) => {
        console.error('Error sharing content:', error);
    });
} else {
    console.error('Web Share API not supported.');
}

This JavaScript code checks if the user's browser supports the Web Share API. If it does, the code calls the navigator.share() method to share the content. The navigator.share() method takes an object with the following properties:

  • title (optional): The title of the content being shared.
  • text (optional): The text of the content being shared.
  • url (optional): The URL of the content being shared.

In this code, we're setting the URL to the URL of the current page. The navigator.share() method returns a Promise, so we're using the then() and catch() methods to handle the success and error cases.

Demo

Enter the title and text you want to share:


More Readings!