// 这里是交互申明,在h5端导入
//
function setupWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
callback(WebViewJavascriptBridge);
}else {
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function() {
callback(WebViewJavascriptBridge)
},
false
);
}
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)
}
• 这里iOS 和安卓端存在差异
//
setupWebViewJavascriptBridge(function(bridge) {
var u = navigator.userAgent;
var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
if(isAndroid){
bridge.init(function(message, responseCallback) {
});
}
// 这里是移动端和h5端的数据互传,特别注意方法名一致
setupWebViewJavascriptBridge(function(bridge) {
/*<!--处理 oc 调用 js -->*/
bridge.registerHandler('registerAction', function(data, responseCallback) {
//处理oc给的传参
alert('oc请求js 传值参数是:'+data)
var responseData = { 'result':'handle success' }
//处理完,回调传值给oc
responseCallback(responseData)
})
var callbackButton = document.getElementById('buttons').appendChild(document.createElement('button'))
callbackButton.innerHTML = '点击我,我会调用oc的方法'
callbackButton.onclick = function(e) {
e.preventDefault()
/*<!--处理 js 调用 oc -->*/
bridge.callHandler(‘closepage’, {‘action’:’close’}, function(response) {
//处理oc过来的回调
alert('收到oc过来的回调:'+response)
})
}
})