wkwebview 代理介紹


iOS 8引入了一個新的框架——WebKit,之后變得好起來了。在WebKit框架中,有WKWebView可以替換UIKit的UIWebView和AppKit的WebView,而且提供了在兩個平台可以一致使用的接口。 WebKit框架使得開發者可以在原生App中使用Nitro來提高網頁的性能和表現,Nitro就是Safari的JavaScript引擎。

WebKit 介紹

下面舉個🌰

代碼中有詳細的注釋

// // ViewController.m // WKWebView01 // // Created by njdby on 16/7/8. // Copyright © 2016年 njdby. All rights reserved. // #import "ViewController.h" #import <WebKit/WebKit.h> @interface ViewController ()<WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler> @property (nonatomic, strong) WKWebView *webView; @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init]; // 設置偏好設置 config.preferences = [[WKPreferences alloc] init]; // 默認為0 config.preferences.minimumFontSize = 10; // 默認認為YES config.preferences.javaScriptEnabled = YES; // 在iOS上默認為NO,表示不能自動通過窗口打開 config.preferences.javaScriptCanOpenWindowsAutomatically = NO; // web內容處理池,由於沒有屬性可以設置,也沒有方法可以調用,不用手動創建 config.processPool = [[WKProcessPool alloc] init]; // 通過JS與webview內容交互 config.userContentController = [[WKUserContentController alloc] init]; // 注入JS對象名稱AppModel,當JS通過AppModel來調用時, // 我們可以在WKScriptMessageHandler代理中接收到 [config.userContentController addScriptMessageHandler:self name:@"AppModel"]; self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config]; [self.view addSubview:self.webView]; // 導航代理 self.webView.navigationDelegate = self; // 與webview UI交互代理 self.webView.UIDelegate = self; // [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"https://www.baidu.com"]]]; NSURL *path = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"]; [self.webView loadRequest:[NSURLRequest requestWithURL:path]]; // 添加KVO監聽 [self.webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil]; [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil]; } #pragma mark - WKUIDelegate #if __IPHONE_OS_VERSION_MAX_ALLOWED > __IPHONE_9_0 - (void)webViewDidClose:(WKWebView *)webView { NSLog(@"%s", __FUNCTION__); } #endif // 創建一個新的WebView(標簽帶有 target='_blank' 時,導致WKWebView無法加載點擊后的網頁的問題。) - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures { // 接口的作用是打開新窗口委托 WKFrameInfo *frameInfo = navigationAction.targetFrame; if (![frameInfo isMainFrame]) { [webView loadRequest:navigationAction.request]; } return nil; } // 在JS端調用alert函數時,會觸發此代理方法。 // JS端調用alert時所傳的數據可以通過message拿到 // 在原生得到結果后,需要回調JS,是通過completionHandler回調 - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler { NSLog(@"%s", __FUNCTION__); UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS調用alert" preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler(); }]]; [self presentViewController:alert animated:YES completion:NULL]; NSLog(@"%@", message); } // JS端調用confirm函數時,會觸發此方法 // 通過message可以拿到JS端所傳的數據 // 在iOS端顯示原生alert得到YES/NO后 // 通過completionHandler回調給JS端 - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler { NSLog(@"%s", __FUNCTION__); UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS調用confirm" 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]; NSLog(@"%@", message); } // JS端調用prompt函數時,會觸發此方法 // 要求輸入一段文本 // 在原生輸入得到文本內容后,通過completionHandler回調給JS - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler { NSLog(@"%s", __FUNCTION__); NSLog(@"%@", prompt); UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS調用輸入框" preferredStyle:UIAlertControllerStyleAlert]; [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.textColor = [UIColor redColor]; }]; [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { completionHandler([[alert.textFields lastObject] text]); }]]; [self presentViewController:alert animated:YES completion:NULL]; } #pragma mark - WKNavigationDelegate #pragma mark - WKNavigationDelegate /** * 在發送請求之前,決定是否跳轉 * * @param webView 實現該代理的 * @param navigationAction 當前navigation * @param decisionHandler 是否調轉block */ - (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSString *hostname = navigationAction.request.URL.host.lowercaseString; if (navigationAction.navigationType == WKNavigationTypeLinkActivated && ![hostname containsString:@".baidu.com"]) { // 對於跨域,需要手動跳轉 [[UIApplication sharedApplication] openURL:navigationAction.request.URL]; // 不允許web內跳轉 decisionHandler(WKNavigationActionPolicyCancel); } else { self.progressView.alpha = 1.0; decisionHandler(WKNavigationActionPolicyAllow); } NSLog(@"%s", __FUNCTION__); } /** * 在收到響應后,決定是否跳轉 * * @param webView 實現該代理的webview * @param navigationResponse 當前navigation * @param decisionHandler 是否跳轉block */ - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { // NSLog(@"%@",navigationResponse.response); // 如果響應的地址是百度,則允許跳轉 // if ([navigationResponse.response.URL.host.lowercaseString isEqual:@"www.baidu.com"]) { // // // 允許跳轉 // decisionHandler(WKNavigationResponsePolicyAllow); // return; // } // // 不允許跳轉 // decisionHandler(WKNavigationResponsePolicyCancel); decisionHandler(WKNavigationResponsePolicyAllow); } /** * 頁面開始加載時調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation */ - (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"%s", __FUNCTION__); } /** * 接收到服務器跳轉請求之后調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation */ - (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"%s", __FUNCTION__); } /** * 加載失敗時調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation * @param error 錯誤 */ - (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { NSLog(@"%s", __FUNCTION__); } /** * 當內容開始返回時調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation */ - (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"%s", __FUNCTION__); } /** * 頁面加載完成之后調用 * * @param webView 實現該代理的webview * @param navigation 當前navigation */ - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation { NSLog(@"%s", __FUNCTION__); } // 導航失敗時會回調 - (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error { } // 對於HTTPS的都會觸發此代理,如果不要求驗證,傳默認就行 // 如果需要證書驗證,與使用AFN進行HTTPS證書驗證是一樣的 - (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *__nullable credential))completionHandler { NSLog(@"%s", __FUNCTION__); completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil); } // 9.0才能使用,web內容處理中斷時會觸發 - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView { NSLog(@"%s", __FUNCTION__); } // 從web界面中接收到一個腳本時調用 #pragma mark - WKScriptMessageHandler - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { if ([message.name isEqualToString:@"AppModel"]) { // 打印所傳過來的參數,只支持NSNumber, NSString, NSDate, NSArray, // NSDictionary, and NSNull類型 NSLog(@"======>%@", message.body); } } #pragma mark - KVO - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context { if ([keyPath isEqualToString:@"loading"]) { NSLog(@"loading"); } else if ([keyPath isEqualToString:@"title"]) { self.title = self.webView.title; } else if ([keyPath isEqualToString:@"estimatedProgress"]) { NSLog(@"progress: %f", self.webView.estimatedProgress); self.progressView.progress = self.webView.estimatedProgress; } // 加載完成 if (!self.webView.loading) { // 手動調用JS代碼 // 每次頁面完成都彈出來,大家可以在測試時再打開 NSString *js = @"callJsAlert()"; [self.webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) { NSLog(@"response: %@ error: %@", response, error); NSLog(@"call js alert by native"); }]; NSString *jsData = @"calltoValue('參數')"; [self.webView evaluateJavaScript:jsData completionHandler:^(id _Nullable response, NSError * _Nullable error) { NSLog(@"response: %@ error: %@", response, error); NSLog(@"------->call js alert by native"); }]; [UIView animateWithDuration:0.5 animations:^{ self.progressView.alpha = 0; }]; } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
<!DOCTYPE html> <html> <head> <title>iOS and Js</title> <style type="text/css"> * { font-size: 40px; } </style> </head> <body> <div style="margin-top: 100px"> <h1>Test how to use objective-c call js</h1><br/> <div><input type="button" value="call js alert" onclick="callJsAlert()"></div> <br/> <div><input type="button" value="Call js confirm" onclick="callJsConfirm()"></div><br/> </div> <br/> <div> <div><input type="button" value="Call Js prompt " onclick="callJsInput()"></div><br/> <div>Click me here: <a href="http://www.baidu.com">Jump to Baidu</a></div> </div> <br/> <div id="SwiftDiv"> <span id="jsParamFuncSpan" style="color: red; font-size: 50px;"></span> </div> <script type="text/javascript"> function callJsAlert() { alert('Objective-C call js to show alert'); window.webkit.messageHandlers.AppModel.postMessage({body: 'call js alert in js'}); } function callJsConfirm() { if (confirm('confirm', 'Objective-C call js to show confirm')) { document.getElementById('jsParamFuncSpan').innerHTML = 'true'; } else { document.getElementById('jsParamFuncSpan').innerHTML = 'false'; } // AppModel是我們所注入的對象 window.webkit.messageHandlers.AppModel.postMessage({body: 'call js confirm in js'}); } function calltoValue(data){ window.webkit.messageHandlers.AppModel.postMessage({body:data}) } function callJsInput() { var response = prompt('Hello', 'Please input your name:'); document.getElementById('jsParamFuncSpan').innerHTML = response; // AppModel是我們所注入的對象 window.webkit.messageHandlers.AppModel.postMessage({body: response}); } </script> </body> </html>



文/Ylang(簡書作者)
原文鏈接:http://www.jianshu.com/p/b9728204e5f9
著作權歸作者所有,轉載請聯系作者獲得授權,並標注“簡書作者”。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM