在微信內建瀏覽器中,透過 WeixinJSBridge 介面自訂分享給好友、朋友圈、微博的標題、描述、圖片與連結。封裝為 _WXShare 函式,一行代碼完成配置。
| 參數 | 說明 | 預設值 |
|---|---|---|
| img | 分享縮圖 URL | 預設圖片 |
| width | 圖片寬度 | 100 |
| height | 圖片高度 | 100 |
| title | 分享標題 | document.title |
| desc | 分享描述 | document.title |
| url | 分享連結 | location.href |
| appid | 微信 AppID(選填) | 空 |
/*******************************
* 微信分享通用組件
* 使用:_WXShare(img, width, height, title, desc, url, appid)
*******************************/
function _WXShare(img, width, height, title, desc, url, appid) {
// 參數預設值
img = img || 'https://example.com/default-share.png';
width = width || 100;
height = height || 100;
title = title || document.title;
desc = desc || document.title;
url = url || location.href;
appid = appid || '';
// 分享給好友
function shareFriend() {
WeixinJSBridge.invoke('sendAppMessage', {
appid: appid,
img_url: img,
img_width: width,
img_height: height,
link: url,
desc: desc,
title: title
}, function(res) { report('send_msg', res.err_msg); });
}
// 分享到朋友圈
function shareTimeline() {
WeixinJSBridge.invoke('shareTimeline', {
img_url: img,
img_width: width,
img_height: height,
link: url,
desc: desc,
title: title
}, function(res) { report('timeline', res.err_msg); });
}
// 分享到微博
function shareWeibo() {
WeixinJSBridge.invoke('shareWeibo', {
content: desc,
url: url
}, function(res) { report('weibo', res.err_msg); });
}
// 微信 JSBridge 就緒後綁定菜單事件
document.addEventListener('WeixinJSBridgeReady', function() {
WeixinJSBridge.on('menu:share:appmessage', shareFriend);
WeixinJSBridge.on('menu:share:timeline', shareTimeline);
WeixinJSBridge.on('menu:share:weibo', shareWeibo);
}, false);
}
<script src="wxshare.js"></script>
<script>
_WXShare(
'https://mysite.com/share-logo.png', // 圖片
300, 300, // 寬高
'超棒的產品標題', // 標題
'這是詳細描述,吸引點擊...', // 描述
'https://mysite.com/product/123', // 連結
'wx_appid_xxxxx' // AppID (選填)
);
</script>
WeixinJSBridge。