前言

分享是小程序裂变的一个非常重要的渠道,但是微信小程序每个页面都要写 onShareAppMessage 来配置分享内容(标题、图片、参数等),页面多的时候写起来重复性太高,所以想出能不能直接全局配置分享,统一接管。

onShareAppMessage

微信小程序开发文档·onShareAppMessage

wxapp-share.png

由于各个小程序开发框架写起来都不太一样,所以就改成了原生的代码

onShareAppMessage: function () {
  return {
    title: '转发标题',
    path: '转发路径',
    imageUrl: '转发卡片图片'
  }
},

查阅文档发现,onShareAppMessage 是一个事件处理函数,用户通过点击小程序的右上角...触发,或者通过页面上的 <button open-type='share'> 来触发,所以只需要在小程序启动的时候重写一下 onShareAppMessage 就可以了。

onLaunch: function (){
    wx.onAppRoute(() => {
        console.log(getCurrentPages());

        const pages = getCurrentPages();
        const current_page = pages[pages.length-1];
        current_page.onShareAppMessage = () => {
          return {
            title: '',
            path: current_page.route,
            imageUrl: '转发卡片图片'
          }
        }
    });
}