安全性及其它

JSBridge類管理暴露給前端方法,前端調用的方法應該在此類中註冊纔可以使用。register的實現是從Map中查找key是否存在,不存在則反射取得對應class中的全部方法,具體方法是在BridgeImpl中定義的,方法包括三個參數分別爲WebView、JSONObject、CallBack。若是知足條件,則將全部知足條件的方法put到map中。javascript

private static Map<String, HashMap<String, Method>> exposedMethods = new HashMap<>();
public static void register(String exposedName, Class<? extends IBridge> clazz) {
if (!exposedMethods.containsKey(exposedName)) {
try {
exposedMethods.put(exposedName, getAllMethod(clazz));
} catch (Exception e) {
e.printStackTrace(http://www.amjmh.com);
}
}
}

複製代碼
JSBridge類中的callJava方法就是將js傳遞過來的URL解析,根據將要調用的類名從剛剛創建的Map中找出,根據方法名調用具體的方法,並將解析出的三個參數傳遞進去。前端

public static String callJava(WebView webView, String uriString) {
String methodName = "";
String className = "";
String param = "{}";
String port = "";
if (!TextUtils.isEmpty(uriString) && uriString.startsWith("JSBridge")) {
Uri uri = Uri.parse(uriString);
className = uri.getHost();
param = uri.getQuery();
port = uri.getPort() + "";
String path = uri.getPath();
if (!TextUtils.isEmpty(path)) {
methodName = path.replace("/", "");
}
}


if (exposedMethods.containsKey(className)) {
HashMap<String, Method> methodHashMap = exposedMethods.get(className);

if (methodHashMap != null && methodHashMap.size() != 0 && methodHashMap.containsKey(methodName)) {
Method method = methodHashMap.get(methodName);
if (method != null) {
try {
method.invoke(null, webView, new JSONObject(param), new Callback(webView, port));
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return null;
}

複製代碼
CallBack類是用來回調js中回調方法的Java對應類。Java層處理好的返回結果是經過CallBack類來實現的。在這個回調類中傳遞的參數是JSONObject(返回結果)、WebView和port,port應與js傳遞過來的port相對應。java

private static Handler mHandler = new Handler(Looper.getMainLooper());
private static final String CALLBACK_JS_FORMAT = "javascript:JSBridge.onFinish('%s', %s);";
private String mPort;
private WeakReference<WebView> mWebViewRef;

public Callback(WebView view, String port) {
mWebViewRef = new WeakReference<>(view);
mPort = port;
}
public void apply(JSONObject jsonObject) {
final String execJs = String.format(CALLBACK_JS_FORMAT, mPort, String.valueOf(jsonObject));
if (mWebViewRef != null && mWebViewRef.get() != null) {
mHandler.post(new Runnable() {
@Override
public void run() {
mWebViewRef.get().loadUrl(execJs);
}
});
}
}web

相關文章
相關標籤/搜索