Learn how to easily create a share button on a webpage, that triggers the native share dialog!

I thought about how I might integrate a share functionality into my blog. Now I could set up a share button for all sorts of social media websites. However this often means sharing user information with third parties and limiting the website to share to.

Now this where I saw the opportunity to integrate a native share dialog into this website. Now this only works under certain circumstances:

  • It needs a SSL secured connection (https)
  • It only works on modern mobile browsers like Chrome (> 61) and Safari (> 12.2) *
  • It needs to be triggered by an action, like a click of a button

The actual implementation is pretty easy:

navigator.share({ text: 'Hi!' });

It returns a Promise and needs a object that has at least one of the following properties: test, title, url or files.

So my code looks something like this. I added a check for supporting browsers and used the canonical URL if available:

if (navigator.share) {
  const button = document.getElementById('share-button');
  button.style.display = 'block';
  button.addEventListener('click', function() {
    let url = document.location.href;
    const canonicalElement = document.querySelector('link[rel=canonical]');
    if (canonicalElement !== null) {
      url = canonicalElement.href;
    }
    navigator.share({
      title: 'My awesome title',
      text: 'An awesome text',
      url: url
    });
  });
}

More information about this API: