WKWebView 協(xié)議篇

WKWebView 的基礎(chǔ)內(nèi)容可以看我之前寫的這篇。WKWebView 基礎(chǔ)篇

項(xiàng)目中用到的幾個(gè)協(xié)議:

  • WKNavigationDelegate
  • WKUIDelegate
  • WKScriptMessageHandler
  • WKHTTPCookieStoreObserver
  • WKURLSchemeHandler
  • WKScriptMessageHandlerWithReply

讓我們康康都是用來做什么的......

WKNavigationDelegate

接受或拒絕導(dǎo)航更改以及跟蹤導(dǎo)航請(qǐng)求進(jìn)度的方法。

功能有點(diǎn)兒類似 UIWebView 的 UIWebViewDelegate。例如,可以使用這些方法來限制網(wǎng)頁(yè)中的特定鏈接導(dǎo)航,還可以使用它們來跟蹤請(qǐng)求的進(jìn)度,并響應(yīng)錯(cuò)誤和身份驗(yàn)證挑戰(zhàn)......等等

一、允許或拒絕一個(gè)導(dǎo)航
用到兩個(gè)常量 WKNavigationActionPolicyWKNavigationResponsePolicy

  • 是否允許或拒絕一個(gè)導(dǎo)航請(qǐng)求
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;

iOS 13新增了一個(gè)接口,需要注意的是,實(shí)現(xiàn)了這個(gè)方法的話,↑ 的是不會(huì)被調(diào)用的。

/*  iOS 13
    @discussion If you implement this method,
    -webView:decidePolicyForNavigationAction:decisionHandler: will not be called.
 */
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction preferences:(WKWebpagePreferences *)preferences decisionHandler:(void (^)(WKNavigationActionPolicy, WKWebpagePreferences *))decisionHandler;
  • 是否展示或拒絕一個(gè)導(dǎo)航的返回值
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;

二、跟蹤請(qǐng)求的加載進(jìn)度

  • 請(qǐng)求開始
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
  • 收到服務(wù)器的重定向請(qǐng)求
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
  • 已經(jīng)開始接收主框架的內(nèi)容
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation;
  • 請(qǐng)求已經(jīng)完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;

三、請(qǐng)求發(fā)生錯(cuò)誤

  • 請(qǐng)求期間發(fā)生錯(cuò)誤
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
  • 請(qǐng)求的早期發(fā)生錯(cuò)誤
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
  • WebView的內(nèi)容進(jìn)程終止
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView;

四、身份驗(yàn)證挑戰(zhàn)

  • 是否回應(yīng)收到的身份驗(yàn)證質(zhì)詢
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler;
  • 詢問委托是否繼續(xù)使用不推薦使用的 TLS 版本的連接, ios(14.0)
- (void)webView:(WKWebView *)webView authenticationChallenge:(NSURLAuthenticationChallenge *)challenge shouldAllowDeprecatedTLS:(void (^)(BOOL))decisionHandler;

WKUIDelegate

代表網(wǎng)頁(yè)以原生的形式實(shí)現(xiàn)一些 UI 元素。

實(shí)現(xiàn)這個(gè)協(xié)議可以:

  • 控制新窗口的打開
  • 自定義 Alert、多個(gè)按鈕的 Alert、可以輸入文字的 Alert 等等
  • 顯示上傳面板、上下文菜單等
    一、JS觸發(fā)的 Alert
    這幾個(gè)我覺得是最常用也是最基本的幾個(gè)方法,UIWebView 中是使用瀏覽器默認(rèn)實(shí)現(xiàn)的樣式,但在 WKWebView 中需要自己實(shí)現(xiàn)原生的視圖。
  • 普普通通的 Alert ,由 JS 的 alert 函數(shù)觸發(fā)。
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;

例如:

alert("逗你玩兒~");

=>

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {     
// JS端調(diào)用alert時(shí)所傳的數(shù)據(jù)可以通過message拿到,message = 逗你玩兒   
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];    
    UIAlertAction *a = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {        
        completionHandler();    
    }];    
    [alert addAction:a];    
    [self presentViewController:alert animated:YES completion:nil];
}
  • 區(qū)分確認(rèn)/取消的 Alert ,由 JS 的 confirm 函數(shù)觸發(fā)。
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler;

例如:

