James Cridland

A share button using the browser share API

If you are making a web page and you think it might be useful to add a “share” button, to help share it to social media, then the “right” way to do it is like this:

Make the share button let you share to all the apps your reader has installed and none else

You can use the web share API which is supported by most browsers, particularly on mobile where most people share onto social media from. Notably, it’s supported by Safari, Edge and Chrome, so effectively 90% of all users. The only browser that doesn’t support it is Firefox.

It opens the standard “share” sheet that you get if you press the share button in the operating system. That mostly means you’ll be able to share directly into Mastodon, or Firefox, or X, or Bluesky.

Make the share button the right button for your reader’s operating system

On Apple devices, a “share” icon looks like an arrow pointing out of a box.

On Android devices (and others, I think), a “share” icon looks like a blob with two other blobs attached.

You can use a little JavaScript to make the “right” icon display for your users: they won’t know what the “other” one means.

Don’t load any external code to display this button

Yes, don’t go using any third-party nonsense. By using the standard Firefox or X buttons, they leak data all over the place, and might well be blocked anyway by your reader’s browser. And they slow your website down as they load (and probably make it jump around, too).

Here’s some code that achieves all that. Put an empty <aside> element with an id of “share” somewhere on your page, and this code will add the (right) button. (As currently written, it will cause some layout shift, which you may wish to fix.)

Or, don’t bother

Or, to be honest, don’t bother.

People typically use consistent UX, which means… the share button they’ve already found in their OS anyway, or just copy/pasting the location. Those are both fine.

If you’re running a website aimed at anyone technical, the odds are much higher that they’ll know how to do this. Some numbers I’ve seen as that share buttons get fewer than 0.5% clicks.

But this might be useful for some articles to have a call-to-action at the end of “if this was useful to you, please share it”, maybe.

Anyway - if the code is useful to you - I wrote it and then realised it was more cruft on a page that I really wanted - then help yourself!

Previously...