Android和IOS js和原生调用的注入的js代码

来源:互联网 发布:数据可视化的产品目标 编辑:程序博客网 时间:2024/05/17 09:27

接触Android一段时间了,一直用github的一个js和原生调用的框架,具体的代码没看过。

现在由于IOS也要集成Android集成代码,想要保证js中调用方法同时可以在IOS和Android中支持,花了一点时间特意研究下了代码

,并且重新改动了下。

JS代码如下:

 <h1>Myframe5 API</h1><h2><a href="http://www.baidu.com">进入百度</a></h2><h2><a href="index2.html">进入index2.html</a></h2><h3><a href="tel:15065194500">tel:方式启动拨打电话</a></h3><h1>提示和消息</h1><input type="button" onClick="javascript:HostApp.toast('冒泡');" value="冒泡" /><br><br><input type="button" onClick="javascript:HostApp.alert('你好啊');" value="提示" /><br><br><input type="button" onClick="huidiao();" value="提示" /><br><br><script type="text/javascript">var huidiao = function(){var tt=HostApp.getIMSI("你好啊?","滚滚滚滚滚滚",function(res){alert(res.status);});alert(tt);}</script><script type="text/javascript">(function(global){console.log("HostApp initialization begin");var hostApp = {queue: [],callback: function () { //执行hostApp.callback执行arguments中的方法var args = Array.prototype.slice.call(arguments, 0);var index = args.shift();try{var json = args[args.length-1];if(json.indexOf("{")!=-1&&json.indexOf("}")!=-1){ args[args.length-1] = JSON.parse(args[args.length-1]);} this.queue[index].apply(this, args); }catch(e){}delete this.queue[index];}};hostApp.toast = hostApp.alert = hostApp.getIMSI = function () {var args = Array.prototype.slice.call(arguments, 0);if (args.length < 1) { throw "error method"; return; }for (var i = 1;i < args.length;i++) {var arg = args[i];var type = typeof arg;if (type == "function") {var index = hostApp.queue.length;hostApp.queue[index] = arg;args[i] = index;}}var jsonstr=JSON.stringify({method: args.shift(),args: args });alert(jsonstr);//res=prompt(jsonstr); prompt来触发java反射调用var res = " = 左侧的结果";return res;};//监测执行方法时候把方法内容备份到arguments中Object.getOwnPropertyNames(hostApp).forEach(function (property) {var original = hostApp[property];if (typeof original === 'function'&&property!=="callback") {hostApp[property] = function () {return original.apply(hostApp,  [property].concat(Array.prototype.slice.call(arguments, 0)));};}});global.HostApp = hostApp;console.log("HostApp initialization end");})(window);</script>


先点击 提示2 按钮,提示如下:


注意标红位置的index,然后手动console中执行(模拟回调):

javascript:HostApp.callback(0 ,"{\"status\":1,\"msg\":\"success\"}");

注意callback中的第一参数,要和标红的位置一致。


在原版本上做了下修改,原版本的教研更加严格,我修改以后无论js端前台的参数是什么传到后台都被我转为String,然后统一赋值给方法执行反射调用。同时回调的时候如果是 {}格式自动转化为json对象,不过后台接收到参数无法判断类型,只能把最后一个参数当作function了。

原文来自:http://blog.csdn.net/u011730649/article/details/44594387?winzoom=1
原创粉丝点击