By using Web Share API, we can implement platform-specific sharing experience in mobile devices from web apps. We can use Web Share API to share text, links, and files to other installed apps on the device.
To share content we use navigator.share
. This method takes an object as an argument with four properties:
At least one option from the above properties should be set; otherwise, TypeError
will be thrown.
The navigator.share
will return a promise that will be fulfilled once the user finishes the share action.
const url = document.querySelector('link[rel=canonical]') && document.querySelector('link[rel=canonical]').href|| window.location.href;if (navigator.share) {navigator.share({title: 'This is the Title of Share',text: 'I am using Web Share API',url}).then(() => console.log('Shared Successfullly')).catch((error) => console.log('Error on sharing', error));}
To share files, we need to check if sharing files is supported by the device using navigator.canShare
. If the device supports file sharing, then we can send the files in the argument.
// creating a filelet imageResponse = await window.fetch('https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png');let imageBuffer = await imageResponse.arrayBuffer();let file = new File([imageBuffer], "Google image", {type: "image/png"});// sharing filelet filesArray = [file];if (navigator.canShare && navigator.canShare({ files: filesArray})) {navigator.share({files: filesArray,title: 'Sharing Files'}).then(() => console.log('Shared successfully.')).catch((error) => console.log('Sharing failed', error));} else {console.log("Sharing Not supported π ");}
In the above code, we have created a file from an image and checked if file sharing is supported on the device. If file sharing is supported, then it will share the file.
- The share can be only invoked upon user action, such as a click.
- Web Share API is only supported on sites that are accessed via HTTPS.