使用框架:Vue.js、微信JS-SDK、HTML5+(HBuilder)
兩種場景:微信生態右上角自定義分享、APP分享到微信
前提
在開發中,採用了HBuilder的打包功能,把vue的項目打包成了 webApp,在manifest.json配置相應SDK就能使用HTML5+提供的封裝的功能
以下代碼均在js文件中實現,.vue文件無法使用
1’ 獲取分享的服務列表
const updateSerivces = () => {
if (!window.plus) {
return false;
}
plus.share.getServices(function(s) {
shares = {};
for (const i in s) {
const t = s[i];
shares[t.id] = t;
}
sweixin = shares['weixin'];
}, function(e) {
console.log(`獲取分享服務列表失敗:${e.message}`);
});
};
2’ 分享基礎配置
const share = (srv, msg, button) => {
console.log('分享操作!');
if (!srv) {
console.log('無效的分享服務!');
return;
}
button && (msg.extra = button.extra);
// 發送分享
if (srv.authenticated) {
console.log('---已授權---');
doShare(srv, msg);
} else {
console.log('---未授權---');
srv.authorize(function() {
doShare(srv, msg);
}, function(e) {
console.log(`認證授權失敗:${JSON.stringify(e)}`);
});
}
}
3’ 發送分享
const doShare = (srv, msg) => {
console.log(JSON.stringify(msg));
srv.send(msg, function() {
console.log(`分享到"${srv.description}"成功!`);
}, function(e) {
console.log(`分享到"${srv.description}"失敗: ${JSON.stringify(e)}`);
});
};
4’ 分享網頁
const shareWeb = (sharemsg) => {
if (!window.plus) {
return false;
}
const msg = {
type: 'web',
thumbs: ['/static/logo.png'],
href: sharemsg.href,
title: sharemsg.title,
content: sharemsg.content,
};
console.log('sweixin:', JSON.stringify(sweixin));
sweixin ? plus.nativeUI.actionSheet({
title: '分享網頁到微信',
cancel: '取消',
buttons: buttons
}, function(e) {
(e.index > 0) && share(sweixin, msg, buttons[e.index - 1]);
}) : plus.nativeUI.alert('當前環境不支持微信分享操作!');
}
5’ 分享圖片
const shareImage = (sharemsg) => {
if (!window.plus) {
return false;
}
const msg = {
type:'image',
};
msg.pictures=[sharemsg.url];
sweixin?plus.nativeUI.actionSheet({
title:'分享二維碼到微信',
cancel:'取消',
buttons:buttons
}, function(e){
(e.index > 0) && share(sweixin, msg, buttons[e.index-1]);
}) : plus.nativeUI.alert('當前環境不支持微信分享操作!');
}