Page sharing in web-view of WeChat applet

Problems encountered

  • Since the entire applet is web-viewembedded, at this time, if you simply share the page, it will only lead to no matter web-viewwhich page is shared, and will enter the home page after clicking.

Solutions

  • The first is to open the page sharing function of the applet
wx.showShareMenu({
  withShareTicket: true, // 该参数在做分享到群内的统计的时候可以用到,单独分享给某个人是undefined,在小程序的load或者show的回调中可以拿到这个值
})
  • Then onShareAppMessagewrap the shared information in the middle. The callback is after clicking the share in the upper right corner, but the information has not been sent out. A callback is performed before. An object containing three parameters from, dataset and webViewUrl is passed in. Its return value is the corresponding shared information. At this time, after we get the url in the corresponding webview, we can do some operations we need.
  onShareAppMessage(options) {
    console.log(options);
    const { webViewUrl } = options;
    const i = webViewUrl.indexOf('?');
    let search = '',
      url = webViewUrl;
    if(i !== -1) {
      url = webViewUrl.slice(0, i);
      search = `${webViewUrl.slice(i + 1)}`;
    }
    const shareObj = {
      title: "分享的标题",        // 默认是小程序的名称(可以写slogan等)
      path: `/pages/index?url=${url}${search ? '&' : ''}${search}`,        // 默认是当前页面,必须是以‘/’开头的完整路径,通过拼接的方式,把需要分享的web-view的url以及参数拼接进去,然后在该`web-view`的页面中去做参数判断,一旦传入了对应的url和参数,就进入对应的url并携带对应的参数
      // imageUrl: '',     //自定义图片路径,可以是本地文件路径、代码包文件路径或者网络图片路径,支持PNG及JPG,不传入 imageUrl 则使用默认截图。显示图片长宽比是 5:4
      success: function (res) {
        // 转发成功之后的回调
        if (res.errMsg == 'shareAppMessage:ok') {
        }
      },
      fail: function () {
        // 转发失败之后的回调
        if (res.errMsg == 'shareAppMessage:fail cancel') {
          // 用户取消转发
        } else if (res.errMsg == 'shareAppMessage:fail') {
          // 转发失败,其中 detail message 为详细失败信息
        }
      },
      complete: function () {
        // 转发结束之后的回调(转发成不成功都会执行)
      }
    }
    // 来自页面内的按钮的转发
    if (options.from == 'button') {
      var data= options.target.dataset;
      console.log(data.name);     // shareBtn
      // 此处可以修改 shareObj 中的内容
      // shareObj.path = '/pages/index' + data.name;
    }
    // 返回shareObj
    return shareObj;
  }

There are still problems

  • After sharing in this way, you can indeed enter the corresponding url after entering, but there will be a problem that you cannot return to the homepage of the applet. Because there is only one web-view for the entire applet, all page switching is performed under a native page, so if you need to roll back, it is best to add a web-view page to use special processing to share the link to.

Guess you like

Origin www.cnblogs.com/aloneMing/p/12739661.html