封装的经过微信JS-SDK实现自定义分享到朋友圈或者朋友的ES6类!

引言:前端

咱们常常在作微信H5的过程当中须要自定义分享网页,这个如何实现呢?请看以下的封装的ES6类及使用说明!微信

/**
 * @jssdk js对象,包括appId,timestamp,nonceStr,signature,后台请求过来。
 * 以上4个参数,须要后台在公众号相关平台进行配置,而后得出!前端页面必须放在服务号配置的域名下面才能够保证成功!
 * options js对象为你自定义要分享的一些参数。
 * 用法:
 *      一、引入weixinShare.js
 *      二、var weixinShare = new weixinShare(jssdk, options);
 *      三、默认加载页面时,调用weixinShare.beforeShareJs,这里必须的!
 *      四、若是点击分享朋友,则调用weixinShare.shareFriends
 *      五、若是点击分享朋友圈,则调用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("失败")
            }
        });
    }
}
相关文章
相关标签/搜索