Up and Running with the JavaScript Share API

Explore the JavaScript API for invoking the native share dialog. Share like a pro from a web application

Keerti Kotaru
Bits and Pieces

--

On your phone, did you share a photo, a YouTube video, a blog or a link with friends and family recently? Sharing is easy, a tap away on Android and iOS apps. The share interface is native to the operating system, especially on mobile devices.

Both Android and iOS show a dialog personalized with the apps and users you frequently share. Between the two platforms, the feature is similar with subtle look & feel differences.

The mobile apps take advantage of the share feature to make it easy for users to improve user engagement and share content.

Share images on iOS and Android
Share images on iOS and Android

Web Share

With Web Share, even web applications can take advantage of this feature. You can share directly from the web application. It pulls Android share dialog for Android and iOS share dialog on iPhones. The interface is familiar and easy to use with recent share shortcuts.

To showcase the ease of use and the Web Share API, I’ve the following sample page. Launch it in a separate window.

Notice the share button next to the profile title (Drake Doppelgänger), clicking which launches the share dialog. You share a title, a detailed description and a link to a web page.

Web Share images on iOS and Android
Web Share images on iOS and Android

The Share() API

Begin by creating a JSON object with the data to be shared. Consider the following code snippet from the sample. It creates an object, drakeProfileData with the fields, a title, description text and a URL.

const drakeProfileData = {
title: 'Drake Doppelganger',
text: '💡Share like a pro from your web application',
url: 'https://kvkirthy.github.io/web-share-sample'
}

In the sample, share is invoked on clicking a button. The click handler invokes the JavaScript share() on the navigator object. You pass the data object created in the above snippet as a parameter. See line number 3 in the following code snippet.

1: btn.addEventListener('click', async () => {
2: try {
3: let result = await navigator.share(drakeProfileData);
4: document.getElementById("status").innerText = result || '';
5: } catch(err) {
6: document.getElementById("status").innerText = "Share not complete";
7: }
8: });

The share() function returns a promise. The promise is resolved/rejected after selecting a share target on the dialog.

The await keyword (and the async keyword on function definition in line number 1) simplify working with promises. The result is set to a variable named result’.

Read this blog to learn more about async/await in JavaScript.

If the user cancels sharing midway, the promise is rejected. It invokes the catch block, where we provide a status to the user. See line number 6 in the above code snippet.

What can you share?

The data object can include the following fields,

  • title: Title for the content being shared
  • text: Share a large text block. It could be a message, a detailed description of the artefact being shared.
  • url: A link to a web page or a file on the network.
  • files: An array of files. The files could be images, documents or videos.

Browser Support

Consider the following for browsers supporting the share() API.

Browser Support for Share API

Verify support for share

It is a good practice to test if the browser supports sharing selected content and files.

Use the API canShare() to validate before calling the share function. The function returns true if the browser supports the share. It helps gracefully handle error scenarios.

01:    const drakeProfileData = {
02: title: 'Drake Doppelganger',
03: text: 'üí°Share like a pro from your web application',
04: url: 'https://kvkirthy.github.io/web-share-sample'
05: }
06:
07: const btn = document.querySelector('svg');
08:
09: // Share must be triggered by "user activation"
10: btn.addEventListener('click', async () => {
11: try {
12: if(navigator.canShare
13: && typeof navigator.canShare === 'function'
14: && navigator.canShare(drakeProfileData)){

15: let result = await navigator.share(drakeProfileData);
16: document.getElementById("status").innerText = result || '';
17: } else {
18: document.getElementById("status").innerText = "Sharing selected data not supported.";
19: }

20: } catch(err) {
21: document.getElementById("status").innerText = "Share not complete";
22: }
23: });

See lines of code between 12 and 14. Verify if the canShare is supported on the browser. If the function is defined, invoke canShare for the given data. If this statement returns true then the share() function is invoked.

See lines of code between 17 and 19 that show an error status if share is unsupported.

In a few situations, you may show or hide the share button based on canShare response.

Browser Support

Consider the following for browsers supporting the canShare() API.

Browser Support for canShare API
Browser Support for canShare() API

Gotchas

Consider the following for implementing Web-Share

  • Share cannot call on load. It need to be explicitly invoked on a user action (like button click)
  • Share is supported only in a secure context. Share can only be used on https connection with a valid certificate.

References

Build composable web applications

Don’t build web monoliths. Use Bit to create and compose decoupled software components — in your favorite frameworks like React or Node. Build scalable and modular applications with a powerful and enjoyable dev experience.

Bring your team to Bit Cloud to host and collaborate on components together, and greatly speed up, scale, and standardize development as a team. Start with composable frontends like a Design System or Micro Frontends, or explore the composable backend. Give it a try →

Learn More

--

--