WKWebView 的基础内容可以看我之前写的这篇。WKWebView 基础篇
项目中用到的几个协议:
- WKNavigationDelegate
- WKUIDelegate
- WKScriptMessageHandler
- WKHTTPCookieStoreObserver
- WKURLSchemeHandler
- WKScriptMessageHandlerWithReply
让我们康康都是用来做什么的......
WKNavigationDelegate
接受或拒绝导航更改以及跟踪导航请求进度的方法。
功能有点儿类似 UIWebView 的 UIWebViewDelegate
。例如,可以使用这些方法来限制网页中的特定链接导航,还可以使用它们来跟踪请求的进度,并响应错误和身份验证挑战......等等
一、允许或拒绝一个导航
用到两个常量 WKNavigationActionPolicy
、 WKNavigationResponsePolicy
- 是否允许或拒绝一个导航请求
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;
iOS 13新增了一个接口,需要注意的是,实现了这个方法的话,↑ 的是不会被调用的。
/* 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;
- 是否展示或拒绝一个导航的返回值
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;
二、跟踪请求的加载进度
- 请求开始
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
- 收到服务器的重定向请求
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;
- 已经开始接收主框架的内容
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation;
- 请求已经完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;
三、请求发生错误
- 请求期间发生错误
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
- 请求的早期发生错误
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
- WebView的内容进程终止
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView;
四、身份验证挑战
- 是否回应收到的身份验证质询
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler;
- 询问委托是否继续使用不推荐使用的 TLS 版本的连接, ios(14.0)
- (void)webView:(WKWebView *)webView authenticationChallenge:(NSURLAuthenticationChallenge *)challenge shouldAllowDeprecatedTLS:(void (^)(BOOL))decisionHandler;
WKUIDelegate
代表网页以原生的形式实现一些 UI 元素。
实现这个协议可以:
- 控制新窗口的打开
- 自定义 Alert、多个按钮的 Alert、可以输入文字的 Alert 等等
- 显示上传面板、上下文菜单等
一、JS触发的 Alert
这几个我觉得是最常用也是最基本的几个方法,UIWebView 中是使用浏览器默认实现的样式,但在 WKWebView 中需要自己实现原生的视图。 - 普普通通的 Alert ,由 JS 的
alert
函数触发。
- (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端调用alert时所传的数据可以通过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];
}
- 区分确认/取消的 Alert ,由 JS 的
confirm
函数触发。
- (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的类型是一个布尔
- (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:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
- 带输入框的 Alert,由 JS 的
prompt
函数触发。
一个 prompt 对话框,包含一个单行文本框,一个“取消”按钮,一个“确定”按钮,在对话框关闭时,返回用户输入到文本框内的值(可能为空)。
- (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];
}
二、创建和关闭新的 WebView
- 用一个新的 WKWebView 加载请求、资源,可以通过 JS 的
window.open()
函数或者a
标签触发。
- (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;
}
- 通知你的应用 DOM 窗口的
close()
已经成功调用,也就是 JS 调用了window.close()
这里我理解的是,和上面的原生页面打开方式对应,原生决定怎么关闭页面。
- (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
已经废弃的几个方法,被 ↑ 的替换掉。
- (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 新增-麦克风、摄像头、运动权限
这两个 API 暂时不太清楚是怎么触发的,通过 input 标签反正没作用
- 代表请求麦克风音频和摄像头视频访问权限。
- (void)webView:(WKWebView *)webView requestMediaCapturePermissionForOrigin:(WKSecurityOrigin *)origin initiatedByFrame:(WKFrameInfo *)frame type:(WKMediaCaptureType)type decisionHandler:(void (^)(WKPermissionDecision decision))decisionHandler;
- 允许你的应用程序确定给定的安全源是否可以访问设备的方向和运动。
- (void)webView:(WKWebView *)webView requestDeviceOrientationAndMotionPermissionForOrigin:(WKSecurityOrigin *)origin initiatedByFrame:(WKFrameInfo *)frame decisionHandler:(void (^)(WKPermissionDecision decision))decisionHandler;
WKScriptMessageHandler
用于
接收
JavaScript 发来的消息的消息处理器。
iOS 与 JavaScript 做交互的协议。当 JavaScript 代码发送一条专门针对我们的消息处理程序的消息时,可以通过这个协议的方法来接收,然后自定义后续的处理。
涉及到的类型 WKUserContentController
。基本用法我们在 WKWebView 基础篇
提到过,这里就不重复了。
很简单,就一个方法。干就完了。
- 接收到 script message
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
WKScriptMessageHandlerWithReply
用于
接收
+响应
JavaScript 发来的消息的消息处理器。
ios14.0 新增的协议和 API ,同样是 iOS 与 JavaScript 做交互的协议。不过与 WKScriptMessageHandler
相比,多了一个可以向 JS 发送响应结果的处理器。
也是只有一个 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
用于监听WebView中cookie的变化。
很简单,就一个方法:
@protocol WKHTTPCookieStoreObserver <NSObject>
@optional
- (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore;
@end
上一篇文章我们提到过,与 NSHTTPCookieStorage
的同步操作不同,WKHTTPCookieStore 获取 cookie 是一个异步操作。从 WKHTTPCookieStore
向 NSHTTPCookieStorage
同步 cookie 的话,会发现获取结果有很明显的延迟。太好的办法我也没发现。
- (void)cookiesDidChangeInCookieStore:(WKHTTPCookieStore *)cookieStore {
[cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> * _Nonnull cookies) {
NSLog(@"%s :[%@]", __FUNCTION__, cookies);
for (NSHTTPCookie *cookie in cookies) {
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
}
}];
}