早期微信內頁面使用 WeixinJSBridge 私有介面,現已全面遷移至官方 微信 JSSDK(wx.config + wx.ready)。本文整理常用場景對應的新舊寫法,建議新專案直接使用 JSSDK。
wx.ready(() => {
document.querySelectorAll('.gallery img').forEach(img => {
img.addEventListener('click', () => {
wx.previewImage({
current: img.src, // 當前顯示圖片連結
urls: [...document.querySelectorAll('.gallery img')].map(i => i.src) // 所有圖片連結
});
});
});
});
// JSSDK
wx.closeWindow();
// 舊版(僅供參考)
WeixinJSBridge.invoke('closeWindow', {}, (res) => { /* ... */ });
需先完成 wx.config 驗證,並在 wx.ready 中註冊:
wx.ready(() => {
const shareData = {
title: '自定義標題',
desc: '自定義描述',
link: location.href,
imgUrl: 'https://example.com/share-icon.png'
};
// 分享給朋友
wx.updateAppMessageShareData(shareData);
wx.onMenuShareAppMessage(shareData);
// 分享到朋友圈
wx.updateTimelineShareData(shareData);
wx.onMenuShareTimeline(shareData);
});
注意:wx.onMenuShareAppMessage 等舊版介面已標記棄用,新專案請使用 updateAppMessageShareData / updateTimelineShareData。
wx.ready(() => {
wx.hideOptionMenu(); // 隱藏右上角「...」選單
wx.hideToolbar(); // 隱藏底部工具列(iOS 已棄用,Android 部分版本仍生效)
});
wx.getNetworkType({
success: (res) => {
console.log(res.networkType); // wifi / 2g / 3g / 4g / 5g / unknown
}
});
wx.ready(() => {
wx.hideMenuItems({ menuList: ['menuItem:share:appMessage', 'menuItem:share:timeline'] });
});
function isWeixin() {
const ua = navigator.userAgent.toLowerCase();
return ua.match(/MicroMessenger/i) === 'micromessenger';
}
// 或使用 JSSDK ready 狀態
wx.ready(() => { /* 在微信中 */ });
wx.error(() => { /* 不在微信或配置失敗 */ });
// 掃碼
wx.scanQRCode({
needResult: 1,
scanType: ['qrCode', 'barCode'],
success: (res) => { console.log(res.resultStr); }
});
// 選圖/拍照
wx.chooseImage({
count: 9,
sizeType: ['original', 'compressed'],
sourceType: ['album', 'camera'],
success: (res) => { console.log(res.localIds); } // 返回本地 ID,需上傳至微信服務器獲取 serverId
});
// 上傳圖片
wx.uploadImage({
localId: localIds[0],
isShowProgressTips: 1,
success: (res) => { console.log(res.serverId); }
});
url、noncestr、timestamp、jsapi_ticket 計算 signature。wx.config({ debug: false, appId, timestamp, nonceStr, signature, jsApiList: [...] })。updateAppMessageShareData,舊版 onMenuShareAppMessage 失效。chooseImage 回傳 localId 必須先 uploadImage 取得 serverId,再傳給後端下載。