Several common interaction methods of H5 embedded App mixed development

Method 1: Use the conventional UA method.

1. Determine whether it is Android or ios

var u = navigator.userAgent;
var isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android
var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios

2. Pass parameters to the client (Android, ios) and call its method

if (isAndroid) {
    
    
    window.android.客户端方法名(JSON.stringify({
    
     // 给安卓传参
       planId: scoped.tasks[index].planId,
       type: 'video',
   }));
} else {
    
    
    window.webkit.messageHandlers.客户端方法名.postMessage({
    
     // 给ios 传参
       planId: scoped.tasks[index].planId,
       type: 'video',
    }); 
} 

3. The client calls the H5 method and passes parameters

let _this = this
// 获取客户端的传参,通过方法获取客户端传递的token等信息;
// 将setTokenToJs方法名暴露在windows下,客户端给调用setTokenToJs方法并传参
window["setTokenToJs"] = result => {
    
    
	_this.getUserInfo(result);
};

Method 2: Using jsBridge.

1. Encapsulate a jsbridge.js file.
You need to communicate with the client about certain fields in ua to determine whether it is Android or ios.

//App ios终端
let bridge = {
    
    
	isIosApp() {
    
    
	   	let isiOS = navigator.userAgent.indexOf('iOS_xxxx') > -1;
	   	return isiOS
	},
	//App Android终端
	isAndroidApp() {
    
    
		let isAndroid = navigator.userAgent.indexOf('android_xxx') > -1;
		return isAndroid
	}
}
export default bridge

2. Call jsbridge to realize interaction

import jsbridge from "@/utils/jsbridge/jsbridge.js";
if (jsbridge.isAndroidApp()) {
    
    // 安卓
	window.appBridge.客户端方法名(JSON.stringify(data))
} else if (jsbridge.isIosLptApp()) {
    
    // ios
	window.webkit.messageHandlers.客户端方法名.postMessage(JSON.stringify({
    
    }));
} else {
    
    
	return;
}

3. The client calls the H5 method and passes parameters

let _this = this
// 获取客户端的传参,通过方法获取客户端传递的token等信息;
// 将setTokenToJs方法名暴露在windows下,客户端给调用setTokenToJs方法并传参
window["setTokenToJs"] = result => {
    
    
	_this.getUserInfo(result);
};

Guess you like

Origin blog.csdn.net/weixin_44684357/article/details/132213241