WKWebview js 调用oc 和oc调用js

2018-09-11  本文已影响79人  帅气的要死的感觉

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];

}

上一篇 下一篇

猜你喜欢

热点阅读