OC和JS交互

可以通過以下幾種方式進行交互

  1. 攔截url(適用于UIWebViewWKWebView
  2. JavaScriptCore(只適用于UIWebView,iOS7+
  3. WKScriptMessageHandler(只適用于WKWebView,iOS8+
  4. WebViewJavascriptBridge(適用于UIWebViewWKWebView,屬于第三方框架)
  5. Cordova框架,這個有點??這里就不做介紹了

UIWebViewJS交互

UIWebView和JS交互.png
1. 直接URL攔截
  • oc調(diào)用JS直接調(diào)用方法即可
// document.title: 你需要監(jiān)聽的`JS`
[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
  • JS調(diào)用OC

通過UIWebView的代理方法來攔截進行自定義

// 加載所有請求數(shù)據(jù), 以及控制是否加載
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    NSLog(@"request = %@",request);
    // 路由能力 --
    NSLog(@"URL = %@",request.URL.pathComponents);
    NSLog(@"scheme = %@",request.URL.scheme);
    NSString *scheme = request.URL.scheme;
      if ([scheme isEqualToString:@"lgedu"]) {
          NSLog(@"------------");
          NSArray *arr = request.URL.pathComponents;
          NSLog(@"---------%@", arr);
          
          if (arr.count) {
              NSString *methodName = arr[1];
              if ([methodName isEqualToString:@"getSum"]) {
                  // array[2],array[3]
                  NSLog(@"%@-%@",arr[2],arr[3]);
              }
              // 調(diào)用OC方法
              // arr 傳遞的方法參數(shù)
              [self performSelector:@selector(getSum:) withObject:arr afterDelay:0];
          }
        return NO;
    }
    return YES;
}
- (void)getSum:(id)str {
    NSLog(@"-------getSum: %@", str);
}
2. 通過JavaScriptCore oc調(diào)用JS**
1. [jsContext evaluateScript]
2. [jsContext callWithArguments]

JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
 // OC調(diào)用JS
[jsContext evaluateScript:@"showAlert()"];

  • JS調(diào)用OC
  __weak typeof(self) weakSelf = self;
    
    // 傳遞參數(shù)arr
    [self.jsContext evaluateScript:@"var arr = ['aaaa', 'bbbb', 'cccc', '哈哈']"];
    // 異常處理
    self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        context.exception = exception;
        NSLog(@"exception == %@",exception);
        NSLog(@"%@",context);
    };
    // JS調(diào)用OC
    self.jsContext[@"showMessage"] = ^{
        // 參數(shù) (JS 帶過來的)
         NSArray *args = [JSContext currentArguments];
         NSLog(@"args = %@",args);
         NSLog(@"currentThis   = %@",[JSContext currentThis]);
         NSLog(@"currentCallee = %@",[JSContext currentCallee]);
         
         // OC調(diào)用JS
         NSDictionary *dict = @{@"name":@"zain", @"age":@18};
         [[JSContext currentContext][@"ocCalljs"] callWithArguments:@[dict,@"咸魚"]];
    };
    // JS調(diào)用OC
    self.jsContext[@"showDict"] = ^{
        
        NSArray *arr = [JSContext currentArguments];
        NSLog(@"----->%@", arr);
    };
    // 獲取變量
    JSValue *arrValue = self.jsContext[@"arr"];
    NSLog(@"arrValue == %@",arrValue);
    
    // JS 操作對象
    YY_JSObject *yyObject = [[YY_JSObject alloc] init];
    self.jsContext[@"yyObject"] = yyObject;
    NSLog(@"yyObject == %d",[yyObject getSum:10 num2:20]);
    
    // 打開相冊
    self.jsContext[@"getImage"] = ^() {
        weakSelf.imagePicker = [[UIImagePickerController alloc] init];
        weakSelf.imagePicker.delegate = weakSelf;
        weakSelf.imagePicker.allowsEditing = YES;
        weakSelf.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [weakSelf presentViewController:weakSelf.imagePicker animated:YES completion:nil];
    };

WKWebViewJS交互

WKWebView和JS交互.png
  • oc調(diào)用JS直接調(diào)用方法即可
    // OC調(diào)用JS
    NSString *jsStr = @"showAlert('messageHandle: OC調(diào)用JS')";
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id result, NSError * _Nullable error) {
        NSLog(@"%@----%@",result, error);
    }];
  • JS調(diào)用OC

web端寫法

window.webkit.messageHandlers.<方法名>.postMessage(<數(shù)據(jù)>)

OC寫法

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"messgaeOC"];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"messgaeOC"];
}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
   
    // 攔截JS
    if (message.name) {
        // OC 實現(xiàn)
    }
    NSLog(@"message == %@ --- %@",message.name,message.body);
}

WebViewJavascriptBridge

WebViewJavascriptBridge地址及用法

最后送上Demo地址

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

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容