美文网首页
WKWebview js 调用oc 和oc调用js

WKWebview js 调用oc 和oc调用js

作者: 帅气的要死的感觉 | 来源:发表于2018-09-11 10:45 被阅读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];

}

相关文章

网友评论

      本文标题:WKWebview js 调用oc 和oc调用js

      本文链接:https://www.haomeiwen.com/subject/fpuygftx.html