Building a share feature can be overwhelming. Taking into account the stress of reading through different platforms (Like Twitter, Facebook or Instagram), developer documentation and app registering, uugh!.
Luckily, some libraries make it easier to implement these features.
However, there is a possibility that you’re someone like me that cares about every extra kb added to a load of whatever I build.
This article would entail my understanding of how best to effect a native share feature on the web. Similar to what the image below communicates.
I would be using the Web Share API to perform this. The API is a promise-based and single object API. Its implementation is as simple as:
if (navigator.share) {
navigator.share({
title: ‘Native share on the Web’,
text: Native share on the Web — PillsOfCodes',
url: '[<https://pillsof.codes/native-share-on-the-web>](<https://pillsof.codes/native-share-on-the-web>)',
})
.then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing', error));
}
Breaking down the code above, we understand that:
if (navigator.share)
checks that the share feature is available to the user by the browsernavigator.share
does the share thing, letting you pass the details you want to share to the share method as an object. The object must have either the text or URL value as it only takes title, text and URL values..then
, .catch
is available to the share method since it is a promise, so we can use it to carry out any action if the share is being initiated or not.