DEV Community

Christian Heilmann
Christian Heilmann

Posted on • Originally published at christianheilmann.com

2 1

What’s your excuse for not using the web share API?

The WebShare API is so easy to use, it is a crime people don't use it more. Instead, we have tons of dead "share on $thing" buttons on the web. Many of which spy on your users and lots of them that started as Wordpress plugins but now are security concerns. Instead of guessing how your visitors want to share the current URL or a file you provide, you can call the API and they can pick their favourite:

Animation of the web share API in action. With 10 lines of Code you can turn a button into a share button

This is the code and you can also check it on codepen:

let shareButton = document.querySelector('button');
shareButton.addEventListener("click", async () => {
  try {
    await navigator.share({ title: "Example Page", url: "" });
    console.log("Data was shared successfully");
  } catch (err) {
    console.error("Share failed:", err.message);
  }
});
Enter fullscreen mode Exit fullscreen mode

An empty url means the current document is shared. You can also add a different title, which makes more sense than "Example page".

Reinvent your career. Join DEV.

It takes one minute and is worth it for your career.

Get started

Top comments (2)

Collapse
 
aszabonorbert profile image
Norbert Szabó

Firefox support is zero. :(

Collapse
 
shahzebbbbb profile image
Shahzeb Ahmed

Great post on the WebShare API! It's such an overlooked tool that can really enhance user experience by allowing them to share content the way they prefer. The traditional "share on $platform" buttons often bring privacy concerns, so using the WebShare API makes a lot of sense for both security and simplicity. If you want to take it a step further, Cloudways offers an optimized WordPress environment where you can easily integrate such modern web standards, keeping your site fast, secure, and ready for the future. Thanks for the helpful demo!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay