微信小程序接入H5页面备忘

liren123.cn

1.微信小程序设置

index.wxml

<view class="container">

<web-view src="{{webUrl}}" bindmessage="msgHandler"></web-view>   //通过web-view绑定现有的H5网站页面

</view>

index.js

msgHandler: function (e) { //(h5像小程序传递参数)

    console.log(e.detail.data) //获取到来自也页面的数据

    var info = (e.detail.data)[e.detail.data.length-1]

    this.setData({

      value: info.value   

    });

    //console.log('msgHandler:value: info.value:' + this.data.value)

    this.setData({

      title: info.title

    });

    //console.log('msgHandler:value: info.title:' + this.data.title)

  },

onLoad: function (options){

    var webUrl = '';

    if (options.value) {//获取转发过来的参数

      webUrl =  options.value;

      console.log('onLoad:webUrl =  options.value'+webUrl)

    } else {

      webUrl = "https://liren123.cn";          

      console.log('onLoad:webUrl = "https://liren123.cn' + webUrl)

    }

    this.setData({

      webUrl: webUrl

    })

  }, 

//转发

  onShareAppMessage: function (options){   

    var that = this;

    //console.log('onShareAppMessage:data.title1=' + that.data.title);

    //console.log('onShareAppMessage:data.link1=' + that.data.value);

    return {

      title: that.data.title,

      path: '/pages/index/index?value=' + that.data.value,//小程序像h5传递参数

      success: function (res) { }

    }

  }

2.H5页面设置

<script type="text/javascript">

var ua = window.navigator.userAgent.toLowerCase();

  if (ua.match(/MicroMessenger/i) == 'micromessenger') {  //判断是不是微信环境

wx.miniProgram.getEnv(function (res) {

  if (res.miniprogram) {

    var info = {

      title: '测试',

      value: window.location.href, 

    };

    wx.miniProgram.postMessage({

      data: info

    });

  } else {

//如果不是...可以忽略,或者去掉这部分

window.location.href ='www.baidu.com'

  }

})

  } else {

//如果不是...可以忽略,或者去掉这部分

window.location.href ='liren123.cn' 

  }

  </script>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。