shouldStartLoadWithRequest 在 webViewDidFinishLoad 之后调用 -Objective C

shouldStartLoadWithRequest is called after webViewDidFinishLoad -Objective C

在我的 webView 的委托方法中,我使用以下代码检查 webview 加载完全完成时的情况:

if ([[webView stringByEvaluatingJavaScriptFromString:@"document.readyState"] isEqualToString:@"complete"]) {

    //Code to handle other things

    //Sometimes after this block shouldStartLoadWithRequest is called

}

有时甚至控制会转到 if 块,即使这样 -shouldStartLoadWithRequest 正在调用此方法并且我的代码中断。

他们还有其他选择吗?我也试过 webview.isLoading 但这也不起作用。

您可以使用 javascript 和 userContentController 作为一种方式,让您的页面向您的本机代码发送消息,表明它已加载并准备就绪。当您设置 WkWebView 时,像这样设置处理程序:

WKWebViewConfiguration *theConfiguration = [[WKWebViewConfiguration alloc] init];
WKUserContentController *controller = [[WKUserContentController alloc] init];
[controller addScriptMessageHandler:self name:@"observe"];
theConfiguration.userContentController = controller;
CGRect statusBarFrame = [UIApplication sharedApplication].statusBarFrame;
CGRect frame = self.view.frame;
frame.origin.y = statusBarFrame.size.height;
frame.size.height -= statusBarFrame.size.height;
self.primaryWebView = [[WKWebView alloc] initWithFrame:frame configuration:theConfiguration];

然后向您的 ViewController 添加一个名为 userContentController 的方法,如下所示:

- (void)userContentController:(WKUserContentController *)userContentController
    didReceiveScriptMessage:(WKScriptMessage *)message {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // Check the details in message.body for what your javascript said
        NSLog(@"javascript message: %@", message.body);
    });
}

我找到了一种解决方法,可以在 didFinishLoading 之后停止进一步执行脚本。

我使用以下条件来停止请求:

 - (BOOL)webView:(UIWebView *)webView
 shouldStartLoadWithRequest:(NSURLRequest *)request
 navigationType:(UIWebViewNavigationType)navigationType
  {
    if(navigationType == UIWebViewNavigationTypeLinkClicked)
   {
     //my code
    }
  }