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! 🎉

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 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