随着H5技术的更新,Android嵌套H5页面的越来越多,js和Android端的交互也是越来越简单,之前用过得是Android提供接口,js端调用,这应该是最常用的方式,不过这种方式需要注意的是防止木马的注入。还有就是我不知道iOS端是如何跟js端交互的,所以导致iOS端开发的时候js又要重新修改。这段时间用到了另一种方式解决了iOS和Android不一致的问题,所以记录下以后用的时候直接拿来:
这种方式就是有服务端制定规则,平常H5的URL都是以Http开头的,只要服务端把H5的URL做个标识我们在webView加载的时候判断下这个标识做相应的操作就行了,这里涉及到解析Url,说白了就是截取自己想要的字段,我用了两种方式,第一种有个小问题就是不能截取最后一个字符:待修改,下面就是方法:
public static Map<String, Object> getClientMap(String data) { int endIndex = data.indexOf("?"); data = data.substring(endIndex + 1); StringBuffer strbuf = new StringBuffer(); StringBuffer strbuild = new StringBuffer(); Map<String, Object> map = new HashMap<>(); for (int i = 0; i < data.length(); i++) { if (data.substring(i, i + 1).equals("=")) { for (int n = i + 1; n < data.length(); n++) { if (data.substring(n, n + 1).equals("&") || n == data.length() - 1) { map.put(strbuf.toString(), strbuild); strbuf = new StringBuffer(""); strbuild = new StringBuffer(""); i = n; break; } strbuild.append(data.substring(n, n + 1)); } continue; } strbuf.append(data.substring(i, i + 1)); } return map; }第二种呢就是指定字段获取:
public static String getValueByName(String url, String name) { String result = ""; if (TextUtils.isEmpty(url) || TextUtils.isEmpty(name)) { return result; } int index = url.indexOf("?"); String temp = url.substring(index + 1); String[] keyValue = temp.split("\\u0024");//"\\u0024"这个是$符号的编码,由于Java对$进行了转义,所以判断的时候需要转义其他的字符转义博客中有
for (String str : keyValue) { if (str.contains(name)) { result = str.replace(name + "@", ""); break; } } return result;}