DEV Community

Cover image for Day 02: Learning JavaScript APIs: Web Share API
Spruce Emmanuel
Spruce Emmanuel

Posted on • Edited on

1

Day 02: Learning JavaScript APIs: Web Share API

Tired of building custom sharing interfaces from scratch? Why go through all that hassle when JavaScript has a built-in tool that lets you tap into the native sharing features of your users' devices? Meet the Web Share API — a handy solution that makes sharing on the web a seamless experience.

In this article, we’ll explore what the Web Share API does and how you can use it to share text, links, and files directly from your web apps.

So after reading this article you'll be working away with knowledge of the Web Share API and how to share various data from texts, to links and even files.

What is the Web Share API?

The Web Share API is a browser feature that allows web applications to access the native sharing capabilities of a user's device. Want to send a link to WhatsApp? Share a file to an email client? All of this becomes effortless, and it works beautifully with mobile devices.

Things You Can Share Using This API

Let’s look at three ways to use the Web Share API:

1. Sharing Text

Sharing text is straightforward. Here’s a simple example:

HTML:

<button id="shareText">Share Text</button>
Enter fullscreen mode Exit fullscreen mode

JavaScript:

const shareTextButton = document.getElementById('shareText');

shareTextButton.addEventListener('click', () => {
  if (navigator.share) {
    navigator.share({
      title: 'Hello World!',
      text: 'Check out this cool text I just shared using the Web Share API!',
    })
      .then(() => console.log('Text shared successfully!'))
      .catch((error) => console.error('Error sharing text:', error));
  } else {
    alert('Your browser does not support the Web Share API.');
  }
});
Enter fullscreen mode Exit fullscreen mode

Preview:

A button labeled

2. Sharing Links

Want to let users share a link? It’s just as simple:

HTML:

<button id="shareLink">Share Link</button>
Enter fullscreen mode Exit fullscreen mode

JavaScript:

const shareLinkButton = document.getElementById('shareLink');

shareLinkButton.addEventListener('click', () => {
  if (navigator.share) {
    navigator.share({
      title: 'Check out this link!',
      text: 'Here’s something interesting:',
      url: 'https://example.com',
    })
      .then(() => console.log('Link shared successfully!'))
      .catch((error) => console.error('Error sharing link:', error));
  } else {
    alert('Your browser does not support the Web Share API.');
  }
});
Enter fullscreen mode Exit fullscreen mode

Preview:

A

3. Sharing Files

With Web Share API, you can even share files. Here’s how users can pick files from their devices and share them:

HTML:

<input type="file" id="fileInput" multiple>
<button id="shareFiles">Share Files</button>
Enter fullscreen mode Exit fullscreen mode

JavaScript:

const fileInput = document.getElementById('fileInput');
const shareFilesButton = document.getElementById('shareFiles');

shareFilesButton.addEventListener('click', () => {
  const files = fileInput.files;
  if (files.length === 0) {
    alert('Please select files to share.');
    return;
  }

  if (navigator.canShare && navigator.canShare({ files })) {
    navigator.share({
      files: Array.from(files),
      title: 'Sharing Files',
      text: 'Here are some files I want to share with you.',
    })
      .then(() => console.log('Files shared successfully!'))
      .catch((error) => console.error('Error sharing files:', error));
  } else {
    alert('Your browser does not support file sharing with the Web Share API.');
  }
});
Enter fullscreen mode Exit fullscreen mode

Preview:

A file input and

Browser Compatibility

The Web Share API is supported on most modern mobile browsers, but desktop support is still catching up. To avoid unpleasant surprises, use the canShare method to check if the API supports what you’re sharing:

JavaScript:

if (navigator.canShare && navigator.canShare({ files: [new File([], 'example.txt')] })) {
  console.log('File sharing is supported!');
} else {
  console.log('File sharing is not supported on this browser.');
}
Enter fullscreen mode Exit fullscreen mode

For detailed browser compatibility, visit the MDN Web Share API documentation.


Wrapping Up

The Web Share API is a game-changer for adding sharing functionality to your apps. By tapping into the native capabilities of users’ devices, it saves you development time while delivering a smooth, polished experience.

So, the next time you’re tempted to build a custom sharing interface, let the Web Share API do the heavy lifting for you.

And hey, if you have any questions, feel free to message me on Twitter at @sprucekhalifa. Don’t forget to follow me for more insights and updates.

Happy coding! 🎉

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay