最近作一個項目,混合了NativeCode 和 HTML,爲了便於JS 調用App的一些方法,統一封裝一個Js方法,記錄以下javascript
Android 端首先要再WebView中容許JS的調用java
WebView myWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = myWebView.getSettings(); webSettings.setJavaScriptEnabled(true); myWebView.addJavascriptInterface(new WebAppInterface(this), "JsAndroid");
IOS端使用的是一個開源庫 EasyJsWebView,在IOS端引用便可android
JS代碼:ios
function callApp(method) { var args = [].slice.call(arguments).splice(1); var s = ""; if (/android/i.test(navigator.userAgent)) {//安卓 s = window["JsAndroid"][method].apply(window.JsAndroid, args); } if (/ipad|iphone|mac/i.test(navigator.userAgent)) {//ios s = window["JsIOS"][method].apply(this, args); } return s; } //與IOS交互的方法 window.EasyJS = { __callbacks: {}, invokeCallback: function (cbId, removeAfterExecute) { var args = Array.prototype.slice.call(arguments).splice(2); for (var i = 0, l = args.length; i < l; i++) { args[i] = decodeURIComponent(args[i]); } var cb = EasyJS.__callbacks[cbId]; if (removeAfterExecute) { EasyJS.__callbacks[cbId] = undefined; } return cb.apply(null, args); }, call: function (obj, functionName, args) { var formattedArgs = []; for (var i = 0, l = args.length; i < l; i++) { if (typeof args[i] == "function") { formattedArgs.push("f"); var cbId = "__cb" + (+new Date); EasyJS.__callbacks[cbId] = args[i]; formattedArgs.push(cbId); } else { formattedArgs.push("s"); formattedArgs.push(encodeURIComponent(args[i])); } } var argStr = (formattedArgs.length > 0 ? ":" + encodeURIComponent(formattedArgs.join(":")) : ""); var iframe = document.createElement("IFRAME"); iframe.setAttribute("src", "easy-js:" + obj + ":" + encodeURIComponent(functionName) + argStr); document.documentElement.appendChild(iframe); iframe.parentNode.removeChild(iframe); iframe = null; var ret = EasyJS.retValue; EasyJS.retValue = undefined; if (ret) { return decodeURIComponent(ret); } }, inject: function (obj, methods) { alert(obj); window[obj] = {}; var jsObj = window[obj]; for (var i = 0, l = methods.length; i < l; i++) { (function () { var method = methods[i]; var jsMethod = method.replace(new RegExp(":", "g"), ""); jsObj[jsMethod] = function () { alert("qq"); return EasyJS.call(obj, method, Array.prototype.slice.call(arguments)); }; })(); } } };
說明一下,一開始調用Android也是採用window["JsAndroid"][method].apply(this,args),這樣的話,就徹底一致了。可是在調試的時候發現這種方式沒法正常調用,google後發現是因爲this的的影響域致使的,須要指明查找域。 參考git
記錄一下!github