Implementation of jump and share of web page embedded in applet

For sharing function, anyone who has done applet development will not be unfamiliar. Add an event like onshare appmessage to the page js to be shared.

Define the onshare appmessage function in Page to set the forwarding information of the Page.

Only when this event handler is defined will the forward button be displayed in the upper right menu

When the user clicks the forward button, it will call

This event needs to return an Object to customize the forwarding content

The sample code is as follows:

Page({
  onShareAppMessage: function (res) {
    if (res.from === 'button') {
      // From in page forward button
      console.log(res.target)
    }
    return {
      title: 'Custom forwarding title',
      path: '/page/user?id=123',
      success: function(res) {
        // Forwarding success
      },
      fail: function(res) {
        // Forwarding failed
      }
    }
  }
})

When there is a web view, there will be another webViewUrl in the onshareapmessage callback parameter res to get the URL address of the current page.

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

We need to realize the function of multiple jump and share in the embedded web page, which requires us to find a way. You can't keep the status in applet sharing. You have to record the path of the web page when sharing. In fact, anyone with some development experience can think of this method, that is, use? Record it after the url, so that when other users open the forwarding applet, take out the parameters and replace the src in the web view with this one. Don't talk much, just go to the code.

Page({
    web_url:"",
    data: {
      title: 'Test embedded sharing',
      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
          // Forwarding success
          wx.showToast({
            title: "Forwarding success",
            icon: 'success',
            duration: 2000
          })
        },
        fail: function (res) {
          // Forwarding failed
        }
      }
    },
    onLoad: function () {
        var pages=getCurrentPages();
        var currentPage = pages[pages.length - 1]; 
        var web_src = decodeURIComponent(currentPage.options.return_url ||
        encodeURIComponent("Your embedded web address"))
        this.web_url = web_src
        this.setData({
          web_src: web_src
        }, function () {

        });

    }
})

Writing here, it's finally done.

Posted on Fri, 20 Mar 2020 10:05:05 -0700 by juliston