參考博客:
iOS中UIWebView與WKWebView盗扒、JavaScript與OC交互、Cookie管理看我就夠(中)
iOS UIWebView 和 WKWebView 的 cookie 獲取,設置,刪除
iOS11 WKWebView過濾規(guī)則WKContentRuleListStore
Webview加載H5優(yōu)化小記
iOS 端 h5 頁面秒開優(yōu)化實踐(使用WKURLSchemeHandler)
iOS WKWebView全部API解讀
南華Coder -- WKWebview使用二三事
1缀去、WKWebView
是Apple于iOS 8.0推出的WebKit中的核心控件侣灶,用來替UIWebView。
WKWebView比UIWebView的優(yōu)勢在于:
1缕碎、更多的支持HTML5的特性
2褥影、高達60fps的滾動刷新率以及內置手勢
3、與Safari相同的JavaScript引擎
4咏雌、將UIWebViewDelegate與UIWebView拆分成了14類與3個協(xié)議(官方文檔說明)
5凡怎、更豐富的api與代理方法,比如可以獲取加載進度:estimatedProgress(UIWebView需要調用私有Api)
WKUserContentController
@property (nonatomic, strong) WKUserContentController *userContentController;
@interface WKUserContentController : NSObject <NSCoding>
//讀取添加過的腳本
@property (nonatomic, readonly, copy) NSArray<WKUserScript *> *userScripts;
//添加腳本
- (void)addUserScript:(WKUserScript *)userScript;
//刪除所有添加的腳本
- (void)removeAllUserScripts;
//通過window.webkit.messageHandlers.<name>.postMessage(<messageBody>) 來實現(xiàn)js->oc傳遞消息赊抖,并添加handler
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
//刪除handler
- (void)removeScriptMessageHandlerForName:(NSString *)name;
@end
創(chuàng)建一個WKWebView的代碼如下:
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *controller = [[WKUserContentController alloc] init];
configuration.userContentController = controller;
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
self.webView.allowsBackForwardNavigationGestures = YES; //允許右滑返回上個鏈接统倒,左滑前進
self.webView.allowsLinkPreview = YES; //允許鏈接3D Touch
self.webView.customUserAgent = @"WebViewDemo/1.0.0"; //自定義UA,UIWebView就沒有此功能氛雪,后面會講到通過其他方式實現(xiàn)
self.webView.UIDelegate = self;
self.webView.navigationDelegate = self;
[self.view addSubview:self.webView];
一些屬性
@property (nullable, nonatomic, readonly, copy) NSString *title; //頁面的title房匆,終于可以直接獲取了
@property (nullable, nonatomic, readonly, copy) NSURL *URL; //當前webView的URL
@property (nonatomic, readonly, getter=isLoading) BOOL loading; //是否正在加載
@property (nonatomic, readonly) double estimatedProgress; //加載的進度
@property (nonatomic, readonly) BOOL canGoBack; //是否可以后退,跟UIWebView相同
@property (nonatomic, readonly) BOOL canGoForward; //是否可以前進报亩,跟UIWebView相同
2浴鸿、動態(tài)注入JS
(1)給每個頁面添加一個Cookie
//注入一個Cookie
WKUserScript *newCookieScript = [[WKUserScript alloc] initWithSource:@"document.cookie = 'DarkAngelCookie=DarkAngel;'" injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[controller addUserScript:newCookieScript];
(2)然后再注入一個腳本,每當頁面加載弦追,就會alert當前頁面cookie岳链,在OC中的實現(xiàn)
//創(chuàng)建腳本
WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource:@"alert(document.cookie);" injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:NO];
//添加腳本
[controller addUserScript:script];
(3)注入客戶端的登錄狀態(tài)方法
NSString *app_isLogin = [NSString stringWithFormat:@"function app_isLogin(){return %i}",[ZYXAccountInfoManager sharedManager].isLogin];
WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javaScriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
[self.webView.configuration.userContentController addUserScript:userScript];
3、OC -> JS
[self.webView evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable title, NSError * _Nullable error) {
NSLog(@"調用evaluateJavaScript異步獲取title:%@", title);
}];
4劲件、JS -> OC
1掸哑、URL攔截
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//可以通過navigationAction.navigationType獲取跳轉類型,如新鏈接零远、后退等
NSURL *URL = navigationAction.request.URL;
//判斷URL是否符合自定義的URL Scheme
if ([URL.scheme isEqualToString:@"darkangel"]) {
//根據(jù)不同的業(yè)務苗分,來執(zhí)行對應的操作,且獲取參數(shù)
if ([URL.host isEqualToString:@"smsLogin"]) {
NSString *param = URL.query;
NSLog(@"短信驗證碼登錄, 參數(shù)為%@", param);
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
}
decisionHandler(WKNavigationActionPolicyAllow);
NSLog(@"%@", NSStringFromSelector(_cmd));
}
2遍烦、WKScriptMessageHandler
OC中添加一個WKScriptMessageHandler俭嘁,則會在all frames中添加一個js的function
(1)OC中監(jiān)聽JS的方法
// 監(jiān)聽JS的currentCookies方法
[controller addScriptMessageHandler:self name:@"currentCookies"]; //這里self要遵循協(xié) WKScriptMessageHandler
(2)JS中調用下面的方法時
// JS調用currentCookies的時候寫上這句代碼
window.webkit.messageHandlers.currentCookies.postMessage(document.cookie);
(3)OC中將會收到WKScriptMessageHandler的回調
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"currentCookies"]) {
NSString *cookiesStr = message.body; //message.body返回的是一個id類型的對象,所以可以支持很多種js的參數(shù)類型(js的function除外)
NSLog(@"當前的cookie為: %@", cookiesStr);
}
}
當然服猪,記得在適當?shù)牡胤秸{用removeScriptMessageHandler
- (void)dealloc {
//記得移除
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"currentCookies"];
}
實現(xiàn)JS -> OC的調用供填,并且OC -> JS 異步回調結果拐云,這里還是拿分享來舉個例子
JS
/**
* 分享方法,并且會異步回調分享結果
* @param {對象類型} shareData 一個分享數(shù)據(jù)的對象近她,包含title,imgUrl,link以及一個回調function
* @return {void} 無同步返回值
*/
function shareNew(shareData) {
//用于WKWebView叉瘩,因為WKWebView并沒有辦法把js function傳遞過去,因此需要特殊處理一下
//把js function轉換為字符串粘捎,oc端調用時 (<js function string>)(true); 即可
var result = shareData.result;
shareData.result = result.toString();
window.webkit.messageHandlers.shareNew.postMessage(shareData);
}
function test() {
//清空分享結果
shareResult.innerHTML = "";
//調用時薇缅,應該
shareNew({
title: "title",
imgUrl: "http://img.dd.com/xxx.png",
link: location.href,
result: function(res) {
//這里shareResult 等同于 document.getElementById("shareResult")
shareResult.innerHTML = res ? "success" : "failure";
}
});
}
在html頁面中我定義了一個a標簽來觸發(fā)test()函數(shù)
<a href="javascript:void(0);" onclick="test()">測試新分享</a>
在OC端,實現(xiàn)如下
//首先別忘了攒磨,在configuration中的userContentController中添加scriptMessageHandler
[controller addScriptMessageHandler:self name:@"shareNew"]; //記得適當時候remove哦
//點擊a標簽時泳桦,則會調用下面的方法
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"shareNew"]) {
NSDictionary *shareData = message.body;
NSLog(@"shareNew分享的數(shù)據(jù)為: %@", shareData);
//模擬異步回調
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//讀取js function的字符串
NSString *jsFunctionString = shareData[@"result"];
//拼接調用該方法的js字符串
NSString *callbackJs = [NSString stringWithFormat:@"(%@)(%d);", jsFunctionString, NO]; //后面的參數(shù)NO為模擬分享失敗
//執(zhí)行回調
[self.webView evaluateJavaScript:callbackJs completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (!error) {
NSLog(@"模擬回調,分享失敗");
}
}];
});
}
}
那么當點擊a標簽時過2s娩缰,會顯示failure灸撰。
5、Cookie管理
Cookie設置
(iOS11以前有些問題拼坎,各種方式都使用了浮毯,有些時候Cookie設置不上去)
///給webView注入cookie
if (@available(iOS 11.0, *)) {
WKHTTPCookieStore *cookieStore = self.webView.configuration.websiteDataStore.httpCookieStore;
// 取出保存的Cookie
NSData *data = [[NSUserDefaults standardUserDefaults] objectForKey:@"WKHTTPCookie"];
NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:data];
for (int i=0; i< cookies.count; i++) {
[cookieStore setCookie:cookies[i] completionHandler:nil];
}
} else {
NSString *cookieString = [[NSUserDefaults standardUserDefaults] objectForKey:@"CookieString"];
//cookieString=@"aaaaaa=bbbb";
if (cookieString) {
// 多鐘方式全都寫上,不管了
// (1)第一種方式:request.setHTTPHeaderField
[request setValue:cookieString forHTTPHeaderField:@"Cookie"];
NSString *documentCookieString = [NSString stringWithFormat:@"document.cookie = '%@'",cookieString];
NSURL *targetURL = [NSURL URLWithString:@"https://test130-m.angsi.com"];
// (2)第二種方式
NSArray *headeringCookie = [NSHTTPCookie cookiesWithResponseHeaderFields:@{@"Set-Cookie":documentCookieString} forURL:targetURL];
[[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookies:headeringCookie forURL:targetURL mainDocumentURL:nil];
// (3)第三種方式
WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource: documentCookieString injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
[_webView.configuration.userContentController addUserScript:cookieScript];
}
}
[self.webView loadRequest:request];
Cookie獲取保存
// 頁面加載完成之后調用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//cookies獲取存儲
if (@available(iOS 11.0, *)) {
WKHTTPCookieStore *cookieStore = webView.configuration.websiteDataStore.httpCookieStore;
[cookieStore getAllCookies:^(NSArray<NSHTTPCookie *> * cookies) {
if (cookies.count >0 ) {
// 保存Cookie
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:cookies];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"WKHTTPCookie"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
} else {
// js獲取
[webView evaluateJavaScript:[NSString stringWithFormat:@"document.cookie"] completionHandler:^(id _Nullable response, NSError * _Nullable error) {
if (response != 0) {
[[NSUserDefaults standardUserDefaults] setObject:response forKey:@"CookieString"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}];
}
}
JS彈窗,需要全部現(xiàn)實WKUIDelegate的代理
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:([UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
- (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];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.text = defaultText;
}];
[alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(alertController.textFields[0].text?:@"");
}])];
[self presentViewController:alertController animated:YES completion:nil];
}
6泰鸡、WKURLSchemeHandler實現(xiàn)攔截(iOS11)
攔截加載本地圖片代碼例子
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
[config setURLSchemeHandler:[[SchemeHandler alloc] init] forURLScheme:@"XXXXXScheme"];
NSURL *url = [NSURL URLWithString:@"XXXXXScheme://xxxx"];
NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];
[webView loadRequest:request];
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
@interface SchemeHandler : NSObject<WKURLSchemeHandler>
@end
#import "SchemeHandler.h"
@implementation SchemeHandler
- (void)webView:(WKWebView *)webView startURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask
{
UIImage *image = [UIImage imageNamed:@"photo"];
NSData *data = UIImageJPEGRepresentation(image, 1.0);
// 這里可以換成任何資源:image/jpg债蓝、text/html
[urlSchemeTask didReceiveResponse:[[NSURLResponse alloc] initWithURL:urlSchemeTask.request.URL MIMEType:@"image/jpg" expectedContentLength:data.length textEncodingName:nil]];
[urlSchemeTask didReceiveData:data];
[urlSchemeTask didFinish];
}
- (void)webView:(WKWebView *)webView stopURLSchemeTask:(id <WKURLSchemeTask>)urlSchemeTask;
{
urlSchemeTask = nil;
}
@end
7、使用WKWebView需要注意的地方
1盛龄、Cookie問題
2饰迹、白屏問題
當WKWebView加載的網(wǎng)頁占用內存過大時,會出現(xiàn)白屏現(xiàn)象讯嫂。
解決:
A蹦锋、借助 WKNavigtionDelegate: (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0));回調函數(shù):
當 WKWebView 總體內存占用過大,頁面即將白屏的時候欧芽,系統(tǒng)會調用上面的回調函數(shù),我們在該函數(shù)里執(zhí)行[webView reload](這個時候 webView.URL 取值尚不為 nil)解決白屏問題葛圃。在一些高內存消耗的頁面可能會頻繁刷新當前頁面千扔,H5側也要做相應的適配操作。
// 白屏處理
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView {
[webView reload]; //刷新就好了
}
B库正、檢測 webView.title 是否為空:在WKWebView白屏的時候曲楚,另一種現(xiàn)象是 webView.titile 會被置空, 因此,可以在 viewWillAppear 的時候檢測 webView.title 是否為空來 reload 頁面
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// 白屏處理
if (self.webView.title == nil) {
[self.webView reload];
}
}