Small program embedded web page jump sharing implementation

For the sharing function, anyone who has done small program development is familiar with it. Just add an event such as onShareAppMessage to the js of the page that needs to be shared.

Define the onShareAppMessage function in Page to set the forwarding information of the page.

Only if this event handler is defined, the "Forward" button will be displayed in the upper right menu

Called when the user clicks the forward button

This event needs to return an Object for custom forwarding content

The sample code is as follows:

Page({
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
    }
    return {
      title: '自定义转发标题',
      path: '/page/user?id=123',
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  }
})

When there is a web-view, there will be an additional webViewUrl in the res parameter of the onShareAppMessage callback function, which can obtain the URL address of the current page.

Page({
  onShareAppMessage(options) {
    console.log(options.webViewUrl)
  }
})

It is necessary to realize the function of multiple jump sharing in the embedded web page, which requires you to find a way. The status cannot be maintained during the sharing of the applet, this has to record the path of the webpage when sharing. In fact, anyone with a little development experience can think of this method, that is, use? Record it after the url, so when other users open the forwarding applet, take out the parameters and replace the src in the web-view with this one. Not much to say, go directly to the code.

Page({
    web_url:"",
    data: {
      title: '测试内嵌分享',
      url:'',
      web_src:''
    },
    onShareAppMessage(options) {
      var that = this
      var return_url = options.webViewUrl
      var path = '/page/test/test?return_url=' + encodeURIComponent(return_url)
      console.log(path, options)
      return {
        title: that.data.title,
        path: path,
        success: function (res) {
          that.web_url = return_url
          // 转发成功
          wx.showToast({
            title: "转发成功",
            icon: 'success',
            duration: 2000
          })
        },
        fail: function (res) {
          // 转发失败
        }
      }
    },
    onLoad: function () {
        var pages=getCurrentPages();
        var currentPage = pages[pages.length - 1]; 
        var web_src = decodeURIComponent(currentPage.options.return_url ||
        encodeURIComponent("你的内嵌网页网址"))
        this.web_url = web_src
        this.setData({
          web_src: web_src
        }, function () {

        });

    }
})

Written here, and finally done.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325282339&siteId=291194637