webview通过uni.postMessage实现JSBridge通讯

发布于 2024-02-29  205 次阅读


H5向uni中发消息

h5全局引用

<script type="text/javascript" src="https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.1.js"></script>  

  uni.postMessage({ data:"data:"+data+"type:"+type, }); // 发送数据
  uni.switchTab({
    url: '/pages/index/index'
  }); // 需要路由跳转的页面

uni中采用

<web-view src="http://192.168.221.34:5173/" @message="handleMessage"></web-view>

handleMessage(e){
                console.log(4444444444444444)
                uni.showToast({
                    title:String(e.detail.data),
                    duration:1500
                });
            },

uni向webview中发送消息

uni中

this.currentWebview = this.$scope.$getAppWebview().children()[0];
            // const  _funName = ;
            this.currentWebview.evalJS(`${'msgFromUniapp'}(${JSON.stringify(123465)})`)

H5中

  window.msgFromUniapp= function(arg:any) {
  //arg.msg  是你传的值!!!!!!
  console.log(JSON.parse(arg));

一沙一世界,一花一天堂。君掌盛无边,刹那成永恒。