function logout() {
    if (window.confirm("Do you really want to leave?")) {
        alert("Thanks for Visiting!");
    } else {
        alert("I love you!");
    }
}

=>

//(void (^)(BOOL))completionHandler Block 返回給JS的類型是一個(gè)布爾
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) { 
        completionHandler(NO);    
    }])]; 
    [alertController addAction:([UIAlertAction actionWithTitle:@"確認(rèn)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { 
        completionHandler(YES);    
    }])];       
    [self presentViewController:alertController animated:YES completion:nil];
}
  • 帶輸入框的 Alert,由 JS 的 prompt 函數(shù)觸發(fā)。
    一個(gè) prompt 對(duì)話框,包含一個(gè)單行文本框,一個(gè)“取消”按鈕,一個(gè)“確定”按鈕,在對(duì)話框關(guān)閉時(shí),返回用戶輸入到文本框內(nèi)的值(可能為空)。
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler;

例如:

function testPrompt() {
    var sign = prompt("你是什么星座的?", "告訴我吧~");
    if (sign == "天蝎座") {
        alert("哇! 我跟天蝎座犯沖!");
    } else {
        alert("好吧,我是射手座!");
    }
}

=>

//prompt = 你是什么星座的?; defaultText = 告訴我吧~
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:defaultText 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];
}

二、創(chuàng)建和關(guān)閉新的 WebView

  • 用一個(gè)新的 WKWebView 加載請(qǐng)求、資源,可以通過 JS 的 window.open() 函數(shù)或者 a 標(biāo)簽觸發(fā)。
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures;

例如:

window.open('https://baidu.com');

=>

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {    
    if (!navigationAction.targetFrame.isMainFrame) {        
        WKWebView* v = [[WKWebView alloc] initWithFrame:webView.frame configuration:configuration];        
        v.UIDelegate = webView.UIDelegate;        
        v.navigationDelegate = webView.navigationDelegate;        
        UIViewController* vc = [[UIViewController alloc] init];        
        vc.modalPresentationStyle = UIModalPresentationOverCurrentContext;        
        vc.view = v;        
        [self presentViewController:vc animated:YES completion:nil];                
        return v;    
    }    
    return nil;
}
  • 通知你的應(yīng)用 DOM 窗口的 close() 已經(jīng)成功調(diào)用,也就是 JS 調(diào)用了 window.close()
    這里我理解的是,和上面的原生頁(yè)面打開方式對(duì)應(yīng),原生決定怎么關(guān)閉頁(yè)面。
- (void)webViewDidClose:(WKWebView *)webView;

三、上下文菜單
不是太熟悉。

- (void)webView:(WKWebView *)webView contextMenuWillPresentForElement:(WKContextMenuElementInfo *)elementInfo;- (void)webView:(WKWebView *)webView contextMenuForElement:(WKContextMenuElementInfo *)elementInfo willCommitWithAnimator:(id<UIContextMenuInteractionCommitAnimating>)animator;- (void)webView:(WKWebView *)webView contextMenuConfigurationForElement:(WKContextMenuElementInfo *)elementInfo completionHandler:(void (^)(UIContextMenuConfiguration * _Nullable configuration))completionHandler;- (void)webView:(WKWebView *)webView contextMenuDidEndForElement:(WKContextMenuElementInfo *)elementInfo;

四、iOS10 - iOS13
已經(jīng)廢棄的幾個(gè)方法,被 ↑ 的替換掉。

- (BOOL)webView:(WKWebView *)webView shouldPreviewElement:(WKPreviewElementInfo *)elementInfo WK_API_DEPRECATED_WITH_REPLACEMENT("webView:contextMenuConfigurationForElement:completionHandler:", ios(10.0, 13.0));
- (nullable UIViewController *)webView:(WKWebView *)webView previewingViewControllerForElement:(WKPreviewElementInfo *)elementInfo defaultActions:(NSArray<id <WKPreviewActionItem>> *)previewActions WK_API_DEPRECATED_WITH_REPLACEMENT("webView:contextMenuConfigurationForElement:completionHandler:", ios(10.0, 13.0));
- (void)webView:(WKWebView *)webView commitPreviewingViewController:(UIViewController *)previewingViewController WK_API_DEPRECATED_WITH_REPLACEMENT("webView:contextMenuForElement:willCommitWithAnimator:", ios(10.0, 13.0));

