无题

微信小程序页面实现分享功能

微信小程序实现页面的分享功能有两种实现方式::

  1. 监听用户点击页面内转发按钮(button 组件 open-type="share"),并自定义转发内容。
  2. 使用onShareAppMessage实现页面的分享功能,完整的文档可前往小程序文档中心查看onShareAppMessage

一.使用自定义的分享方式(用户点击页面内的按钮进行分享):

在需要分享的页面中添加一个按钮button:

属性为 open-type="share"

在微信小程序的页面的js文件中添加一个函数:onShareAppMessage(Object object)

二.使用默认的分享方式

在微信小程序的页面的js文件中添加一个函数:onShareAppMessage(Object object)

相较于上面的少了添加button按钮

代码展示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
Page({
data: {
activity_infor: {
id: 520,
name: "广州大学实验室开放日",
image: "/assets/share-banner.jpg"
}
},

onShareAppMessage(res) {
console.log('分享来源:', res.from); // button 或 menu

if (res.from === 'button') {
console.log('分享按钮元素:', res.target);
}

const { id, name, image } = this.data.activity_infor;

// 使用 promise 异步设置分享内容(模拟异步请求)
const promise = new Promise(resolve => {
setTimeout(() => {
resolve({
title: `【热门活动】${name}`,
path: `/pages/activity-detail/activity-detail?id=${id}`,
imageUrl: image
});
}, 1000);
});

return {
title: `【热门活动】${name}`,
path: `/pages/activity-detail/activity-detail?id=${id}`,
imageUrl: image,
promise
};
}
});
字段说明
title分享卡片显示的标题
path小程序跳转路径(必须以 / 开头)
imageUrl分享卡片封面图(支持本地/网络)
promise异步处理分享内容,可用于接口动态配置

三.分享到朋友圈

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Page({
data: {
activity_infor: {
id: 123,
name: "广州大学实验室开放日"
}
},

// 分享到朋友圈
onShareTimeline() {
const { id, name } = this.data.activity_infor
return {
title: `快来参加:${name}`, // 分享标题
query: `id=${id}`, // 携带参数,不能包含页面路径
imageUrl: '/assets/share-cover.jpg' // 自定义图片路径,可以是本地文件或者网络图片
}
}
})