0%

Interaction Between H5 and Native

When interacting with native applications, we usually cannot see the data returned or printed by the native side in our local environment. In this case, we need to use a debugging tool. A very useful tool is vConsole, which allows us to clearly view network requests, console logs, and other information. It is similar to the browser’s DevTools (F12 console). Below is how to integrate it:

H5 Mobile Debugging Tool (vConsole for Mobile)

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

If you want to interact with the native side, you also need to use window. There are two scenarios: sending data and receiving data. Different approaches are used for different cases.

Case 1: Sending Data to the Native App

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) {
// Defined on iOS side
window.webkit.messageHandlers.getUserInfo.postMessage(null);
} else {
// Defined on Android side
feedback.getUserInfo();
}

if (window.webkit != undefined) {
window.webkit.messageHandlers.feedback.postMessage({
title: "Test share title",
content: "Test share content",
url: "https://github.com/maying1992",
});
} else {
// try {
// result = feedback.getUserInfo();
// } catch(err){
// }
feedback.postMessage();
}

Case 2: Receiving Data from the Native 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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
created() {
// Attach method to window
window.setUserInfo = this.setUserInfo;
},

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

if (isiOS) {

this.queryParams = result.userInfo.token;

// Handle inconsistent values from native side
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");

return localStorage.getItem("lang");
}

When You Need to Redirect to the App via a Button

You can directly use an <a> tag with the href attribute to trigger the app, provided that the native application has defined a custom scheme such as:

1
myapp://***

This works similarly to how Instagram handles H5-to-app redirection using a scheme like:

1
instagram://**

If the redirect does not work, it usually means the native app does not support the corresponding URL scheme.

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