Stimulus - Web Share API

Use the native browser web sharing capabilities from Stimulus

Stimulus - Web Share API

Premise

Among the more esoteric native browser APIs there’s one that is mostly overlooked (well, tbh most of them are) and thus lead to a whole host of third-party solutions when in fact the browser already includes this capability out of the box: The Web Share API, which allows a site to share text, files, and URLs in a simple, standardized manner.

Note: Of course, there’s a caveat - Firefox does NOT support this functionality: https://caniuse.com/web-share

Starting Point

We start with a grid of four images from https://picsum.photos/. In the caption of each image, next to the title there’s a link that shows a share button. This link already contains the binding to the share Stimulus controller, along with several values and an action defined for each:

  • an action that points to share
  • a title value that contains the image name (unoriginally just Picsum’s ID)
  • a text value for sharing a description (in our case alt text) of the photo
  • a url value containing the image URL, and
  • a file value pointing to a downloadable resource to share (for demonstration purposes, again just the image URL).

https://stackblitz.com/edit/stimulus-web-share-api?file=index.html%3AL60

Challenge

Your challenge is to use the Web Share API - most notably navigator.share() and navigator.canShare - to complete the sharing solution using the provided share data values:

Here’s a preview of the result on Mac OS:

Share dialogs being opened for four images

Caveat

You will have to use feature detection using canShare for certain share data values!

More from

Faceted Search with Stimulus and Turbo Frames
10 December 2024

Harness the power of Stimulus and Turbo Frames to drive a simple but powerful faceted search solution

Stimulus - Video Progress Tracker with LocalStorage
29 October 2024

Store ephemeral user state like video playback progress in localStorage

Stimulus - Image Upload Previews with `URL.createObjectURL`
17 September 2024

Create client-side previews of files using URL.createObjectURL

Cookies
essential