A :JS調用JAVAhtml
/** * 點擊按鈕 * Click the button */ private onButtonClick(e: egret.TouchEvent) { // this.textfield.text = "點擊了按鈕"; console.log(`game button 點擊了 , 開始調用JAVA函數`); let $obj : Object = { "name" : "Aonaufly", "occupation" : "warrior" }; window["WebViewJavascriptBridge"].callHandler( 'JS2JAVA' , JSON.stringify($obj) , function(responseData) { // this.textfield.text = `enterGame 2 Android callback param : ${responseData}`; console.log(`enterGame 2 Android callback param : ${responseData}`); } ); }
PS 參數
①,JAVA的方法(string類型), 此處我定義的是「JS2JAVA」
②,JS給JAVA傳遞的參數
③,回調函數,供JAVA調用,回調函數的參數responseData,由JAVA回調給JS使用前端
B : JS註冊方法供JAVA調用git
private connectWebViewJavascriptBridge( callback : Function ) : void { if (window["WebViewJavascriptBridge"]) { callback(window["WebViewJavascriptBridge"]) } else { document.addEventListener( 'WebViewJavascriptBridgeReady' , function() { callback(window["WebViewJavascriptBridge"]) }, false ); } } protected createGameScene(): void { this.connectWebViewJavascriptBridge(function (bridge) { bridge.init(function(message, responseCallback) { console.log('JS got a message', message); var data = { 'Javascript Responds': '測試中文!' }; if (responseCallback) { console.log('JS responding with', data); responseCallback(data); } }); /// Java 調 JS bridge.registerHandler("JAVA2JS", function(data, responseCallback) { if (responseCallback) { var responseData = "Javascript Says Right back aka!"; // this.textfield1.text = JSON.stringify(data); console.log(JSON.stringify(data)); responseCallback(responseData); } }); }) }
注意 :
「JAVA2JS」 , 既是在TS端註冊了一個「JAVA2JS」的方法,供JAVA端來調用,
github
①,須要下載jsBridge類庫 : https://github.com/lzyzsd/JsBridge
②,須要得到前端遊戲的html地址 : http://www.xxx.com/index(好比)
重點:須要使用WebView控件
A : TS調用JAVAweb
webView.registerHandler("JS2JAVA", new BridgeHandler() { @Override public void handler(String data, CallBackFunction function) { // Log.i(TAG, "handler = submitFromWeb, data from web = " + data); makeText(MainActivity.this, "handler = submitFromWeb, data from web = " + data, LENGTH_SHORT).show(); function.onCallBack("submitFromWeb exe, response data 中文 from Java"); } });
注意 , TS端和JAVA的方法名稱字符串必定要一致,此處用的是「JS2JAVA」
B:JAVA調用TSide
@Override public void onClick(View v) { if (button.equals(v)) { makeText(MainActivity.this, "JAVA調用JS ", LENGTH_SHORT).show(); webView.callHandler("JAVA2JS", "data from Java", new CallBackFunction() { @Override public void onCallBack(String data) {//functionInJs // TODO Auto-generated method stub Log.i(TAG, "reponse data from js " + data); makeText(MainActivity.this, "reponse data from js ", LENGTH_SHORT).show(); } }); } }
一樣的「JAVA2JS」方法名稱要一致。函數
附送IOS類庫地址 : https://github.com/wangjiaojiao77/WebViewJavascriptBridge測試