核心:通过WebViewJavascriptBridge建立一个桥梁
github仓库链接: https://github.com/marcuswestin/WebViewJavascriptBridge
function setupWebViewJavascriptBridge(callback){
if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
if (window.WVJBCallbacks) { return window.WVJBCallbacks.push(callback); }
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'https://__bridge_loaded__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function() { document.documentElement.removeChild(WVJBIframe) }, 0)
}
用法:例如检测是否安装某款app
function checkAppPayIsInstalled(payMethod){
let plat = getAppPlat()
if(plat === 'ios'){
return new Promise((resolve,reject)=> {
setupWebViewJavascriptBridge(bridge => {
if (payMethod === 'weixin') {
//检测微信是否安装
bridge.callHandler('isWXAppInstalled', '', responseData => {
responseData?resolve(true):resolve(false)
})
} else {
//检测支付宝是否安装
bridge.callHandler('isAliPayAppInstalled', '', responseData => {
responseData?resolve(true):resolve(false)
})
}
})
})
}else {
if(window.nativeBridge){
return new Promise((resolve,reject)=> {
if (payMethod === 'weixin') {
//检测微信是否安装
let result = window.nativeBridge.isWXAppInstalled();
result?resolve(true):resolve(false)
} else {
//检测支付宝是否安装
let result = window.nativeBridge.isAliPayAppInstalled();
result?resolve(true):resolve(false)
}
})
}
}
}