oc调用js就特别简单了,只需WKWebView调用
-(void)evaluateJavaScript:completionHandler:方法即可。
js调用oc
#pragma mark - get方法
- (WKWebView*)webView {if(_webView ==nil) {// js配置WKUserContentController*userContentController = [[WKUserContentControlleralloc] init]; [userContentController addScriptMessageHandler:selfname:@"jsCallOC"];
// js注入,注入一个alert方法,页面加载完毕弹出一个对话框。
NSString*javaScriptSource =@"alert(\"WKUserScript注入js\");";
WKUserScript*userScript = [[WKUserScriptalloc] initWithSource:javaScriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentEndforMainFrameOnly:YES];
// forMainFrameOnly:NO(全局窗口),yes(只限主窗口)
[userContentController addUserScript:userScript];
// WKWebView的配置WKWebViewConfiguration*configuration = [[WKWebViewConfigurationalloc] init];
configuration.userContentController = userContentController;
// 显示WKWebView_webView = [[WKWebViewalloc] initWithFrame:self.view.frame configuration:configuration];
[self.view addSubview:_webView]; }return_webView;
}
#pragma mark alert弹出框
- (void)webView:(WKWebView*)webView runJavaScriptAlertPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo*)frame completionHandler:(void(^)(void))completionHandler {
NSLog(@"%s",__FUNCTION__);
// 确定按钮UIAlertAction*alertAction = [UIAlertActionactionWithTitle:@"OK"style:UIAlertActionStyleCancelhandler:^(UIAlertAction* _Nonnull action) {
completionHandler();
}];
// alert弹出框UIAlertController*alertController = [UIAlertControlleralertControllerWithTitle:message message:nilpreferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:alertAction]; [selfpresentViewController:alertController animated:YEScompletion:nil];
}