這陣子移動端兩個端都和前端做了交互 記錄一下
前端調用iOS/Android(以目前前端最流行的框架Vue為例 )
//判斷安卓
const isAndroid = navigator.userAgent.indexOf('Android') > -1 || navigator.userAgent.indexOf('Linux') > -1;
//判斷iOS
const isIOS = !!navigator.userAgent.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);
if (isAndroid) {
// 'scan'為標志符 app定義 ,data 為傳過去app的值
window.WebViewJavascriptBridge.callHandler( 'scan', data
function(responseData) {});
}else if (isIOS) {
//ios如果不需要傳值 則data要傳null
window.webkit.messageHandlers.scan.postMessage(data)
}
iOS注冊接受前端的事件 (目前基本上都是WKWebview,以此為例)
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
self.userController = [[WKUserContentController alloc] init];
[self.userController addScriptMessageHandler:self name:@"scan"];
//在代理方法里
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
if([message.name isEqualToString:@"scan"]){ //調用 }
}
安卓注冊接受前端的事件 ( 借助jsbridge輕松實現 )
onScan(mWebView);
private void onScan(BridgeWebView webView) {
webView.registerHandler("scan", (data, function) -> {
});
}
==============
移動端調用前端的方法(需要注意的是如果h5是用js寫的方法則h5端不需要做什么操作,如果h5是vue實現的話需要把方法暴露出來)
//這是寫在methods中給app調用方法
scanResult(resultStr){
console.log('app傳過來的數據',resultStr)
},
//此外需要在mounted里暴露這個方法
mounted(){
window.scanResult = this.scanResult;
},
iOS調用h5的方法
NSString *anyId = @""; (傳遞的參數)
NSString *jsStr = [NSString stringWithFormat:@"scanResult('%@')",anyId];
[self.myWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (error) {
NSLog(@"調用錯誤");
}
}];
安卓調用h5的方法
String deviced = data.getStringExtra("result") (傳遞的參數)
mWebView.loadUrl("javascript:scanResult('" + deviced + "')");