使用 wx.miniProgram.postMessage 传递网站数据来分享网站程序页面

在小程序里使用web-view组件,在对小程序点击顶部分享按钮分享时,分享的内容为当前页面的内容,须要使用wx.miniProgram.postMessage来进行处理javascript

H5页面代码html

created() {
    this.$store
      .dispatch({
        type: "user/saveCurrentUrl",
        data: {
          current_url: window.location.pathname + window.location.search,
          page_type: "3"
        }
      })
      .then(res => {
        if (res.code == 1) {
          window.wx.miniProgram.postMessage({
            data: {
              title: res.data.title, // 标题
              desc: "", // 描述
              imgUrl: "", // 图片
              link: res.data.url, // 连接
              unique_mark: res.data.unique_mark
            }
          });
        }
      });
    let id = this.$route.params.id;
    let activityId = this.$route.query.activityId;
    this.getActivityProductDetail(id, activityId);
  }

  小程序端代码java

<web-view src='{{weburl}}' bindmessage="getSharePage"></web-view>

  

  onShareAppMessage: function() {
    let _this = this;
    let title = "发现一件好物";
    if (app.globalData.shopname) {
      title = app.globalData.shopname;
    }
    console.log(this.data.sharePageModel);
    let path = "pages/index/index";
    if (this.data.sharePageModel) {
      path += "?share_openid=" + app.globalData.openid + "&unique_mark=" + this.data.sharePageModel.unique_mark;
      title = this.data.sharePageModel.title;
    }

    return {
      title: title,
      path: path,
      success: _suc => {
        wx.showToast({
          title: '分享成功',
        })
      },
      fail: _fail => {
        wx.showToast({
          title: '分享失败',
        })
      }
    };
  },
  getSharePage: function(e) {
    console.log("获取网页内容");
    console.log(e);
    if (e && e.detail && e.detail.data) {
      let len = e.detail.data.length;
      this.setData({
        sharePageModel: e.detail.data[len - 1]
      });
    }

  },

调试截图web

 

 注意点:wx.miniProgram.postMessage该方法的使用有条件,小程序分享、销毁等都会执行,H5页面每执行一次,会在小程序端记录一条数据(数组形式),我目前作的是用户分享时取的是数组下标最大的,可是也存在一个缺陷,当H5页面未设置分享参数,而用户点击了顶部分享操做,分享数据将取最后一条,目前还在处理中(每一个H5页面加上分享postMessage感受不现实),求招...小程序

转载于:https://www.cnblogs.com/WQ1992/p/11508540.html数组