JSBridge.js 5.44 KB
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终端
var appClient = null;
function AppClient(appObj, isAndroid) {
    this.appObj = appObj;
    this.isAndroid = isAndroid;
};
function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
// console.log(obj.latitude)
// function toJson(str) {
//     try {
//         if(str.length > 2){
//             var result = /\{([\s\S]*)\}/.exec(str);
//         }
//         var arr =  result[1].split(',')
//         var obj = {}
//         arr.forEach(function (value) {
//             var key, val
//             if(isAndroid){
//                 key = value.split('=')[0]
//                 val = value.split('=')[1]
//             } else {
//                 key = value.split(':')[0]
//                 val = value.split(':')[1]
//             }
//
//             obj[key] = val*1
//         })
//         return obj
//
//     } catch (e) {
//         return {}
//     }
// }
// layer.open({
//     content: "isAndroid:"+ isAndroid+ ",isiOS:" + isiOS,
//     time: 2
// })
AppClient.prototype.getERCode = function (jsonStr, callback) {
    var dataParams = "";
    if(isJson(jsonStr)){
        dataParams = JSON.parse(jsonStr);
    }
    var param = {
        from: 'H5',
        params: dataParams
    };
    if(this.isAndroid) {
        window.WebViewJavascriptBridge.callHandler('getERCode', jsonStr);
        window.WebViewJavascriptBridge.registerHandler('postERCode', callback)
    } else {
        this.appObj.registerHandler("postERCOde", callback)
        this.appObj.callHandler("getERCode", param, function (data, responseCallback) {

        });
    }

};
AppClient.prototype.getGPS = function (jsonStr, callback) {
    var dataParams = "";
    if(isJson(jsonStr)) {
        dataParams = JSON.parse(jsonStr);
    }
    var param = {
        from: 'H5',
        params: dataParams
    };
    var isRes = false
    if(this.isAndroid) {
        var toNonExponential = function (num) {
            var m = num.toExponential().match(/\d(?:\.(\d*))?e([+-]\d+)/);
            return num.toFixed(Math.max(0, (m[1] || '').length - m[2]));
        }

        var cb = function(data, responseCallback){

            isRes = true
            var latitude = ''
            var longitude = ''
            var str = JSON.stringify(data)
            try {
                var result = /\{([\s\S]*)\}/.exec(str);
                var arr = result[1].split(',')
                latitude = arr[0].split('=')[1]
                longitude = arr[1].split('=')[1]
                latitude = toNonExponential(latitude)
                longitude = toNonExponential(longitude)
            } catch (e) {
                layer.open({
                    content: e
                })
            }

            layer.open({
                content: latitude
            })
            callback(latitude, longitude, responseCallback)
        }
        window.WebViewJavascriptBridge.callHandler('getGPS', jsonStr, function (data, responseCallback) {
            cb(data, responseCallback)
        })
        window.WebViewJavascriptBridge.callHandler('postGPS', function (data, responseCallback) {
            cb(data, responseCallback)
        })
    } else {
        this.appObj.registerHandler("postGPS", function (data, responseCallback) {
            isRes = true
            var latitude = ''
            var longitude = ''
            var str = JSON.stringify(data)
            var result = /\{([\s\S]*)\}/.exec(str);
            var arr = result[1].split(',')
            longitude = arr[0].split(':')[1]
            latitude = arr[1].split(':')[1]
            callback(latitude, longitude, responseCallback)
        })
        this.appObj.callHandler("getGPS", param, function (data, responseCallback) {
            
        });
    }
    setTimeout(function () {
        if(!isRes){
            layer.open({
                content: '无法获取定位信息,检查定位设置,或重新打开'
            })
            callback(30.2741500000, 120.1551500000, function(){})
        }
    }, 10000)
};

if(isAndroid || isiOS) {

    function setupWebViewJavascriptBridge(callback) {
        if (window.WebViewJavascriptBridge) { return callback(WebViewJavascriptBridge); }
        if(isiOS){
            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)
        } else if (isAndroid) {
            document.addEventListener('WebViewJavascriptBridgeReady', function (event) {
                callback(WebViewJavascriptBridge)
            }, false)
        }
    }
    setupWebViewJavascriptBridge(function(bridge) {
        if(isAndroid) {
            appClient =  new AppClient(window.WebViewJavascriptBridge, true);
            bridge.init(function (message, responseCallback) {
                responseCallback({'Javascript Responds': 'Wee!'})
            })
        }
        if(isiOS) {
            appClient = new AppClient(bridge, false);
        }
        // 此处可以调用一些init的方法
    });
} else {
    appClient = undefined;
}