UIWebView: when did a page really finish loading?

后端 未结 11 1198
轮回少年
轮回少年 2020-11-29 00:09

I need to know, when a web page has completely been loaded by UIWebView. I mean, really completely, when all redirects are done and dynamically loaded content is ready. I tr

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-29 00:44

    Here's a simplified version of @jasonjwwilliams answer.

    #define JAVASCRIPT_TEST_VARIBLE @"window.IOSVariable"
    #define JAVASCRIPT_TEST_FUNCTION @"IOSFunction"
    #define LOAD_COMPLETED @"loaded"
    
    // Put this in your init method
    // In Javascript, first define the function, then attach it as a listener.
    _javascriptListener = [NSString stringWithFormat:
        @"function %@() {\
             %@ = '%@';\
        };\
        window.addEventListener(\"load\", %@, false);",
            JAVASCRIPT_TEST_FUNCTION, JAVASCRIPT_TEST_VARIBLE, LOAD_COMPLETED, JAVASCRIPT_TEST_FUNCTION];
    
    // Then use this:
    
    - (void)webViewDidFinishLoad:(UIWebView *)webView;
    {
        // Only want to attach the listener and function once.
        if (_javascriptListener) {
            [_webView stringByEvaluatingJavaScriptFromString:_javascriptListener];
            _javascriptListener = nil;
        }
    
        if ([[webView stringByEvaluatingJavaScriptFromString:JAVASCRIPT_TEST_VARIBLE] isEqualToString:LOAD_COMPLETED]) {
            NSLog(@"UIWebView object has fully loaded.");
        }
    }
    

提交回复
热议问题