The Web Share API exposes the native device sharing capabilities to a browser, providing a way to trigger the share dialog of a device when a user browsing a site wants to share the content via, for example, email or social media. The API was originally designed for mobile devices but also works on OS X (using Safari).
The web share API exposes a single method -- navigator.share() -- that accepts an object with three properties: URL, text, and title. It returns a Promise that resolves once the user completes the share action.
Once the share API is called, a native sharing window is opened, and a list of available sharing targets is displayed to the user.
Using the native sharing process provides a significant advantage to websites, as it exposes a familiar interface to the user, skips the need to sign in to multiple social networks, and provides new sharing targets that were previously unavailable the browser.
To avoid abuse, the web share API does come with a few restrictions. Your website must be served over HTTPS, and sharing must be triggered by a user action, for example, via a click.
An example of a simple sharing process looks like this:
document.querySelector('.sharebtn').addEventListener('click', shareSite)
function shareSite() {
navigator.share({
title: document.title,
text: 'Hello World',
url: 'https://mewebsite.com',
})
.then(() => {
console.log('Share completed successfuly')
})
.catch((error) => { console.log(`share failed: ${error}`) });
}
The current version of the web share API only includes the ability to share URLs. Additional features, including the ability to share files with other applications, will be added when Web Share API level 2 is released.
The Web Share API level 2 is currently in active development within Chrome. You can follow it's progress on the Chrome status website