WKWebview的学习 - WKUIDelegate

一、实现WKUIDelegate的意义

1. 防止网页内容在遇到__blank标签时不响应点击的bug
2. 使Webview能显示JS弹框(Alert弹框、confirm弹框、TextInput弹框)
3. 如果不设置代理然后实现这些方法,网页就像少了这些功能一样

二、代理方法的实现

#pragma mark alert弹出框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString*)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void(^)(void))completionHandler {
  // 确定按钮
  UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    completionHandler();
  }];
// alert弹出框
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:alertAction];
[self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark Confirm选择框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(nonnull NSString*)message initiatedByFrame:(nonnull  WKFrameInfo *)frame completionHandler:(nonnull void(^)(BOOL result))completionHandler {
UIAlertAction *alertActionCancel = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull  action) {// 返回用户选择的信息
  completionHandler(NO);
}];
UIAlertAction *alertActionOK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
  completionHandler(YES);
}];
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:alertActionCancel];
[alertController addAction:alertActionOK];
[self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark TextInput输入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(nonnull NSString*)prompt defaultText:(nullable NSString*)defaultText initiatedByFrame:(nonnull WKFrameInfo *)frame completionHandler:(nonnull void(^)(NSString* _Nullable))completionHandler {
// alert弹出框
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
  textField.placeholder= defaultText;
}];
[alertController addAction:[UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {// 返回用户输入的信息
UITextField *textField = alertController.textFields.firstObject;
  completionHandler(textField.text);
}]];
[self presentViewController:alertController animated:YEScompletion:nil];
}

你可能感兴趣的:(WKWebview的学习 - WKUIDelegate)