Javascript

Javascript Hidden Apis: The Web Share Api

Javascript Hidden Apis_ The Web Share Api

In this snippet we will introduce the Web Share Api in javascript and how to use it to share content across websites.

 

 

 

Most of us who work on website development implemented the sharing functionality before across other websites or social networks. In these times, mostly relying on an external third party library or plugin or use the html meta tags dedicated for sharing.

Therefore, browsers always strive to improve the user experience by relying on the browser’s API without depending on external API’s. So in this regard, we will talk about Share API

The Share Api in javascript belongs to the family of Web Api’s included recently in javascript. The Share Api is part of the Navigator object. It allows websites to share content, urls , or files to user selected share targets.

 

According to mdn web docs the Share Api available only on secure contexts (HTTPS) in some or all supporting browsers.

 

If you experiment the sharing functionality before on your mobile phone whether Android or IOS you will see the share popup which includes many share target like the social apps installed or email apps.

The Web Share API work on the same way. Once executed it invokes the operating system native sharing mechanism of the device to share data such as text, URLs, or files to the available share targets.

So what is the share target? The share target is any application that is capable to handle and share the content. These applications depends on the device which include the email applications, contacts, clipboard, websites, bluetooth, etc. 

 

 

The Share Api exposes these functions:

  • navigator.share(data): Accepts a share data object and returns a promise which resolves successfully if the data shared to the share target. Must be called in response to button click.
  • navigator.canShare(): returns true or false on whether the data can be sharable. 

 

Basic Example:

<button type="button" id="share">Share</button>

 <script>
 	var btn = document.getElementById('share');

 	btn.onclick = function() {
 		const shareData = {
 			title: 'My Website',
 			text: 'Learn web development'
 		}

 		try {
     		// feature check
     		if(navigator.canShare(shareData)) {


     			navigator.share(shareData).then(() => {
     				// share works, the share popup is showing
     			});
     		} else {
     			alert('OOps, share not available at the moment!');
     		}
 		} catch(err) {
 			alert(`Error, ${err}`);
 		}
 	}

 </script>

In this code when the button clicked it should fire a callback which in turn triggers the share functionality. Inside the onclick callback first i prepared the share data object. Then i wrapped the share logic between try catch block so that any exception from share is caught here.

Before invoking navigator.share() i invoked the navigator.canShare(data) which return true if sharing is supported. Once this code is true the navigator.share() will be executed and return a promise which if resolved successfully it will launch the OS native share popup.

 

Share Data

The share data object contains any of these possible values:

  • title: (optional) A string representing a title to be shared.
  • text: (optional) represent text to be shared.
  • url: (optional) url to be shared.
  • files: (optional) represent array of files to be shared. Each file is an instance of File interface.

As you see all these values are optional, but you should pass at least one item. In the above example i passed two items which is the title and text.

 

Possible Exceptions

The Share Api can throw these exceptions if not resolved successfully:

  • NotAllowedError: in case the browser blocked the use of the Share feature or the file share has been block due security reasons.
  • TypeError: in case the share data is omitted or not well formed, for example the share data can unknown values, or url badly formed.
  • AbortError: in case user cancel the share operation.
  • DataError: in case failures in data transmission.

 

Example: sharing url

btn.onclick = function() {
 		const shareData = {
 			title: 'My Website',
 			url: window.location.href
 		}

 		try {
     		// feature check
     		if(navigator.canShare(shareData)) {


     			navigator.share(shareData).then(() => {
     				// share works, the share popup is showing
     			});
     		} else {
     			alert('OOps, share not available at the moment!');
     		}
 		} catch(err) {
 			alert(`Error, ${err}`);
 		}
 	}

 

Example: sharing files:

<div>
  <label for="files">Select files:</label>
  <input id="files" type="file" accept="image/*" multiple />
</div>
 <button type="button" id="share">Share</button>

 <script>
 	var btn = document.getElementById('share');
 	var files = document.getElementById('files')

 	btn.onclick = function() {
 		const files = files.files;

  		if (files.length === 0) {
    		alert('No files selected.');
    		return
  		}

 		const shareData = {
 			title: 'My Website',
 			files,
 		}

 		try {
     		// feature check
     		if(navigator.canShare(shareData)) {


     			navigator.share(shareData).then(() => {
     				// share works, the share popup is showing
     			});
     		} else {
     			alert('OOps, share not available at the moment!');
     		}
 		} catch(err) {
 			alert(`Error, ${err}`);
 		}
 	}

 

 

0 0 votes
Article Rating

What's your reaction?

Excited
0
Happy
1
Not Sure
0
Confused
0

You may also like

Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments