Web Share API - Implement Share Button on Websites with Native Methods

javascript
Published on July 19, 2019

Use-Cases of this Tutorial

  • Provide a sharing dialog for users (just like on Android) with native browser methods.
  • Know about Web Share API.

The Web Share API helps a user in sharing text or URL in a website by using the sharing mechanism of the device. With this API we can add a "Share" button in a website, and clicking on this would invoke the standard share dialog available on that device.

Share dialog on an Android phone.

Note that this API is mostly for mobiles — where a user can choose an app to share. For desktops, this API does not make much sense (Mac iOS being an exception where it has a feature to share via applications like iMessage, Mail etc).

Demo

Open this page in a mobile browser and click the button below. For desktops this won't do anything (except Mac iOS).

Concepts and Methods Used

Sharing on the web is possible with the Web Share API, which is implemented by the navigator.share() method.

Web Share API Needs HTTPS

The web application needs to be hosted over HTTPS for sharing to work. It won't work on HTTP websites. However it'll work on the localhost environment, HTTP or HTTPS.

Using the Web Share API

The Web Share API is exposed via the navigator.share() method. To this method you can pass an object parameter that contains the data that is to be shared. This object parameter can have 3 properties :

  • title : Title of the shared item
  • text : Description of the shared item
  • url : URL of the shared item

Note that you need to pass at least one of the above properties. You can also pass all the 3 properties if the situation requires.

// API is fairly new, check if it is supported
if(navigator.share) {	
	navigator.share({
		title: "UsefulAngle",
		text: "Code snippets, tutorials and useful angles on web & development",
		url: "https://www.usefulangle.com/"
	})
	.then(function() {
		// success
		console.log("Article shared");
	})
	.catch(function(e) {
		// error message
		console.log(e.message);
	});
}

navigator.share() will returns a Promise object. This Promise is resolved once the user has shared successfully, and rejected if some error occurs or wrong parameters were passed.

In this Tutorial