五、iOS 15 新增-麥克風(fēng)、攝像頭、運(yùn)動(dòng)權(quán)限
這兩個(gè) API 暫時(shí)不太清楚是怎么觸發(fā)的,通過 input 標(biāo)簽反正沒作用

  • 代表請(qǐng)求麥克風(fēng)音頻和攝像頭視頻訪問權(quán)限。
- (void)webView:(WKWebView *)webView requestMediaCapturePermissionForOrigin:(WKSecurityOrigin *)origin initiatedByFrame:(WKFrameInfo *)frame type:(WKMediaCaptureType)type decisionHandler:(void (^)(WKPermissionDecision decision))decisionHandler;
  • 允許你的應(yīng)用程序確定給定的安全源是否可以訪問設(shè)備的方向和運(yùn)動(dòng)。
- (void)webView:(WKWebView *)webView requestDeviceOrientationAndMotionPermissionForOrigin:(WKSecurityOrigin *)origin initiatedByFrame:(WKFrameInfo *)frame decisionHandler:(void (^)(WKPermissionDecision decision))decisionHandler;

WKScriptMessageHandler

用于 接收 JavaScript 發(fā)來的消息的消息處理器。

iOS 與 JavaScript 做交互的協(xié)議。當(dāng) JavaScript 代碼發(fā)送一條專門針對(duì)我們的消息處理程序的消息時(shí),可以通過這個(gè)協(xié)議的方法來接收,然后自定義后續(xù)的處理。
涉及到的類型 WKUserContentController。基本用法我們?cè)?WKWebView 基礎(chǔ)篇 提到過,這里就不重復(fù)了。
很簡(jiǎn)單,就一個(gè)方法。干就完了。

  • 接收到 script message
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;

WKScriptMessageHandlerWithReply

用于 接收響應(yīng) JavaScript 發(fā)來的消息的消息處理器。

ios14.0 新增的協(xié)議和 API ,同樣是 iOS 與 JavaScript 做交互的協(xié)議。不過與 WKScriptMessageHandler 相比,多了一個(gè)可以向 JS 發(fā)送響應(yīng)結(jié)果的處理器。
也是只有一個(gè) API 。

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message replyHandler:(void (^)(id _Nullable reply, NSString *_Nullable errorMessage))replyHandler;

例如:

function scriptMessageWithReply() {
    let promise = window.webkit.messageHandlers.YYWK.postMessage("Fulfill me with 42");
    promise.then(
        function(result) {
            alert('result' + result)
        },
        function(error) {
            alert('error' + error)
        }
    );
}

=>

{  
WKUserContentController *userContentController = [[WKUserContentController alloc] init]; 
[userContentController addScriptMessageHandlerWithReply:self contentWorld:[WKContentWorld pageWorld] name:@"YYWK"];  
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];  
configuration.userContentController = userContentController;  
...
}
... 
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message replyHandler:(void (^)(id _Nullable reply, NSString *_Nullable errorMessage))replyHandler {    
    if ([message.body isEqual:@"Fulfill me with 42"])        
        replyHandler(@42, nil);    
    else        
        replyHandler(nil, @"Unexpected message received");
}

WKHTTPCookieStoreObserver

用于監(jiān)聽WebView中cookie的變化。

很簡(jiǎn)單,就一個(gè)方法:

@protocol WKHTTPCookieStoreObserver <NSObject>
@optional
- (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore;
@end

上一篇文章我們提到過,與 NSHTTPCookieStorage 的同步操作不同,WKHTTPCookieStore 獲取 cookie 是一個(gè)異步操作。從 WKHTTPCookieStoreNSHTTPCookieStorage 同步 cookie 的話,會(huì)發(fā)現(xiàn)獲取結(jié)果有很明顯的延遲。太好的辦法我也沒發(fā)現(xiàn)。

- (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore {
    [cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> * _Nonnull cookies) {
        NSLog(@"%s :[%@]", __FUNCTION__, cookies);      
        for (NSHTTPCookie *cookie in cookies) {           
             [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];        
        }    
    }];
}

WKURLSchemeHandler

關(guān)于 WKWebView 的幾篇文章:

WKWebView 基礎(chǔ)篇
WKWebView 協(xié)議篇

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容