uni-app中app和webview的h5通信简单步骤

前情提要:

1、使用webview的页面需要是nvue,否则没有 sWebViewRef.value.evalJS() 方法;

2、需要自己安装npm i y_uniwebview,官方的 引入https://js.cdn.aliyun.dcloud.net.cn/dev/uni-app/uni.webview.1.5.2.js脚本存在冲突,会报错

第一步,在 h5 项目中安装y_uniwebview插件

1
2
安装: npm i y_uniwebview
引入: import y_uni from "y_uniwebview"

第二步,h5 代码,接收app信息和向app发送信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<button>向app发送信息</button>
     
      接收到app信息:{{ appMsg }}
     
 
import y_uni from "y_uniwebview"
import { ref } from 'vue';
 
const appMsg = ref('');
 
// app信息触发方法
window.appCallBack = (val) => {
  appMsg.value = val
  console.log('app发送过来的数据---', val)
}
 
let count = 0;
 
// 向app发送信息
function postMessage(type) {
  console.log('h5发送信息');
  // 发送信息
  y_uni.webView.postMessage({
    data: {
      msg: `h5信息 ${count++} 次`
    }
  });
}

第三步、app页面,接收h5信息和向h5发送信息

注意,这里需要用nvue,否则会没有 sWebViewRef.value.evalJS() 导致报错

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<button>
            向h5发送信息
        </button>
         
            接收到h5信息:{{h5Msg}}
        <br>
    import {computed, ref} from 'vue';
 
    const sWebViewRef = ref()
 
    const h5Msg = ref('');
 
    // 接收h5信息
    function handleMessage(event) {
        // 接收webview发送的消息
        h5Msg.value = event.detail.data[0].msg;
        console.log('收到 h5 消息: ' + h5Msg);
    }
     
    let count = 0;
 
    // 向 h5 发送信息
    function postMsg(msg) {
        console.log('app发送信息')
        sWebViewRef.value.evalJS(`appCallBack('app信息 ${count++} 次')`)
    }
 
    const webViewStyle = computed(() => {
        let width = 0;
        let height = 0;
        uni.getSystemInfo({
            // 获取当前设备的具体信息
            success: sysinfo => {
                width = sysinfo.windowWidth - 100;
                height = sysinfo.windowHeight - 100;
            }
        })
        return {
            width: width + 'px', height: height + 'px'
        }
    })

总结 

到此这篇关于uni-app中app和webview的h5通信的文章就介绍到这了,更多相关uni-app app和webview的h5通信内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章希望大家以后多多支持IT俱乐部!

本文收集自网络,不代表IT俱乐部立场,转载请注明出处。https://www.2it.club/navsub/js/14635.html
上一篇
下一篇
联系我们

联系我们

在线咨询: QQ交谈

邮箱: 1120393934@qq.com

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部