iOS/Android與前端Vue的交互

這陣子移動端兩個端都和前端做了交互 記錄一下

前端調用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 + "')");

后續(xù) 這樣基本上都能完成三端的交互啦 (o)/~

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容