萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

微信網頁分享通用組件:自訂標題、描述、圖片、鏈接

在微信內建瀏覽器中,透過 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。
  • 需在微信公眾平台配置 **JS 安全域名**,否則 JSBridge 不會就緒。
  • 現代微信開發建議使用 **微信 JS-SDK (wx.config / wx.updateAppMessageShareData)**,功能更完整、支援簽名驗證。
  • 圖片建議使用 HTTPS、尺寸 300x300px 以內、大小 < 100KB,確保載入速度。
copyright © 萬盛學電腦網 all rights reserved