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 book lover

Growing Rails Applications in Practice

Check out our e-book. Learn to structure large Ruby on Rails codebases with the tools you already know and love.

  • Introduce design conventions for controllers and user-facing models
  • Create a system for growth
  • Build applications to last
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)