WKWebView中经常用到的操作
生活随笔
收集整理的這篇文章主要介紹了
WKWebView中经常用到的操作
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
WKWebView相對UIWebView的直觀優勢
- 更多的支持HTML5的特性
- 官方宣稱的高達60fps的滾動刷新率以及內置手勢
- 占用更少的內存
現在總結一下我們用WKWebView時經常用到的一些操作
頁面允許跳轉與取消
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{if (navigationAction.targetFrame == nil) {[webView loadRequest:navigationAction.request];}if ([navigationAction.request.URL.absoluteString containsString:@"wexin://"]){ //當url中存在weixin://時不進行頁面跳轉,進行其它操作//TODO: 做一些其它操作decisionHandler(WKNavigationActionPolicyCancel);}else{decisionHandler(WKNavigationActionPolicyAllow);} } 復制代碼WK與JS交互
//**********WK與JS交互********** //配置 - (WKWebViewConfiguration *)configuration{if (!_configuration) {_configuration = [[WKWebViewConfiguration alloc] init];WKUserContentController *userContentController = [[WKUserContentController alloc] init];//jumpQRCode是和JS約定好的字符串,保證JS調用OC時判斷相同就行,沒有具體限制[userContentController addScriptMessageHandler:self name:@"jumpQRCode"]; _configuration.userContentController = userContentController;self.webView.configuration = _configuration;}return _configuration; } //JS調用OC - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{if ([message.name isEqualToString:@"openQRCode”]) {[self openQRCode];} } - (void)openQRCode{ //OC調用JS NSString *JSResult = [NSString stringWithFormat:@"callback('%@','%@')", index,strScan]; //JS方法名和參數 [self.webView evaluateJavaScript:JSResult completionHandler:^(id _Nullable result, NSError * _Nullable error) {NSLog(@"完成...."); }]; }復制代碼WKWebView加載Webp
Cookie丟失
NSString *cookieStr = [self setJSCookie]; WKUserScript *cookieScipt = [[WKUserScript alloc] initWithSource:cookieStr injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO]; WKUserContentController *wku = [[WKUserContentController alloc] init]; [wku addScriptMessageHandler:self name:@"openPay"]; [wku addUserScript:cookieScipt];-(NSString *)setJSCookie{NSMutableDictionary *cookiesDic = [[LFCacheTool lf_getCacheObjectFromKey:COOKIES] mutableCopy];__block NSString *cookieStr = @"";[cookiesDic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {NSDictionary *dic = obj;NSString *appendString;if ([self.url rangeOfString:@"丟失cookie的鏈接"].location != NSNotFound){//根據后臺需要的樣式修改cookie(多參數少參數都可能獲取失敗)appendString= [NSString stringWithFormat:@"'%@=%@;path=/;domain=%@';",key, dic[@"Value"],@"丟失cookie的鏈接"];}cookieStr = [NSString stringWithFormat:@"%@document.cookie=%@",cookieStr,appendString];}];return cookieStr; }復制代碼總結
以上是生活随笔為你收集整理的WKWebView中经常用到的操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 登录框显示,错误:Cookies因预料之
- 下一篇: 简单的DPDK介绍与分析