iOS UIWebView更换为WKWebView遇到的问题及解

2023-07-12  本文已影响0人  LFBoys

1、JS的alert弹窗没有弹出

参考自https://blog.csdn.net/xiaobo0134/article/details/84190254

#pragma mark -- WKUIDelegate
// 显示一个按钮。点击后调用completionHandler回调
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
 
        completionHandler();
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
}
 
// 显示两个按钮,通过completionHandler回调判断用户点击的确定还是取消按钮
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(YES);
    }]];
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        completionHandler(NO);
    }]];
    [self presentViewController:alertController animated:YES completion:nil];
    
}

2、在一个需要登录的WKWebView中点击按钮,打开新的WKWebView加载内容,提示需要登录

WKProcessPool

在WKWebView中定义了processPool属性,可以指定对应的进程池对象。每个webView都有自己的内容进程,如果不指定则默认是一个新的内容进程。内容进程中包括一些本地cookie、资源之类的,如果不在一个内容进程中,则不能共享这些数据。
可以创建一个公共的WKProcessPool,是一个单例对象。所有webView创建的时候,都使用同一个内容进程,即可实现资源共享。
参考自https://juejin.cn/post/7025420337600790541

    WKWebViewConfiguration* config = [WKWebViewConfiguration new];
    config.preferences = preference;
    config.processPool = _browser.configuration.processPool;
    CGRect rectWeb = CGRectMake(10, 40, rect.size.width - 20, rect.size.height - 50);
    
    WKWebView *webView = [[WKWebView alloc]
                          initWithFrame: rectWeb configuration:config];

3、在新窗口打开链接没有反应

参考自https://www.cnblogs.com/shenyuiOS/p/14747411.html

WKPreferences *preferences = [[WKPreferences alloc] init];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
config.preferences = preferences;

- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (navigationAction.request.URL) {
        [self.webView loadRequest:[NSURLRequest requestWithURL:navigationAction.request.URL]];
    }
    return nil;
}
上一篇下一篇

猜你喜欢

热点阅读