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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM