Skip to content

Instantly share code, notes, and snippets.

@joychetry
Created April 16, 2024 08:28
Show Gist options
  • Save joychetry/4d1e8c60e80360367a27dcee6a35b469 to your computer and use it in GitHub Desktop.
Save joychetry/4d1e8c60e80360367a27dcee6a35b469 to your computer and use it in GitHub Desktop.
Prompt native sharing options inside a post page
<script>
document.addEventListener('DOMContentLoaded', function() {
// Click event listener for images with class 'shareLink'
const images = document.querySelectorAll('.shareLink');
images.forEach(function(image) {
image.addEventListener('click', function() {
const link = document.URL;
// Check if Web Share API is supported
if (navigator.share) {
navigator.share({
title: document.title,
text: 'Check out this link:',
url: link,
}).catch((error) => {
console.error('Error sharing link:', error);
});
} else {
// Fallback to copying link to clipboard for unsupported browsers
const textarea = document.createElement('textarea');
textarea.value = link;
document.body.appendChild(textarea);
textarea.select();
document.execCommand('copy');
document.body.removeChild(textarea);
alert('Link copied to clipboard: ' + link);
}
});
});
});
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment