Recipe 14.5

Sharing Content With the Web Share API

In supported browsers, you can use the operating system’s share functionality to share links.

Demo

Code

JavaScript
const shareButton = document.querySelector('#share-button');

if (!('share' in navigator)) {
  shareButton.disabled = true;
  document.querySelector('#not-supported').classList.remove('d-none');
} else {
  shareButton.addEventListener('click', () => {
    navigator.share({
      title: 'Web API Cookbook',
      url: 'browserapis.dev'
    });
  });
}
HTML
<div id="not-supported" class="alert alert-warning d-none" role="alert">
  This browser does not support the Web Share API.
</div>

<button id="share-button" class="btn btn-primary">Share this page</button>
Web API Cookbook
Joe Attardi