實(shí)例代碼如下:
#import <WebKit/WebKit.h>
<WKNavigationDelegate,WKUIDelegate>
WKWebViewConfiguration *config = [WKWebViewConfiguration new];
config.preferences = [WKPreferences new];
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
WKWebView *webView_WK = [[WKWebView alloc]initWithFrame:frame configuration:config];
webView_WK.navigationDelegate = self;
webView_WK.UIDelegate = self;
[self.view addSubview: webView_WK];
#pragma mark - WKNavigationDelegate
// 請求開始前,會(huì)先調(diào)用此代理方法
//- (BOOL)webView:shouldStartLoadWithRequest:navigationType:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSURLRequest *request = navigationAction.request;
if (navigationAction.navigationType == WKNavigationTypeLinkActivated &&
[request.URL.host.lowercaseString containsString:@"我是跨域標(biāo)識(shí)符"]) {
// 對于跨域,需要手動(dòng)跳轉(zhuǎn)
[[UIApplication sharedApplication] openURL:navigationAction.request.URL];
// 不允許web內(nèi)跳轉(zhuǎn)
decisionHandler(WKNavigationActionPolicyCancel);
}
else {
NSString *word = [request.URL.absoluteString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(@"網(wǎng)址:%@",word);
//允許web內(nèi)跳轉(zhuǎn)
decisionHandler(WKNavigationActionPolicyAllow);
}
}
// 在響應(yīng)完成時(shí),會(huì)回調(diào)此方法
// 如果設(shè)置為不允許響應(yīng),web內(nèi)容就不會(huì)傳過來
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
decisionHandler(WKNavigationResponsePolicyAllow);
}
// 開始導(dǎo)航跳轉(zhuǎn)時(shí)會(huì)回調(diào)
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
}
// 接收到重定向時(shí)會(huì)回調(diào)
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation {
}
// 導(dǎo)航失敗時(shí)會(huì)回調(diào)
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}
// 頁面內(nèi)容到達(dá)main frame時(shí)回調(diào)
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation {
}
// 導(dǎo)航完成時(shí),會(huì)回調(diào)(也就是頁面載入完成了)
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
}
// 導(dǎo)航失敗時(shí)會(huì)回調(diào)
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
}
// 對于HTTPS的都會(huì)觸發(fā)此代理,如果不要求驗(yàn)證,傳默認(rèn)就行
// 如果需要證書驗(yàn)證,與使用AFN進(jìn)行HTTPS證書驗(yàn)證是一樣的
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler {
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
// 9.0才能使用,web內(nèi)容處理中斷時(shí)會(huì)觸發(fā)
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
}
#pragma mark - WKUIDelegate
//需要打開新界面時(shí)
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
//會(huì)攔截到window.open()事件.
//只需要我們在在方法內(nèi)進(jìn)行處理
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
- (void)webViewDidClose:(WKWebView *)webView {
}
// 在JS端調(diào)用alert函數(shù)時(shí),會(huì)觸發(fā)此代理方法。
// JS端調(diào)用alert時(shí)所傳的數(shù)據(jù)可以通過message拿到
// 在原生得到結(jié)果后,需要回調(diào)JS,是通過completionHandler回調(diào)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:NULL];
}
// JS端調(diào)用confirm函數(shù)時(shí),會(huì)觸發(fā)此方法
// 通過message可以拿到JS端所傳的數(shù)據(jù)
// 在iOS端顯示原生alert得到Y(jié)ES/NO后
// 通過completionHandler回調(diào)給JS端
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}]];
[alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}]];
[self presentViewController:alert animated:YES completion:NULL];
}
// JS端調(diào)用prompt函數(shù)時(shí),會(huì)觸發(fā)此方法
// 要求輸入一段文本
// 在原生輸入得到文本內(nèi)容后,通過completionHandler回調(diào)給JS
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:prompt preferredStyle:UIAlertControllerStyleAlert];
[alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.textColor = [UIColor blackColor];
}];
[alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler([[alert.textFields lastObject] text]);
}]];
[self presentViewController:alert animated:YES completion:NULL];
}
#pragma mark - 注入JS
/** 以文件的方式注入JS */
- (void)resgisterJSWithResource:(NSString *)resource ofType:(NSString *)type {
NSBundle *bundle = [NSBundle mainBundle];
NSString *filePath = [bundle pathForResource:resource ofType:type];
NSString *script = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
[self.webView_WK evaluateJavaScript:script completionHandler:nil];
}
/** 以字符串的方式注入JS */
- (void)stringByEvaluatingJavaScriptFromString:(NSString *)script {
[self.webView_WK evaluateJavaScript:script completionHandler:nil];
}
重要的事情只說一遍:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
相當(dāng)于UIWebView中的:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
重要的事情只說一遍:
//需要打開新界面時(shí):必須實(shí)現(xiàn)該代理,否則webView無響應(yīng)
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
//會(huì)攔截到window.open()事件.
//只需要我們在在方法內(nèi)進(jìn)行處理
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}