小程序全局设置分享封面

微信小程序每个页面都可以在onShareAppMessage中设置分享内容,如果想要全局设置成一样的分享内容如何设置呢?

在app.js中新增以下方法:

App({
  onLaunch: function () {
    this.overShare()
  },
  //重写分享方法
  overShare: function () {
    //监听路由切换
    //间接实现全局设置分享内容
    wx.onAppRoute(function (res) {
      //获取加载的页面
      let pages = getCurrentPages(),
        //获取当前页面的对象
        view = pages[pages.length - 1],
        data;
      if (view) {
        data = view.data;
        // console.log('是否重写分享方法', data.isOverShare);
        if (!data.isOverShare) {
          data.isOverShare = true;
          view.onShareAppMessage = function () {
            //你的分享配置
            return {
              title: '学事通升学汇',
              path: '/pages/index/index',
              imageUrl: 'https://proxy.shunzhi.net:51315/mp_share.png',
            };
          }
        }
      }
    })
  }
})

然后在onLaunch中调用即可。

转载自:https://www.cnblogs.com/mlzs/p/10894777.html