javascript:
window.bridge = {
getDouble: value => {
// 20
},
getTriple: value => {
// more
}
};
location.href = \'sdk://double?value=10\';
android:
webview.setWebViewClient(new WebViewClient() {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// 判断如果 url 是 sdk:// 打头的就拦截掉
// 然后从 url sdk://action?params 中取出 action 与params
Uri uri = Uri.parse(url);
if ( uri.getScheme().equals("sdk")) {
// 比如 action = double, params = value=10
webview.evaluateJavascript(\'window.bridge.getDouble(20)\');
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
});
ios:
- (BOOL)webview:(UIWebView *)webview shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
// 判断如果 url 是 sdk:// 打头的就拦截掉
// 然后从 url sdk://action?params 中取出 action 与params
NSString *urlStr = request.URL.absoluteString;
if ([urlStr hasPrefix:@"sdk://"]) {
// 比如 action = double, params = value=10
NSString *func = @"window.bridge.getDouble(20)";
[webview stringByEvaluatingJavaScriptFromString:func];
return NO;
}
return YES;
}
参考:
h5 与原生 app 交互的原理