Created
April 16, 2024 08:28
-
-
Save joychetry/4d1e8c60e80360367a27dcee6a35b469 to your computer and use it in GitHub Desktop.
Prompt native sharing options inside a post page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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