Read more

JavaScript: Sharing content with the native share dialog

Tobias Kraze
October 18, 2018Software engineer at makandra GmbH

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.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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.

Posted by Tobias Kraze to makandra dev (2018-10-18 18:14)