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