Instead of trying to account for all available options, we should now go with two universal sharing options: “Copy link” and “Send email”.
“Copy link”, would work as a convenient way to copy the current page URL to the visitor’s clipboard. Here is Javascript code that will do that:
async function copyShareLink() {
let text = window.location.href;
await navigator.clipboard.writeText(text);
document.querySelector('#share-link').innerText = "Copied";
setTimeout(() => {
document.querySelector('#share-link').innerText = "Copy Link";
}, 1000);
}
With the HTML that triggers it:
<a onclick="copyShareLink();" id="share-link">Copy Link</a>
And the CSS to make it feel like a link:
#share-link:hover {
cursor: pointer;
}
“Send email”, uses the oldest standard for sharing a web page, email, which is still commonly used today, and is guaranteed to still be used in the future! You can set it up to launch the visitor’s email app with a new email draft.
Here's HTML + Javascript code that fills out the subject line with the page's title, and in the message includes the URL and the page's meta description, if available:
<a href="javascript:window.open('mailto:?subject='+document.title+'&body='+encodeURIComponent(document.querySelector('meta[name=description]').content)+'%20'+encodeURIComponent(window.location.href));">Send Email</a>
You can see an example of the working code for both of these options at the end of this article's page.
Top comments (1)
Full code available via GitHub.