uniapp使用web-view跳转vue单页面通信,互发消息

uniapp使用web-view跳转vue单页面通信,互发消息

1、背景:uniapp使用web-view跳转网页,互发消息,APP向h5发消息好处理,但是h5往APP发消息就很难,官方给的例子很简单,且基于传统js页面,并没有vue写的h5页面的例子,自己也是踩了一堆坑,现在分享我的处理过程,

首先,在vue的index,html文件引入web-view的插件

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

(1)、APP向h5传值,这个比较简单,直接上代码

(2)、vue做的h5向APP发消息

a、h5页面设置第一步

  1.  
    // 在使用到的页面 添加如下代码
  2.  
    mounted () {
  3.  
    this.$nextTick(()=>{
  4.  
    document.addEventListener('UniAppJSBridgeReady', function() {
  5.  
    // alert("jsbridge")
  6.  
    uni.getEnv(function(res) {
  7.  
    console.log('当前环境:' + JSON.stringify(res));
  8.  
    });
  9.  
    });
  10.  
    })
  11.  
    },

b、h5页面设置第二步

  1.  
    // function 调用uniapp的 方法
  2.  
    postMsg(){
  3.  
    console.log("调用uni.postMessage,开始发送")
  4.  
    uni.postMessage({
  5.  
    data: {
  6.  
    action: 'postMessage hh'
  7.  
    }
  8.  
    });
  9.  
    },

c、uniapp设置第三步

  1.  
    <template>
  2.  
    <view>
  3.  
    <web-view :src="url" @message="getMessage" @onPostMessage="getPostMessage"></web-view>
  4.  
    </view>
  5.  
    </template>
  6.  
     
  7.  
    <script>
  8.  
    export default {
  9.  
    data() {
  10.  
    return {
  11.  
    url: 'http://192.168.0.133:8031/#/recommend?id=1' // 你的地址
  12.  
    }
  13.  
    },
  14.  
    methods: {
  15.  
    getMessage(e) {
  16.  
    console.log("@message 接收成功")
  17.  
    uni.showModal({
  18.  
    content: JSON.stringify(e.detail),
  19.  
    // content: 'haha',
  20.  
    showCancel: false
  21.  
    })
  22.  
    },
  23.  
    getPostMessage(e) {
  24.  
    console.log("@onPostMessage 接收成功")
  25.  
    uni.showModal({
  26.  
    content: JSON.stringify(e.detail),
  27.  
    // content: 'haha',
  28.  
    showCancel: false
  29.  
    })
  30.  
    },
  31.  
    }
  32.  
    }
  33.  
    </script>
  34.  
     
  35.  
    <style>
  36.  
     
  37.  
    </style>

如下图所示


最终效果如下

2、相关文档

官方文档:https://uniapp.dcloud.io/component/web-view?id=web-view

参考文档:https://ask.dcloud.net.cn/article/id-35083__page-2

 
原文地址:https://www.cnblogs.com/xiondun/p/14581924.html