CDVWebViewDelegate.m 14.6 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
/*
 Licensed to the Apache Software Foundation (ASF) under one
 or more contributor license agreements.  See the NOTICE file
 distributed with this work for additional information
 regarding copyright ownership.  The ASF licenses this file
 to you under the Apache License, Version 2.0 (the
 "License"); you may not use this file except in compliance
 with the License.  You may obtain a copy of the License at

 http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing,
 software distributed under the License is distributed on an
 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 KIND, either express or implied.  See the License for the
 specific language governing permissions and limitations
 under the License.
 */

//
// Testing shows:
//
// In all cases, webView.request.URL is the previous page's URL (or empty) during the didStartLoad callback.
// When loading a page with a redirect:
// 1. shouldStartLoading (requestURL is target page)
// 2. didStartLoading
// 3. shouldStartLoading (requestURL is redirect target)
// 4. didFinishLoad (request.URL is redirect target)
//
// Note the lack of a second didStartLoading **
//
// When loading a page with iframes:
// 1. shouldStartLoading (requestURL is main page)
// 2. didStartLoading
// 3. shouldStartLoading (requestURL is one of the iframes)
// 4. didStartLoading
// 5. didFinishLoad
// 6. didFinishLoad
//
// Note there is no way to distinguish which didFinishLoad maps to which didStartLoad **
//
// Loading a page by calling window.history.go(-1):
// 1. didStartLoading
// 2. didFinishLoad
//
// Note the lack of a shouldStartLoading call **
// Actually - this is fixed on iOS6. iOS6 has a shouldStart. **
//
// Loading a page by calling location.reload()
// 1. shouldStartLoading
// 2. didStartLoading
// 3. didFinishLoad
//
// Loading a page with an iframe that fails to load:
// 1. shouldStart (main page)
// 2. didStart
// 3. shouldStart (iframe)
// 4. didStart
// 5. didFailWithError
// 6. didFinish
//
// Loading a page with an iframe that fails to load due to an invalid URL:
// 1. shouldStart (main page)
// 2. didStart
// 3. shouldStart (iframe)
// 5. didFailWithError
// 6. didFinish
//
// This case breaks our logic since there is a missing didStart. To prevent this,
// we check URLs in shouldStart and return NO if they are invalid.
//
// Loading a page with an invalid URL
// 1. shouldStart (main page)
// 2. didFailWithError
//
// TODO: Record order when page is re-navigated before the first navigation finishes.
//

#import "CDVWebViewDelegate.h"
#import "CDVAvailability.h"

// #define VerboseLog NSLog
#define VerboseLog(...) do {} while (0)

typedef enum {
    STATE_IDLE = 0,
    STATE_WAITING_FOR_LOAD_START = 1,
    STATE_WAITING_FOR_LOAD_FINISH = 2,
    STATE_IOS5_POLLING_FOR_LOAD_START = 3,
    STATE_IOS5_POLLING_FOR_LOAD_FINISH = 4,
    STATE_CANCELLED = 5
} State;

static NSString *stripFragment(NSString* url)
{
    NSRange r = [url rangeOfString:@"#"];

    if (r.location == NSNotFound) {
        return url;
    }
    return [url substringToIndex:r.location];
}

@implementation CDVWebViewDelegate

- (id)initWithDelegate:(NSObject <UIWebViewDelegate>*)delegate
{
    self = [super init];
    if (self != nil) {
        _delegate = delegate;
        _loadCount = -1;
        _state = STATE_IDLE;
    }
    return self;
}

- (BOOL)request:(NSURLRequest*)newRequest isEqualToRequestAfterStrippingFragments:(NSURLRequest*)originalRequest
{
    if (originalRequest.URL && newRequest.URL) {
        NSString* originalRequestUrl = [originalRequest.URL absoluteString];
        NSString* newRequestUrl = [newRequest.URL absoluteString];

        NSString* baseOriginalRequestUrl = stripFragment(originalRequestUrl);
        NSString* baseNewRequestUrl = stripFragment(newRequestUrl);
        return [baseOriginalRequestUrl isEqualToString:baseNewRequestUrl];
    }

    return NO;
}

- (BOOL)isPageLoaded:(UIWebView*)webView
{
    NSString* readyState = [webView stringByEvaluatingJavaScriptFromString:@"document.readyState"];

    return [readyState isEqualToString:@"loaded"] || [readyState isEqualToString:@"complete"];
}

- (BOOL)isJsLoadTokenSet:(UIWebView*)webView
{
    NSString* loadToken = [webView stringByEvaluatingJavaScriptFromString:@"window.__cordovaLoadToken"];

    return [[NSString stringWithFormat:@"%ld", (long)_curLoadToken] isEqualToString:loadToken];
}

