Skip to content

Instantly share code, notes, and snippets.

@stephenajulu
Forked from deanhume/web-share.js
Created April 22, 2020 09:18
Show Gist options
  • Save stephenajulu/c37cbebd31a82d728fb41ee002bb2ef6 to your computer and use it in GitHub Desktop.
Save stephenajulu/c37cbebd31a82d728fb41ee002bb2ef6 to your computer and use it in GitHub Desktop.
Web Share API example
var shareButton = document.getElementById('shareThis');
var supported = document.getElementById('support');
// Listen for any clicks
shareButton.addEventListener('click', function (ev) {
// Check if the current browser supports the Web Share API
if (navigator.share !== undefined) {
// Get the canonical URL from the link tag
var shareUrl = document.querySelector('link[rel=canonical]') ? document.querySelector('link[rel=canonical]').href : window.location.href;
// Share it!
navigator.share({
title: document.title,
url: shareUrl
}).then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing:', error));
ev.preventDefault();
} else {
supported.innerHTML = "Unfortunately, this feature is not supported on your browser";
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment