可以通过以下几种方式进行交互
- 拦截
url
(适用于UIWebView
和WKWebView
) -
JavaScriptCore
(只适用于UIWebView,iOS7+
) -
WKScriptMessageHandler
(只适用于WKWebView,iOS8+
) -
WebViewJavascriptBridge
(适用于UIWebView
和WKWebView
,属于第三方框架) -
Cordova
框架,这个有点🤮这里就不做介绍了
UIWebView
和JS
交互
UIWebView和JS交互.png
1. 直接URL
拦截
-
oc
调用JS
直接调用方法即可
// document.title: 你需要监听的`JS`
[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
-
JS
调用OC
通过
UIWebView
的代理方法来拦截进行自定义
// 加载所有请求数据, 以及控制是否加载
- (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]);
}
// 调用OC方法
// arr 传递的方法参数
[self performSelector:@selector(getSum:) withObject:arr afterDelay:0];
}
return NO;
}
return YES;
}
- (void)getSum:(id)str {
NSLog(@"-------getSum: %@", str);
}
2. 通过JavaScriptCore
oc
调用JS
**
1. [jsContext evaluateScript]
2. [jsContext callWithArguments]
JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// OC调用JS
[jsContext evaluateScript:@"showAlert()"];
-
JS
调用OC
__weak typeof(self) weakSelf = self;
// 传递参数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调用OC
self.jsContext[@"showMessage"] = ^{
// 参数 (JS 带过来的)
NSArray *args = [JSContext currentArguments];
NSLog(@"args = %@",args);
NSLog(@"currentThis = %@",[JSContext currentThis]);
NSLog(@"currentCallee = %@",[JSContext currentCallee]);
// OC调用JS
NSDictionary *dict = @{@"name":@"zain", @"age":@18};
[[JSContext currentContext][@"ocCalljs"] callWithArguments:@[dict,@"咸鱼"]];
};
// JS调用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
调用JS
直接调用方法即可
// OC调用JS
NSString *jsStr = @"showAlert('messageHandle: OC调用JS')";
[self.webView evaluateJavaScript:jsStr completionHandler:^(id result, NSError * _Nullable error) {
NSLog(@"%@----%@",result, error);
}];
-
JS
调用OC
web
端写法
window.webkit.messageHandlers.<方法名>.postMessage(<数据>)
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 实现
}
NSLog(@"message == %@ --- %@",message.name,message.body);
}