JavaScript: Sharing content with the native share dialog

Mobile Chrome and Safari support the "web share API" which allow you to use the native share functionality of an Android or iOS phone. Some desktop OSs like Windows or MacOS also support native share dialogs. See Can I Use Show archive.org snapshot for a detailed support matrix.

When clicking a share button using this API, the browser will automatically show all installed applications that support content sharing, such as Whatsapp, Facebook, Twitter, e-mail etc.

The API is extremely simple to use:

if (typeof navigator.share === 'function') {
  let data = {
    url: '<url to share>',
    title: '<title to share>',
    text: '<text to share>',
  }
  element.addEventListener('click', (event) => {
    navigator.share(data)
    event.preventDefault()
  })
}

If you require feedback, navigator.share will return a promise that resolves or rejects, depending on whether the sharing was completed.

Note that this will only work on https pages, so to test it in development, you will have to start your development server with SSL.

Tobias Kraze Over 5 years ago