我正在尝试使用Web共享API,以允许用户共享文章URL的链接。我希望是,当用户单击“共享文章”按钮时,用户会收到可以共享的多个社交媒体和应用程序,以及当他们选择首选应用程序时,它将发送我提供的URL。我不确定问题是什么,我在GitHub页面上运行该网站,但我不认为这是问题。 有什么建议或解决方案吗?我将在下面添加代码。

问题描述 投票:0回答:1

javascript

// 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
javascript html share web-share
1个回答
0
投票
在我的情况下,它在桌面Chrome/Firefox上不起作用。但是在Android Chrome上工作正常。

<!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>

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.