- (void)setLoadToken:(UIWebView*)webView
{
    _curLoadToken += 1;
    [webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.__cordovaLoadToken=%ld", (long)_curLoadToken]];
}

- (NSString*)evalForCurrentURL:(UIWebView*)webView
{
    return [webView stringByEvaluatingJavaScriptFromString:@"location.href"];
}

- (void)pollForPageLoadStart:(UIWebView*)webView
{
    if (_state != STATE_IOS5_POLLING_FOR_LOAD_START) {
        return;
    }
    if (![self isJsLoadTokenSet:webView]) {
        VerboseLog(@"Polled for page load start. result = YES!");
        _state = STATE_IOS5_POLLING_FOR_LOAD_FINISH;
        [self setLoadToken:webView];
        if ([_delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
            [_delegate webViewDidStartLoad:webView];
        }
        [self pollForPageLoadFinish:webView];
    } else {
        VerboseLog(@"Polled for page load start. result = NO");
        // Poll only for 1 second, and then fall back on checking only when delegate methods are called.
        ++_loadStartPollCount;
        if (_loadStartPollCount < (1000 * .05)) {
            [self performSelector:@selector(pollForPageLoadStart:) withObject:webView afterDelay:.05];
        }
    }
}

- (void)pollForPageLoadFinish:(UIWebView*)webView
{
    if (_state != STATE_IOS5_POLLING_FOR_LOAD_FINISH) {
        return;
    }
    if ([self isPageLoaded:webView]) {
        VerboseLog(@"Polled for page load finish. result = YES!");
        _state = STATE_IDLE;
        if ([_delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
            [_delegate webViewDidFinishLoad:webView];
        }
    } else {
        VerboseLog(@"Polled for page load finish. result = NO");
        [self performSelector:@selector(pollForPageLoadFinish:) withObject:webView afterDelay:.05];
    }
}

- (BOOL)shouldLoadRequest:(NSURLRequest*)request
{
    NSString* scheme = [[request URL] scheme];

    if ([scheme isEqualToString:@"mailto"] || [scheme isEqualToString:@"tel"]) {
        return YES;
    }

    return [NSURLConnection canHandleRequest:request];
}

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType
{
    BOOL shouldLoad = YES;

    if ([_delegate respondsToSelector:@selector(webView:shouldStartLoadWithRequest:navigationType:)]) {
        shouldLoad = [_delegate webView:webView shouldStartLoadWithRequest:request navigationType:navigationType];
    }

    VerboseLog(@"webView shouldLoad=%d (before) state=%d loadCount=%d URL=%@", shouldLoad, _state, _loadCount, request.URL);

    if (shouldLoad) {
        // When devtools refresh occurs, it blindly uses the same request object. If a history.replaceState() has occured, then
        // mainDocumentURL != URL even though it's a top-level navigation.
        BOOL isDevToolsRefresh = (request == webView.request);
        BOOL isTopLevelNavigation = isDevToolsRefresh || [request.URL isEqual:[request mainDocumentURL]];
        if (isTopLevelNavigation) {
            // Ignore hash changes that don't navigate to a different page.
            // webView.request does actually update when history.replaceState() gets called.
            if ([self request:request isEqualToRequestAfterStrippingFragments:webView.request]) {
                NSString* prevURL = [self evalForCurrentURL:webView];
                if ([prevURL isEqualToString:[request.URL absoluteString]]) {
                    VerboseLog(@"Page reload detected.");
                } else {
                    VerboseLog(@"Detected hash change shouldLoad");
                    return shouldLoad;
                }
            }

            switch (_state) {
                case STATE_WAITING_FOR_LOAD_FINISH:
                    // Redirect case.
                    // We expect loadCount == 1.
                    if (_loadCount != 1) {
//                        NSLog(@"CDVWebViewDelegate: Detected redirect when loadCount=%ld", (long)_loadCount);
                    }
                    break;

                case STATE_IDLE:
                case STATE_IOS5_POLLING_FOR_LOAD_START:
                case STATE_CANCELLED:
                    // Page navigation start.
                    _loadCount = 0;
                    _state = STATE_WAITING_FOR_LOAD_START;
                    break;

                default:
                    {
                        _loadCount = 0;
                        _state = STATE_WAITING_FOR_LOAD_START;
                        NSString* description = [NSString stringWithFormat:@"CDVWebViewDelegate: Navigation started when state=%ld", (long)_state];
//                        NSLog(@"%@", description);
                        if ([_delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
                            NSDictionary* errorDictionary = @{NSLocalizedDescriptionKey : description};
                            NSError* error = [[NSError alloc] initWithDomain:@"CDVWebViewDelegate" code:1 userInfo:errorDictionary];
                            [_delegate webView:webView didFailLoadWithError:error];
                        }
                    }
            }
        } else {
            // Deny invalid URLs so that we don't get the case where we go straight from
            // webViewShouldLoad -> webViewDidFailLoad (messes up _loadCount).
            shouldLoad = shouldLoad && [self shouldLoadRequest:request];
        }
        VerboseLog(@"webView shouldLoad=%d (after) isTopLevelNavigation=%d state=%d loadCount=%d", shouldLoad, isTopLevelNavigation, _state, _loadCount);
    }
    return shouldLoad;
}

- (void)webViewDidStartLoad:(UIWebView*)webView
{
    VerboseLog(@"webView didStartLoad (before). state=%d loadCount=%d", _state, _loadCount);
    BOOL fireCallback = NO;
    switch (_state) {
        case STATE_IDLE:
            if (IsAtLeastiOSVersion(@"6.0")) {
                break;
            }
            // If history.go(-1) is used pre-iOS6, the shouldStartLoadWithRequest function is not called.
            // Without shouldLoad, we can't distinguish an iframe from a top-level navigation.
            // We could try to distinguish using [UIWebView canGoForward], but that's too much complexity,
            // and would work only on the first time it was used.

            // Our work-around is to set a JS variable and poll until it disappears (from a navigation).
            _state = STATE_IOS5_POLLING_FOR_LOAD_START;
            _loadStartPollCount = 0;
            [self setLoadToken:webView];
            [self pollForPageLoadStart:webView];
            break;

        case STATE_CANCELLED:
            fireCallback = YES;
            _state = STATE_WAITING_FOR_LOAD_FINISH;
            _loadCount += 1;
            break;

        case STATE_WAITING_FOR_LOAD_START:
            if (_loadCount != 0) {
//                NSLog(@"CDVWebViewDelegate: Unexpected loadCount in didStart. count=%ld", (long)_loadCount);
            }
            fireCallback = YES;
            _state = STATE_WAITING_FOR_LOAD_FINISH;
            _loadCount = 1;
            break;

        case STATE_WAITING_FOR_LOAD_FINISH:
            _loadCount += 1;
            break;

        case STATE_IOS5_POLLING_FOR_LOAD_START:
            [self pollForPageLoadStart:webView];
            break;

        case STATE_IOS5_POLLING_FOR_LOAD_FINISH:
            [self pollForPageLoadFinish:webView];
            break;

        default:
        {
//            NSLog(@"CDVWebViewDelegate: Unexpected didStart with state=%ld loadCount=%ld", (long)_state, (long)_loadCount);
        }
    }
    VerboseLog(@"webView didStartLoad (after). state=%d loadCount=%d fireCallback=%d", _state, _loadCount, fireCallback);
    if (fireCallback && [_delegate respondsToSelector:@selector(webViewDidStartLoad:)]) {
        [_delegate webViewDidStartLoad:webView];
    }
}

- (void)webViewDidFinishLoad:(UIWebView*)webView
{
    VerboseLog(@"webView didFinishLoad (before). state=%d loadCount=%d", _state, _loadCount);
    BOOL fireCallback = NO;
    switch (_state) {
        case STATE_IDLE:
            break;

        case STATE_WAITING_FOR_LOAD_START:
//            NSLog(@"CDVWebViewDelegate: Unexpected didFinish while waiting for load start.");
            break;

        case STATE_WAITING_FOR_LOAD_FINISH:
            if (_loadCount == 1) {
                fireCallback = YES;
                _state = STATE_IDLE;
            }
            _loadCount -= 1;
            break;

        case STATE_IOS5_POLLING_FOR_LOAD_START:
            [self pollForPageLoadStart:webView];
            break;

        case STATE_IOS5_POLLING_FOR_LOAD_FINISH:
            [self pollForPageLoadFinish:webView];
            break;
    }
    VerboseLog(@"webView didFinishLoad (after). state=%d loadCount=%d fireCallback=%d", _state, _loadCount, fireCallback);
    if (fireCallback && [_delegate respondsToSelector:@selector(webViewDidFinishLoad:)]) {
        [_delegate webViewDidFinishLoad:webView];
    }
}

- (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error
{
    VerboseLog(@"webView didFailLoad (before). state=%d loadCount=%d", _state, _loadCount);
    BOOL fireCallback = NO;

    switch (_state) {
        case STATE_IDLE:
            break;

        case STATE_WAITING_FOR_LOAD_START:
            if ([error code] == NSURLErrorCancelled) {
                _state = STATE_CANCELLED;
            } else {
                _state = STATE_IDLE;
            }
            fireCallback = YES;
            break;

        case STATE_WAITING_FOR_LOAD_FINISH:
            if ([error code] != NSURLErrorCancelled) {
                if (_loadCount == 1) {
                    _state = STATE_IDLE;
                    fireCallback = YES;
                }
                _loadCount = -1;
            } else {
                fireCallback = YES;
                _state = STATE_CANCELLED;
                _loadCount -= 1;
            }
            break;

        case STATE_IOS5_POLLING_FOR_LOAD_START:
            [self pollForPageLoadStart:webView];
            break;

        case STATE_IOS5_POLLING_FOR_LOAD_FINISH:
            [self pollForPageLoadFinish:webView];
            break;
    }
    VerboseLog(@"webView didFailLoad (after). state=%d loadCount=%d, fireCallback=%d", _state, _loadCount, fireCallback);
    if (fireCallback && [_delegate respondsToSelector:@selector(webView:didFailLoadWithError:)]) {
        [_delegate webView:webView didFailLoadWithError:error];
    }
}

@end