The gift of giving
Using the next generation of web apps has some clear advantages, one of which is using the navigator's share-API. Thanks to an ever evolving rich set of capabilities, your navigator of choice is now able to invoke Web Share API to share the following items:
- plain text
- links by providing a title
- files directly
If a user's browser supports the new navigator.share, you can use this feature right now!
Demo time!
Using the share-functionality is as straightforward as it gets, here's an example that's actually used on the site:
<Button
className={classes.container}
aria-label={"Share this article"}
onClick={() => {
// '.share' can only by called when
// triggered by click-events to make
// sure it's the user's intention.
navigator.share?.({
title: info.title,
text: info.description,
url: `${getBaseRoute(routes.posts)}/${info.slug.current}`,
}).catch(console.error);
// Optionally virbrate slightly.
navigator.vibrate?.([30, 20, 10]);
}}>
<ShareIcon />
<Typography>{"Share"}</Typography>
</Button>
As you can see, this callback invokes the async share-function (if possible) and provides some data so that a nice URL + descriptive title and subtitle can be shown in the share-sheet. The code shown is used in a slightly different variant at the end of this article. If you browser supports sharing, then a related button will be rendered in the "Actions"-row.
Where to use
As of writing, the API can mostly be used on mobile variants of the popular browsers (Chrome, Opera, Safari) but only on Safari + Edge on Desktop. As this functionality is not limited to specific hardware requirements, I expect support to increase in the coming months.
And yeah, that was a quick intro to the Web Share API, for more information check out the linked web.dev as well as MDN articles in the addendum.
- Tom