如何设置分享到微信朋友圈时链接的图片及标题

这个问题真的是困扰了我很久,为了记录一下,也为了帮助需要帮助的人,我在这分享一下自己的做法。

一、效果如下

在这里插入图片描述

二、如何调试

通常我们在电脑上想要模仿手机的功能是比较麻烦的,但是微信开发者工具给我们提供了一个非常好用的功能。

操作如下

1、我们打开开发者工具,然后选择公众号网页,在公众号网页里面直接输入本地的地址就可以模拟微信的分享等功能了,相关打印也可以在控制台的console看到,如下所示:
在这里插入图片描述
在这里插入图片描述

三、如何设置

相关代码如下(本人使用的是vue,其他的原理应该也是一样):

 mounted() {
    
    
    this.getWxSignature()
  },
  methods: {
    
    
    // 微信分享
    async getWxSignature() {
    
    
      const ua = window.navigator.userAgent.toLowerCase()
      if (ua.indexOf('micromessenger') === -1) return

      const weixinSign = await this.$axios.get('/shareSign', {
    
    
        params: {
    
     aoeu: 'aoeu', rawUrl: document.location.href },
      })

      if (weixinSign.data) {
    
    
        setTimeout(() => this.initWeixinShare(weixinSign.data), 1000)
      } else {
    
    
        console.log('weixin signature get failed!')
      }
    },
    initWeixinShare(weixinSign) {
    
    
      wx.config({
    
    
        appId: weixinSign.appId,
        timestamp: weixinSign.timestamp,
        nonceStr: weixinSign.nonceStr,
        signature: weixinSign.signature,
        jsApiList: ['checkJsApi', 'getLocation', 'onMenuShareTimeline', 'onMenuShareAppMessage'],
      })

      const shareData = {
    
    
        title: '中国仓库数据平台',
        imgUrl: 'http://outter-common.toodc.cn/bigdata-icon.jpg',//一定要注意,此处的imgUrl最好使用网络图片,不要写成本地,不然很可能没有效果,图片显示不出来
        desc:
          '覆盖全国113个城市,土地项目租约全链路跟踪,一手数据对接,专业团队七年沉淀,最新开发商资讯',
      }

      wx.ready(() => {
    
    
        wx.onMenuShareTimeline({
    
    
          title: shareData.title, // 分享标题
          link: shareData.link || document.location.href, // 分享链接
          imgUrl: shareData.imgUrl, // 分享图标
          success:
            shareData.shareTimelineSuccess ||
            function() {
    
    
              console.log('share success')
            },
        })

        wx.onMenuShareAppMessage({
    
    
          title: shareData.title, // 分享标题
          desc: shareData.desc, // 分享描述
          link: shareData.link || document.location.href, // 分享链接
          imgUrl: shareData.imgUrl, // 分享图标
          success: function() {
    
    
            console.log('share success')
          },
        })
      })

      wx.error(function(res) {
    
    
        console.log(res.errMsg)
      })
    },
  },
}

猜你喜欢

转载自blog.csdn.net/m0_46412825/article/details/123838854