今天學習怎么在java中調用javascript方法,做個記錄:
第一種方式,這個最簡單:
loadUrl("javascript:func1()");
要注意要在deviceready后調用,否則會報方法未定義的錯誤:"Uncaught ReferenceError: fun1 is not defined";
第二種方式:注冊一個通道,在native中向js發送回調,這也是新版cordova推薦的方法:
javascript:
function myinit(){ alert('12355'); } //最省事的就是找個現成的插件添加個函數"callJSInit",能執行注冊就可以,或者在cordova_plugins.js里注冊一個單獨的插件模塊,見注1; cordova.define("插件模塊ID", function(require, exports, module) { var exec = require('cordova/exec'); var callJS = { init:function() { cordova.require('cordova/channel').onCordovaReady.subscribe(function(){ exec(succeedCallback, null, "PluginName", "callJSInit", []); function succeedCallback(message){ //執行js代碼 eval(message); //還可以這樣,大膽的發揮你的想象力 /* if(message=='f1') alert(1); else if(message == 'f2') alert(2); …… */ } }); } }; module.exports = callJS; }); //注1:在cordova_plugins.js里注冊一個單獨的插件模塊 cordova.define('cordova/plugin_list', function(require, exports, module) { module.exports = [ //添加: { "file": "js文件路徑", "id": "插件模塊", "clobbers": ["navigator.callJS"] } ] } //在app deviceready后執行: navigator.callJS.init()
java文件:
public class PluginName extends CordovaPlugin { private static CallbackContext mCallbackContext; @Override public boolean execute(String action, final JSONArray args, final CallbackContext callbackContext) throws JSONException { if (action.equals("callJSInit")) { mCallbackContext = callbackContext; //拿到回調對象並保存 //PluginResult dataResult = new PluginResult(PluginResult.Status.OK, "calljs init ready"); //dataResult.setKeepCallback(true);// 非常重要 //mCallbackContext.sendPluginResult(dataResult); return true; } else { return false; } } @Override public Object onMessage(String id, Object data) { return null; } public static void callJS(String message) { if (mCallbackContext != null) { PluginResult dataResult = new PluginResult(PluginResult.Status.OK, message); dataResult.setKeepCallback(true);// 非常重要 mCallbackContext.sendPluginResult(dataResult); } } }
在其它java文件中調用js:
PluginName.callJS("myinit()");
運行app就會顯示"myinit"方法中的內容了。
//在app deviceready后執行: