/** * WX_SHARE v1.0.3 * Desc: 使用微信JS-SDK(手浪接口提供动态token)实现自定义微信分享(仅在微信内,非微信浏览器do nothing) * Modified: 2017/8/14 * Email: minhua@staff.sina.com.cn */ var WX_SHARE = (function () { var isInited = false; //工具函数 function _getScript(src, onLoad) { var s = document.createElement('script'); s.charset = 'utf-8'; s.type = 'text/javascript'; s.src = src; document.getElementsByTagName('body')[0].appendChild(s); if ('onreadystatechange' in s) { s.onreadystatechange = function () { if (s.readyState.toLowerCase() === 'loaded') { onLoad && onLoad(); } }; } else { s.onload = function () { onLoad && onLoad(); } } } function _merge(tar, src) { var val; for (var key in src) { if (src.hasOwnProperty(key)) { //''或null或undefined使用默认,不覆盖 val = src[key]; if (val == null || val === '') continue; tar[key] = val; } } return tar; } function init(shareCfg) { if (isInited) return; if (!navigator.userAgent.match(/MicroMessenger/gi)) return; isInited = true; _getScript(document.location.protocol+'//res.wx.qq.com/open/js/jweixin-1.0.0.js', function () { var _desc = document.querySelector('meta[name=description]'); var _poster = document.querySelector('img[name=weixin_poster]'); var _shareCfg = { title: document.title, desc: (_desc && _desc.content) || document.title, imgUrl: (_poster && _poster.src) || document.location.protocol+'//n.sinaimg.cn/finance/6adc145b/20170719/wx_poster_finance.png', type: '', dataUrl: '', success: function () { }, cancel: function () { } }; shareCfg && _merge(_shareCfg, shareCfg); _shareCfg.link = location.href.split('#')[0]; window.setWxCfg = function (res) { if (Number(res.status) === 0) { var data = res.data; wx.config({ debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。 appId: data.appid, // 必填,公众号的唯一标识 timestamp: data.time, // 必填,生成签名的时间戳 nonceStr: data.nonceStr,// 必填,生成签名的随机串 signature: data.signature,// 必填,签名 jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline'] // 必填,需要使用的JS接口列表 }); wx.ready(function () { wx.onMenuShareAppMessage(_shareCfg); wx.onMenuShareTimeline(_shareCfg); WX_SHARE.update = function (cfg) { _merge(_shareCfg, cfg); wx.onMenuShareAppMessage(_shareCfg); wx.onMenuShareTimeline(_shareCfg); } }); wx.error(function (res) { console.log('wx error: ', res); }); } }; _getScript(document.location.protocol + '//mp.sina.cn/aj/wechat/gettoken?url=' + encodeURIComponent(location.href.split('#')[0]) + '&callback=setWxCfg'); }); } if (typeof window._wxShareConfig === 'object') { init(window._wxShareConfig); } //export return { update: null, init: init }; })();