引言:
我們經常在做微信H5的過程中需要自定義分享網頁,這個如何實現呢?請看如下的封裝的ES6類及使用說明!
/** * @jssdk js對象,包括appId,timestamp,nonceStr,signature,后台請求過來。 * 以上4個參數,需要后台在公眾號相關平台進行配置,然后得出!前端頁面必須放在服務號配置的域名下面才可以保證成功! * options js對象為你自定義要分享的一些參數。 * 用法: * 1、引入weixinShare.js * 2、var weixinShare = new weixinShare(jssdk, options); * 3、默認加載頁面時,調用weixinShare.beforeShareJs,這里必須的! * 4、如果點擊分享朋友,則調用weixinShare.shareFriends * 5、如果點擊分享朋友圈,則調用weixinShare.shareCircleFriends * 備注:通過右上角的分享按鈕,則不需要進行點擊事件觸發。 */ class weixinShare { constructor(jssdk, options) { this.jssdk = jssdk; this.options = options; } beforeShareJs() { var that = this; wx.config({ debug: false,//是否開啟調試功能,這里關閉! appId: that.jssdk.appId,//appid timestamp: parseInt(that.jssdk.timestamp), //時間戳 nonceStr: that.jssdk.nonceStr, //生成簽名的隨機字符串 signature: that.jssdk.signature,//簽名 jsApiList: [ "onMenuShareTimeline", "onMenuShareAppMessage" ] }); } defaultOptions() { var defaults = { title: "分享的標題", desc: "分享的描述", link: location.href, //分享頁面地址,不能為空,這里可以傳遞參數!!!!!!! imgUrl: 'https://tup.iheima.com/sport.png', //分享是封面圖片,不能為空 success: function () { }, //分享成功觸發 cancel: function () { } //分享取消觸發,需要時可以調用 } // 合並對象,后面的替代前面的! return Object.assign({}, defaults, this.options); } shareCircleFriends() { var thatopts = this.defaultOptions(); wx.onMenuShareTimeline({ title: thatopts.title, // 分享標題 desc: thatopts.desc, // 分享描述 link: thatopts.link, // 分享鏈接 imgUrl: thatopts.imgUrl, // 分享圖標 success: function () { // alert("成功"); }, cancel: function () { // alert("失敗"); } }); } shareFriends() { var thatopts = this.defaultOptions(); wx.onMenuShareAppMessage({ title: thatopts.title, // 分享標題 desc: thatopts.desc, // 分享描述 link: thatopts.link, // 分享鏈接 imgUrl: thatopts.imgUrl, // 分享圖標 success: function () { // alert("成功"); }, cancel: function () { // alert("失敗") } }); } }