// Add event listeners to each share button
var shareButton2 = document.getElementById('share-button2');
shareButton2.addEventListener('click', function() {
// Share the link for the 1 in 4 college students article
var urlToShare = 'https://safechoiceusa.com/articles/1-in-4-college-students-has-an-STI-We-need-to-do-something...html';
var title = '1 in 4 college students has an STI… We need to do something.';
shareLink(urlToShare, title);
});
var shareButton3 = document.getElementById('share-button3');
shareButton3.addEventListener('click', function() {
// Share the link for the STDs in the LGBTQ community article
var urlToShare = 'https://safechoiceusa.com/articles/Sexually%20transmitted%20diseases%20are%20highest%20in%20the%20LGBTQ%20community.html';
var title = 'Sexually transmitted diseases are highest in the LGBTQ community';
shareLink(urlToShare, title);
});
function shareLink(urlToShare, title) {
// Use the Web Share API (if it's available) to share the link
if (navigator.share) {
navigator.share({
title: title,
url: urlToShare
})
.then(function() {
console.log('Thanks for sharing!');
})
.catch(function(error) {
console.log('Error sharing:', error);
});
} else {
// If the Web Share API is not available, fall back to a URL-based approach
var shareUrl = 'https://twitter.com/share?url=' + encodeURIComponent(urlToShare);
window.open(shareUrl, '_blank');
}
}
这对我来说很好:
https://shotor.github.io/web-share-api/
确保您在支持它的浏览器中运行它:https://developer.mozilla.org/en-us/docs/web/api/web/web_share_api#api.navigator.navigator.share
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Web Share API</title>
</head>
<body>
<button
data-share-title="Web Share API @ MDN"
data-share-url="https://developer.mozilla.org/en-US/docs/Web/API/Web_Share_API"
>
Share MDN
</button>
<button
data-share-title="Web Share API @ Google"
data-share-url="https://web.dev/web-share/"
>
Share Google
</button>
<script>
document.querySelectorAll('button').forEach((button) => {
button.addEventListener('click', async () => {
const title = button.getAttribute('data-share-title')
const url = button.getAttribute('data-share-url')
const data = {
title,
url,
}
if (navigator.share) {
await navigator.share(data)
console.log('Thanks for sharing!')
return
}
const shareUrl = `https://twitter.com/share?url=${encodeURIComponent(
url
)}`
window.open(shareUrl, '_blank')
})
})
</script>
</body>
</html>