This content originally appeared on Bits and Pieces - Medium and was authored by Keerti Kotaru
JavaScript API for web applications to share content including images and videos. Take advantage of the powerful feature that has always been available to Android and iOS apps.
Explore the JavaScript API for invoking the native share dialog. Share like a pro from a web application
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.
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.
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.
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.
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
- Integrate with the OS sharing UI with the Web Share API
- Navigator.canShare() - Web APIs | MDN
- Navigator.share() - Web APIs | MDN
Build component-driven. It’s better, faster, and more scalable.
Forget about monolithic apps, start building component-driven software. Build better software from independent components and compose them into infinite features and apps.
OSS Tools like Bit offer a great developer experience for building component-driven. Start small and scale with many apps, design systems or even Micro Frontends. Give it a try →
Learn more
Up and Running with the JavaScript Share API was originally published in Bits and Pieces on Medium, where people are continuing the conversation by highlighting and responding to this story.
This content originally appeared on Bits and Pieces - Medium and was authored by Keerti Kotaru
Keerti Kotaru | Sciencx (2022-02-16T13:39:56+00:00) Up and Running with the JavaScript Share API. Retrieved from https://www.scien.cx/2022/02/16/up-and-running-with-the-javascript-share-api/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.