可以通過以下幾種方式進行交互
- 攔截
url(適用于UIWebView和WKWebView) -
JavaScriptCore(只適用于UIWebView,iOS7+) -
WKScriptMessageHandler(只適用于WKWebView,iOS8+) -
WebViewJavascriptBridge(適用于UIWebView和WKWebView,屬于第三方框架) -
Cordova框架,這個有點??這里就不做介紹了
UIWebView和JS交互

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];
};
WKWebView和JS交互

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);
}