How-to: using WebShare and browsers "Share this" functionality

Activated the browser native WebShare API for a client. It works beautifully, no need for external services like ShareThis, AddToAny, Shareaholic etc. Site speed and simplicity. And the WebShare API can share directly to apps on mobile.

I’m thinking this could be a {{WebShare}} helper, it is so smooth, and link sharing is critical for independent publishing.

Add a data-webshare attribute to any link or button…

<a href="#" data-webshare >
  <p>Share this</p>
</a>

And then we need javascript to (a) attach the click event listener, and (2) process the Web Share.

In this example we’re sharing title as Document Title, text as the meta description field, and url is the active URL.

// =====================
  // WebShare API Utility Function
  // =====================
  function initWebShare(element) {
    // Check if WebShare API is supported
    if (navigator.share) {
      const metaDescription = document.querySelector('meta[name="description"]');
      // Use data attributes or fallback to metadata description or document.title
      const shareData = {
        title: element.getAttribute('data-share-title') || document.title,
        text: element.getAttribute('data-share-text') || (metaDescription ? metaDescription.getAttribute('content') : document.title),
        url: element.getAttribute('data-share-url') || window.location.href
      };
      console.log('Updated shareData:', shareData);
      // Trigger share dialog
      navigator.share(shareData)
        .then(() => {
          console.log('Page shared successfully');
        })
        .catch((error) => {
          console.error('Error sharing:', error);
        });
    } else {
      console.warn('WebShare API not supported');
      // Optional: Fallback sharing method or user notification
      alert('Sharing is not supported on this browser.');
    }
  }

  // =====================
  // Attach WebShare to elements with data-webshare attribute
  // =====================
  document.querySelectorAll('[data-webshare]').forEach(function(element) {
    element.addEventListener('click', function(e) {
      e.preventDefault();
      initWebShare(this);
    });
  });

This shares the current URL, if you want to share the root domain or any other url add a data-share-url parameter

<a href="#" data-webshare data-share-url="https://www.example.com" >

You may have to wrap this in DOMContentLoaded so it waits until all content is loaded.

document.addEventListener('DOMContentLoaded', function() {
 ....
});

It works on almost all (92%) desktop and mobile browsers except desktop Firefox, plays fine on FF mobile.

Web Share API | Can I use… Support tables for HTML5, CSS3, etc

5 Likes

Here’s an example from a while back, if anyone wants to see how it looks on their device of choice. Needs work on styling— it could look like a normal ghost button with a bit of tweaking.

1 Like

Elegant to make the button invisible if not on a supported platform. It would be great to have a {{webshare}} helper, something like …

{{#webshare}}
 text, button, image etc
{{/webshare}}
1 Like