当前位置: 首页 > 工具软件 > Jot-iOS > 使用案例 >

jsBridge与安卓,ios

宰父深
2023-12-01
var uniqueId = 0;

;(function($){
	var scWid = document.documentElement.offsetWidth||document.body.offsetWidth;
	var initScWid = 375;
	var initFontSize = 20;
	$('html').css({
		'fontSize': parseInt((scWid * initFontSize) / initScWid) + 'px'
	});
})(Zepto);

function jsBridge(funcName,data,callback){
	if (navigator.userAgent.match(/(iPhone|iPod|iPad);?/i)) { //ios
		setupWebViewJavascriptBridge(function (bridge) {
			bridge.callHandler(funcName, data,callback );
		});
	} else if (navigator.userAgent.match(/android/i)) {
		connectWebViewJavascriptBridge(function(bridge) {
			if(uniqueId==1){
                bridge.init(function(message, responseCallback) {responseCallback(data)});
            }
			if(window.WebViewJavascriptBridge){
				window.WebViewJavascriptBridge.callHandler(
	               funcName
	               , data,
				   callback
	            );
			}else{
				bridge.callHandler(funcName, data, callback);
			}
			bridge.registerHandler("openPage", function(data, responseCallback) {
                console.log("from android",data);
                var responseData = "我接受到了安卓的调用";
           	});
       });
	} else {
		console.log('this is an error ouput');
	}
}

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 = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function () {
        document.documentElement.removeChild(WVJBIframe)
    }, 100)
}

function connectWebViewJavascriptBridge(callback) {
    uniqueId++;
    if (window.WebViewJavascriptBridge) {
        callback(WebViewJavascriptBridge)
    } else {
        document.addEventListener(
        'WebViewJavascriptBridgeReady'
        , function () {
            callback(WebViewJavascriptBridge)
        }, false);
    }
}


代码如上,ios里面直接使用setupWebViewJavascriptBridge方法就可以,但是在安卓上,需要调用一次init()方法进行初始化,且只能调用一次,重复调用会抛异常:WebViewJavascriptBridge.init() called twice。所以定一了一个全局变量进行处理。

调用方式:

var data = {
				"userName":realName,
				"userIDcard":idCard,
				"securityCode":code,
			}
			jsBridge("webSubmit",data,function(responseData){
				var responseData = JSON.parse(responseData);
				console.log(responseData);
				toast(responseData.msg);
			});


 类似资料: