小程序内嵌网页跳转分享实现

对于分享功能,作太小程序开发的都不会陌生,在须要被分享的页面js中加入onShareAppMessage这样一个事件便可。web

在 Page 中定义 onShareAppMessage 函数,设置该页面的转发信息。小程序

只有定义了此事件处理函数,右上角菜单才会显示 “转发” 按钮函数

用户点击转发按钮的时候会调用测试

此事件须要 return 一个 Object,用于自定义转发内容this

示例代码以下:

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) {
        // 转发失败
      }
    }
  }
})

当存在web-view时,onShareAppMessage回调函数参数res中还会多一个webViewUrl,能够获取当前页面的URL地址。url

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

须要实现内嵌网页内屡次跳转分享的功能,这就须要本身想办法了。在小程序分享中又不能保持状态,这个得去记录分享时网页的路径。其实有点开发经验的都能想到这个办法,那就是使用?在url后记录下来,这样在其它用户打开转发小程序的时候,取出其中的参数,将web-view中的src替换成这个就好了。话很少说,直接上代码。spa

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 () {

        });

    }
})

写到这里,终于大功告成了。code

相关文章
相关标签/搜索