前言
因业务需要 某些页面需要使用appbridge配合原生做混合开发,废话不多说直接上代码
function isAndroid() {
var ua = navigator.userAgent,
_isAndroid = ua.indexOf('Android') > -1 || ua.indexOf('Linux') > -1;
return _isAndroid;
}
function isIOS() {
return !!navigator.userAgent.match(/(i[^;]+\;(U;)? CPU.+Mac OS X)/);
}
function isPad() {
return navigator.userAgent.toLowerCase().match(/iPad/i) == "ipad";
}
function isWinPad() {
return navigator.userAgent.indexOf("Windows NT") >= 0;
}
/**
* js-app桥接
* @param {Function} callback
*/
function connectWebViewJavascriptBridge(callback) {
if (window.WebViewJavascriptBridge) {
return callback(WebViewJavascriptBridge);
}
/*IOS或者ipad*/
if (isIOS() || isPad()) {
if (window.WVJBCallbacks) {
return window.WVJBCallbacks.push(callback);
}
window.WVJBCallbacks = [callback];
var WVJBIframe = document.createElement('iframe');
WVJBIframe.style.display = 'none';
WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
document.documentElement.appendChild(WVJBIframe);
setTimeout(function () {
document.documentElement.removeChild(WVJBIframe)
}, 0);
}
else {
console.log("Android");
document.addEventListener(
'WebViewJavascriptBridgeReady'
, function () {
callback(WebViewJavascriptBridge)
},
false
);
}
}
/**
* 调用app方法
* @param {String} handlerName 对应app方法名
* @param {Object} options 参数对象
* @param {Function} callback 调用成功回调
*/
function callHandler(handlerName, options, callback) {
console.log('callHandler:' + handlerName, options);
connectWebViewJavascriptBridge(function (bridge) {
bridge.callHandler(handlerName, options, function (result) {
if (isIOS() || isPad()) {
result = result || {};
}
else {
result = result || "{}";
result = JSON.parse(result) || {};
}
result['extras'] = options['extras'];
console.log('callback:' + handlerName, result);
callback && callback(result);
});
});
}
AppBridge.registerHandler = registerHandler;
/**
* 提供给app调用的方法
* @param {String} handlerName 方法名
*/
function registerHandler(handlerName, pageCallback) {
console.log('registerHandler:' + handlerName);
connectWebViewJavascriptBridge(function (bridge) {
bridge.registerHandler(handlerName, function (data, appCallback) {
if (isIOS() || isPad()) {
data = data || {};
}
else {
data = data || "{}";
data = JSON.parse(data) || {};
}
console.log('callback:' + handlerName, data);
if (pageCallback) {
pageCallback(data, appCallback);
}
else {
appCallback && appCallback(data);
}
});
});
}
AppBridge.isBridge = false;
// #ifdef H5
/*初始化js-bridge*/
connectWebViewJavascriptBridge(function (bridge) {
AppBridge.isBridge = true;
})
// #endif
export default AppBridge
使用isBridge 判断是否需要调用bridge方法
3 个评论
要回复文章请先登录或注册
2***@qq.com
我可爱的app
1***@163.com