js 实现分享
使用 Web Share API 实现分享
Web Share API 是现代浏览器提供的一种原生分享功能,允许调用操作系统的分享对话框。
if (navigator.share) {
navigator.share({
title: '分享标题',
text: '分享内容',
url: 'https://example.com'
})
.then(() => console.log('分享成功'))
.catch((error) => console.log('分享失败:', error));
} else {
console.log('浏览器不支持Web Share API');
}
自定义社交平台分享
对于不支持Web Share API的浏览器或特定平台分享,可以使用URL scheme实现。

function shareToPlatform(platform) {
const url = encodeURIComponent('https://example.com');
const title = encodeURIComponent('分享标题');
const text = encodeURIComponent('分享内容');
let shareUrl = '';
switch(platform) {
case 'twitter':
shareUrl = `https://twitter.com/intent/tweet?text=${text}&url=${url}`;
break;
case 'facebook':
shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}`;
break;
case 'linkedin':
shareUrl = `https://www.linkedin.com/shareArticle?mini=true&url=${url}&title=${title}`;
break;
case 'weibo':
shareUrl = `http://service.weibo.com/share/share.php?url=${url}&title=${title}`;
break;
}
window.open(shareUrl, '_blank', 'width=600,height=400');
}
复制链接到剪贴板
实现复制当前页面URL到剪贴板的功能。

function copyToClipboard() {
const url = window.location.href;
navigator.clipboard.writeText(url)
.then(() => alert('链接已复制到剪贴板'))
.catch(err => console.error('复制失败:', err));
}
邮件分享
生成邮件分享链接,预填充主题和正文。
function shareViaEmail() {
const subject = encodeURIComponent('分享标题');
const body = encodeURIComponent(`分享内容\n${window.location.href}`);
window.location.href = `mailto:?subject=${subject}&body=${body}`;
}
二维码分享
使用第三方库生成当前页面的二维码。
// 需要先引入qrcode.js库
function generateQRCode() {
const qrCode = new QRCode(document.getElementById('qrcode'), {
text: window.location.href,
width: 128,
height: 128
});
}
注意事项
- Web Share API仅在HTTPS环境下或localhost可用
- 移动端浏览器对分享API的支持更好
- 自定义分享按钮需要考虑各平台的URL scheme差异
- 复制剪贴板功能可能需要用户交互触发
- 二维码生成需要引入第三方库如qrcode.js






