WKWebView的屬性cookie同步撰洗、alert不彈出等問(wèn)題
零段直、WKWebView屬性
1泡挺、基本屬性
代理:WKUIDelegate,WKNavigationDelegate(代理方法見(jiàn)后面)
//進(jìn)行配置控制器
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
//實(shí)例化對(duì)象
configuration.userContentController = [WKUserContentController new];
//JS調(diào)用OC方法注冊(cè),在dealloc方法中必須移除桨嫁,否則內(nèi)存泄露
[configuration.userContentController addScriptMessageHandler:self name:@"appShareIOS"];
//允許視頻播放(默認(rèn)是YES)
configuration.allowsAirPlayForMediaPlayback = YES;
// 允許在線播放(默認(rèn)是YES)
configuration.allowsInlineMediaPlayback = YES;
// 允許可以與網(wǎng)頁(yè)交互乙各,選擇視圖
configuration.selectionGranularity = YES;
// 是否支持記憶讀取
configuration.suppressesIncrementalRendering = YES;
// 創(chuàng)建設(shè)置屬性對(duì)象
WKPreferences *preference = [[WKPreferences alloc]init];
// 設(shè)置字體大小(最小的字體大小)
preference.minimumFontSize = 40;
// 設(shè)置偏好設(shè)置對(duì)象
configuration.preferences = preference;
_webView = [[HtmlWKWebView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, SCREEN_HEIGHT-64) configuration:configuration];
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
//開(kāi)啟手勢(shì)觸摸
_webView.allowsBackForwardNavigationGestures = YES;
// 設(shè)置 可以前進(jìn) 和 后退
//適應(yīng)你設(shè)定的尺寸
[_webView sizeToFit];
//注意飒货!注意匾荆!注意:上面將當(dāng)前ViewController設(shè)置為MessageHandler之后需要在當(dāng)前ViewController銷毀前將其移除俯在,否則會(huì)造成內(nèi)存泄漏搔确。
-(void)dealloc{
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"appShareIOS"];
}
2彼棍、禁止頁(yè)面一些操作,在網(wǎng)頁(yè)加載完時(shí)寫入(didFinishNavigation)
//頁(yè)面加載完后獲取高度
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
(1) 禁用 頁(yè)面元素選擇
[_webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
}];
(2) 禁用 長(zhǎng)按彈出ActionSheet
[_webView evaluateJavaScript:@"document.documentElement.style.webkitTouchCallout='none';" completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
}];
(3) WKWebView禁止放大縮小(捏合手勢(shì))
NSString *injectionJSString = @"var script = document.createElement('meta');"
"script.name = 'viewport';"
"script.content=\"width=device-width, initial-scale=1.0,maximum-scale=1.0, minimum-scale=1.0, user-scalable=no\";"
"document.getElementsByTagName('head')[0].appendChild(script);";
[webView evaluateJavaScript:injectionJSString completionHandler:nil];
(4)清除WK緩存膳算,否則H5界面跟新座硕,這邊不會(huì)更新
if ([UIDevice currentDevice].systemVersion.floatValue>=9.0) {
// - (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation 中就成功了 。
// 然而我們等到了iOS9L榉洹;摇!沒(méi)錯(cuò)机隙!WKWebView的緩存清除API出來(lái)了蜘拉!代碼如下:這是刪除所有緩存和cookie的
NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
//// Date from
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
//// Execute
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
}];
}else{
//iOS8清除緩存
NSString * libraryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
NSString * cookiesFolderPath = [libraryPath stringByAppendingString:@"/Cookies"];
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:nil];
}
(5)獲取網(wǎng)頁(yè)高度
[webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id Result, NSError * error) {
dispatch_async(dispatch_get_main_queue(), ^{
CGFloat documentHeight = [Result doubleValue]+15.00;
// NSLog(@"高度%f",documentHeight);
// [DWBToast showCenterWithText:[NSString stringWithFormat:@"%f",documentHeight]];
if (self.htmlString.length>0) {
//啥也不干
}else{
documentHeight = 0.0;
}
_footView.frame = CGRectMake(0, documentHeight-self.footView.frame.size.height, SCREEN_WIDTH, self.footView.frame.size.height);
//加載完設(shè)置好坐標(biāo)打開(kāi)
_footView.hidden = NO;
});
}];
}
一、WKWebView - alert不彈出(這是WKWebView相對(duì)于UIWebView的一個(gè)坑)
#pragma mark======================WKWebView - alert不彈出(這是WKWebView相對(duì)于UIWebView的一個(gè)坑)===========================================
//WKWebView默認(rèn)不響應(yīng)js的alert()事件,如何可以開(kāi)啟alert權(quán)限呢?
//設(shè)置wkwebview.delegate = self;
//實(shí)現(xiàn)下面三個(gè)方法:
- (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:@"確認(rèn)" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}])];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
// DLOG(@"msg = %@ frmae = %@",message,frame);
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);
}])];
[[UIApplication sharedApplication].keyWindow.rootViewController 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?:@"");
}])];
[[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:alertController animated:YES completion:nil];
}
二有鹿、WKWebView默認(rèn)禁止了一些跳轉(zhuǎn)
//UIWebView打開(kāi)ituns.apple.com跳轉(zhuǎn)到appStore, 撥打電話, 喚起郵箱等一系列操作UIWebView默認(rèn)支持的.
//WKWebView默認(rèn)禁止了以上行為,除此之外,js端通過(guò)window.open()打開(kāi)新的網(wǎng)頁(yè)的動(dòng)作也被禁掉了.如何支持呢?可以跳轉(zhuǎn)appStore或者撥號(hào)
-(void)webView:(WKWebView* )webView decidePolicyForNavigationAction:(WKNavigationAction* )navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
if(webView != _webView) {
decisionHandler(WKNavigationActionPolicyAllow);
return;
}
UIApplication *app = [UIApplication sharedApplication];
if ([url.scheme isEqualToString:@"tel"])
{
if ([app canOpenURL:url])
{
[app openURL:url];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
}
if ([url.absoluteString containsString:@"ituns.apple.com"])
{
if ([app canOpenURL:url])
{
[app openURL:url];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
}
decisionHandler(WKNavigationActionPolicyAllow);
}
三旭旭、WKWebView代理方法
#pragma mark - WKNavigationDelegate
// 頁(yè)面開(kāi)始加載時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
}
// 內(nèi)容開(kāi)始返回時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
}
// 頁(yè)面加載完成時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
}
// 頁(yè)面加載失敗時(shí)調(diào)用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation {
}
//新增的三個(gè)代理方法:
// 這個(gè)方法是服務(wù)器重定向時(shí)調(diào)用,即 接收到服務(wù)器跳轉(zhuǎn)請(qǐng)求之后調(diào)用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
}
// 在收到響應(yīng)后葱跋,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
}
// 在發(fā)送請(qǐng)求之前持寄,決定是否跳轉(zhuǎn)
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
//需執(zhí)行decisionHandler的block。
}
四娱俺、WKUIDelegate 協(xié)議
#pragma mark - WKUIDelegate
//WKWebView打開(kāi)新界面 需要打開(kāi)新界面是,WKWebView的代理WKUIDelegate方法
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
// 會(huì)攔截到window.open()事件.只需要我們?cè)谠诜椒▋?nèi)進(jìn)行處理
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
/**
* web界面中有彈出警告框時(shí)調(diào)用
*
* @param webView 實(shí)現(xiàn)該代理的webview
* @param message 警告框中的內(nèi)容
* @param frame 主窗口
* @param completionHandler 警告框消失調(diào)用
*/
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(void (^)())completionHandler {
}
/// 輸入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {
}
/// 確認(rèn)框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
}
/// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
}