WebViewJavascriptBridge(H5与原生交互)

酆光熙
2023-12-01
/* eslint-disable */
/**
 * 调用原生的一些方法
 * 有些回调绑定到window上,是因为现在安卓回调里不能调用局部变量
 */

// android有问题,回调函数的作用域是window下才能访问,其他传进去的都是undefined
// 提升回调函数到window下解决此问题
window.androidCallbackBridge = null;

function platform() {
    var u = navigator.userAgent;
    let type = "pc"
    if (u.indexOf("Android") > -1 || u.indexOf("Adr") > -1) {
        type = "android"
    } else if (!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)) {
        type = "ios"
    }
    return type;
}

function connectWebViewJavascriptBridge(callback) {
    let type = platform()
    if (type == "android") {
        // Android使用
        if (window.WebViewJavascriptBridge) {
            callback(WebViewJavascriptBridge);
        } else {
            document.addEventListener(
                "WebViewJavascriptBridgeReady",
                function() {
                    callback(WebViewJavascriptBridge);
                },
                false
            );
        }
    }
    if (type == "ios") {
        // iOS使用
        if (window.WebViewJavascriptBridge) {
            return callback(window.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);
        }, 0);
    }
}

export function $openNewWebView() {
	connectWebViewJavascriptBridge(function(bridge) {
	
	    //注册一个方法(方法名是“JS Echo”),客户端进行调用(方法名也是“JS Echo”),responseCallback是回调函数
	    bridge.registerHandler('JS Echo', function(data, responseCallback) {
	        console.log("JS Echo called with:", data)
	        responseCallback(data)
	    })
	
	    //客户端已经注册好一个名为“ObjC Echo”的方法,H5直接进行调用(方法名也为“ObjC Echo”)就行,调用的时候可以传客户端需要的参数
	    bridge.callHandler('ObjC Echo', {'key':'value'}, function responseCallback(responseData) {
	        console.log("JS received response:", responseData)
	    })
	})

}
 类似资料: