January 23, 2020

hosein

Articles Tutorials

Displaying native share menu in web

Nowadays social media and the concept of sharing content online has become an important part of our daily activities and many companies and individuals take advantage of social media and online marketing to promote and advertise their products or services.

Both android and ios, two most used mobile operating systems have share menu feature which allows users to easily and quickly share links, text, etc by their favorite apps or text message. however in websites this feature wasn’t available and developers had to implement their own custom share menus which didn’t have access to the users’ installed apps until recently.

Web share api is a relatively new web api that enables developers to display native share menu in websites and web apps.

Compatibility

But how compatible are browsers with this feature? according to caniuse both google chrome and safari stable versions support web share api:

google chrome and safari support share api while firefox doesn’t support it yet

How to display native share menu

share api is a function of navigator (user agent) interface, the share function has three parameters: title, text, url

Please note that share api works only if the webpage has HTTPS protocol and navigator.share will not trigger if your website doesn’t have SSL.

Example:

const shareButton = document.querySelector('.share-button');

shareButton.addEventListener('click', () => {
  // check if the browser supports share api
  if (navigator.share) {
  	        navigator.share({
    		title: 'My shop',
    		text: 'Check out this product from my shop:',
    		url: window.location.href,
  		})
    .then(() => console.log('Successful share'))
    .catch((error) => console.log('Error sharing:', error));
}else{
        // fallback: if the browser doesn't support this feature copy link to clipboard and alert the user
	let temp = document.createElement('input'),
        link = window.location.href;
        document.body.appendChild(temp);
        temp.value = link;
        temp.select();
        document.execCommand('copy');
        document.body.removeChild(temp);
        alert('Product URL copied to clipboard!');
}
});

the above code will first check if the browser supports share api, if it does, the share menu will show up and when user chooses an app a message with text and the current page’s url will be sent if the browser doesn’t support this feature, as a fallback we’ll copy the current page’s url to clipboard and let the user know.

While this feature isn’t supported by all browsers yet, it can make web apps and PWAs feel even more like native apps.