Recently done a project, mixed with Nativecode and HTML, in order to facilitate the JS call app some methods, unified encapsulation of a JS method, recorded as follows
The Android side first wants to webview in the Allow JS the call
WebView Mywebview = (WebView) Findviewbyid (R.id.webview); WebSettings websettings = Mywebview.getsettings (); websettings.setjavascriptenabled (true); Mywebview.addjavascriptinterface (New Webappinterface (This), "jsandroid");
iOS uses an open-source library Easyjswebview, which is referenced on iOS
JS Code:
function Callapp (method) {var args = [].slice.call (arguments). Splice (1); var s = ""; if (/android/i.test (navigator.useragent)) {//android 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; }//how to interact with 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)); }; })(); } }};
Note that the first call to Android is also the use of window["Jsandroid"][method].apply (This,args), so it is completely consistent. However, when debugging, it is found that this method can not be called normally, after Google found that the impact of this is caused by the domain, need to indicate the lookup domain. Reference
Record it!
Use JS in WebView to call function functions of Android/ios