0%

H5与原生交互

H5手机端日志工具(vconsole手机端):

1
2
3
4
5
6
<script src="https://cdn.bootcdn.net/ajax/libs/vConsole/3.15.1/vconsole.min.js"></script>
<script>
// 初始化 vConsole
var vConsole = new VConsole();
console.log('vConsole is ready.');
</script>

第一种情况:传数据给原生端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
if (window.webkit != undefined) {
//这是ios端定义的
window.webkit.messageHandlers.getUserInfo.postMessage(null);
} else {
//这是android端定义的feedback
feedback.getUserInfo();
}

if (window.webkit != undefined) {
window.webkit.messageHandlers.feedback.postMessage({
title: "测试分享的标题",
content: "测试分享的内容",
url: "https://github.com/maying1992",
});
} else {
// try {
// result = feedback.getUserInfo();
// } catch(err){
// }
feedback.postMessage();
}

第二种情况:获取原生端的数据

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
created() {
//window挂载
window.setUserInfo = this.setUserInfo;
},

setUserInfo(param) {
const u = navigator.userAgent;
const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
const result = JSON.parse(param);
if (isiOS) {

this.queryParams = result.userInfo.token;

//兼容原生端那边传过来的不统一值
if (
result.userInfo.userId == undefined ||
result.userInfo.userId == 0
) {
this.usrIdd = 0;
} else {
this.usrIdd = result.userInfo.userId;
}

window.localStorage.setItem("lang", result.userInfo.language);

} else {
this.queryParams = result;
if (result.userId == undefined || result.userId == 0) {
this.usrIdd = 0;
} else {
this.usrIdd = result.userId;
}
window.localStorage.setItem("lang", result.language);

}
this.$i18n.locale = localStorage.getItem("lang");
// let data = {
// 'name' : 'xiaoming'
// };
return localStorage.getItem("lang");
}

当需要通过按钮跳转到app时:

直接用 a 标签的 href 跳转,前提是原生应用定义了 myapp://*** 作为触发特定功能的URL,可参考 Instagram 的 H5 跳转 app 的竞品例子,instagram://**
一般跳不过去就是原生端不支持。

-------------本文结束感谢您的阅读-------------