1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ios/web/web_state/ui/crw_ui_web_view_web_controller.h"
7 #import "base/ios/ns_error_util.h"
8 #import "base/ios/weak_nsobject.h"
9 #include "base/json/json_reader.h"
10 #include "base/json/string_escape.h"
11 #include "base/mac/bind_objc_block.h"
12 #import "base/mac/scoped_nsobject.h"
13 #include "base/memory/scoped_ptr.h"
14 #include "base/metrics/field_trial.h"
15 #include "base/metrics/histogram.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/sys_string_conversions.h"
18 #include "base/timer/timer.h"
19 #include "base/values.h"
20 #import "ios/net/nsurlrequest_util.h"
21 #import "ios/web/navigation/crw_session_controller.h"
22 #import "ios/web/navigation/crw_session_entry.h"
23 #include "ios/web/net/clients/crw_redirect_network_client_factory.h"
24 #import "ios/web/net/crw_url_verifying_protocol_handler.h"
25 #include "ios/web/net/request_group_util.h"
26 #include "ios/web/public/url_scheme_util.h"
27 #include "ios/web/public/web_client.h"
28 #import "ios/web/public/web_state/ui/crw_web_view_content_view.h"
29 #import "ios/web/ui_web_view_util.h"
30 #include "ios/web/web_state/frame_info.h"
31 #import "ios/web/web_state/js/crw_js_invoke_parameter_queue.h"
32 #import "ios/web/web_state/ui/crw_context_menu_provider.h"
33 #import "ios/web/web_state/ui/crw_web_controller+protected.h"
34 #import "ios/web/web_state/ui/crw_web_controller.h"
35 #import "ios/web/web_state/ui/web_view_js_utils.h"
36 #import "ios/web/web_state/web_state_impl.h"
37 #import "ios/web/web_state/web_view_internal_creation_util.h"
38 #import "net/base/mac/url_conversions.h"
39 #include "net/base/net_errors.h"
40 #include "url/url_constants.h"
44 // The following continuous check timer frequency constants are externally
45 // available for the purpose of performance tests.
46 // Frequency for the continuous checks when a reset in the page object is
47 // anticipated shortly. In milliseconds.
48 const int64 kContinuousCheckIntervalMSHigh = 100;
50 // The maximum duration that the CRWWebController can run in high-frequency
51 // check mode before being changed back to the low frequency.
52 const int64 kContinuousCheckHighFrequencyMSMaxDuration = 5000;
54 // Frequency for the continuous checks when a reset in the page object is not
55 // anticipated; checks are only made as a precaution.
56 // The URL could be out of date for this many milliseconds, so this should not
57 // be increased without careful consideration.
58 const int64 kContinuousCheckIntervalMSLow = 3000;
62 @interface CRWUIWebViewWebController () <CRWRedirectClientDelegate,
64 // The UIWebView managed by this instance.
65 base::scoped_nsobject<UIWebView> _uiWebView;
67 // Whether caching of the current URL is enabled or not.
68 BOOL _urlCachingEnabled;
70 // Temporarily cached current URL. Only valid/set while urlCachingEnabled
72 // TODO(stuartmorgan): Change this to a struct so code using it is more
74 std::pair<GURL, web::URLVerificationTrustLevel> _cachedURL;
76 // The last time a URL with absolute trust level was computed.
77 // When an untrusted URL is retrieved from the
78 // |CRWURLVerifyingProtocolHandler|, if the last trusted URL is within
79 // |kContinuousCheckIntervalMSLow|, the trustLevel is upgraded to Mixed.
80 // The reason is that it is sometimes temporarily impossible to do a
81 // AsyncXMLHttpRequest on a web page. When this happen, it is not possible
82 // to check for the validity of the current URL. Because the checker is
83 // only checking every |kContinuousCheckIntervalMSLow| anyway, waiting this
84 // amount of time before triggering an interstitial does not weaken the
85 // security of the browser.
86 base::TimeTicks _lastCorrectURLTime;
88 // Each new UIWebView starts in a state where:
89 // - window.location.href is equal to about:blank
90 // - Ajax requests seem to be impossible
91 // Because Ajax requests are used to determine is a URL is verified, this
92 // means it is impossible to do this check until the UIWebView is in a more
93 // sane state. This variable tracks whether verifying the URL is currently
94 // impossible. It starts at YES when a new UIWebView is created,
95 // and will change to NO, as soon as either window.location.href is not
96 // about:blank anymore, or an URL verification request succeeds. This means
97 // that a malicious site that is able to change the value of
98 // window.location.href and that is loaded as the first request will be able
99 // to change its URL to about:blank. As this is not an interesting URL, it is
100 // considered acceptable.
101 BOOL _spoofableRequest;
103 // Timer used to make continuous checks on the UIWebView. Timer is
104 // running only while |webView| is non-nil.
105 scoped_ptr<base::Timer> _continuousCheckTimer;
106 // Timer to lower the check frequency automatically.
107 scoped_ptr<base::Timer> _lowerFrequencyTimer;
109 // Counts of calls to |-webViewDidStartLoad:| and |-webViewDidFinishLoad|.
110 // When |_loadCount| is equal to |_unloadCount|, the page is no longer
111 // loading. Used as a fallback to determine when the page is done loading in
112 // case document.readyState isn't sufficient.
113 // When |_loadCount| is 1, the main page is loading (as opposed to a
118 // Backs the property of the same name.
119 BOOL _inJavaScriptContext;
121 // Backs the property of the same name.
122 base::scoped_nsobject<CRWJSInvokeParameterQueue> _jsInvokeParameterQueue;
124 // Blocks message queue processing (for testing).
125 BOOL _jsMessageQueueThrottled;
127 // YES if a video is playing in fullscreen.
128 BOOL _inFullscreenVideo;
130 // Backs the property of the same name.
131 id<CRWRecurringTaskDelegate>_recurringTaskDelegate;
133 // Redirect client factory.
134 base::scoped_nsobject<CRWRedirectNetworkClientFactory>
135 redirect_client_factory_;
138 // Whether or not URL caching is enabled. Between enabling and disabling
139 // caching, calls to webURLWithTrustLevel: after the first may return the same
140 // answer without re-checking the URL.
141 @property(nonatomic, setter=setURLCachingEnabled:) BOOL urlCachingEnabled;
143 // Returns whether the current page is the web views initial (default) page.
144 - (BOOL)isDefaultPage;
146 // Returns whether the given navigation is triggered by a user link click.
147 - (BOOL)isLinkNavigation:(UIWebViewNavigationType)navigationType;
149 // Starts (at the given interval) the timer that drives runRecurringTasks to see
150 // whether or not the page has changed. This is used to work around the fact
151 // that UIWebView callbacks are not sufficiently reliable to catch every page
153 - (void)setContinuousCheckTimerInterval:(const base::TimeDelta&)interval;
155 // Evaluates the supplied JavaScript and returns the result. Will return nil
156 // if it is unable to evaluate the JavaScript.
157 - (NSString*)stringByEvaluatingJavaScriptFromString:(NSString*)script;
159 // Evaluates the user-entered JavaScript in the WebView and returns the result.
160 // Will return nil if the web view is currently not available.
161 - (NSString*)stringByEvaluatingUserJavaScriptFromString:(NSString*)script;
163 // Checks if the document is loaded, and if so triggers any necessary logic.
164 - (void)checkDocumentLoaded;
166 // Returns a new autoreleased UIWebView.
167 - (UIWebView*)createWebView;
169 // Sets value to web view property.
170 - (void)setWebView:(UIWebView*)webView;
172 // Simulates the events generated by core.js during document loading process.
173 // Used for non-HTML documents (e.g. PDF) that do not support data flow from
174 // JavaScript to obj-c via iframe injection.
175 - (void)generateMissingDocumentLifecycleEvents;
177 // Makes a best-effort attempt to retroactively construct a load request for an
178 // observed-but-unexpected navigation. Should be called any time a page
179 // change is detected as having happened without the current internal state
180 // indicating it was expected.
181 - (void)generateMissingLoadRequestWithURL:(const GURL&)currentURL
182 referrer:(const web::Referrer&)referrer;
184 // Returns a child scripting CRWWebController with the given window name.
185 - (id<CRWWebControllerScripting>)scriptingInterfaceForWindowNamed:
188 // Called when UIMoviePlayerControllerDidEnterFullscreenNotification is posted.
189 - (void)moviePlayerDidEnterFullscreen:(NSNotification*)notification;
191 // Called when UIMoviePlayerControllerDidExitFullscreenNotification is posted.
192 - (void)moviePlayerDidExitFullscreen:(NSNotification*)notification;
194 // Exits fullscreen mode for any playing videos.
195 - (void)exitFullscreenVideo;
197 // Handles presentation of the web document. Checks and handles URL changes,
198 // page refreshes, and title changes.
199 - (void)documentPresent;
201 // Handles queued JS to ObjC messages.
202 // All commands are passed via JSON strings, including parameters.
203 - (void)respondToJSInvoke;
205 // Pauses (|throttle|=YES) or resumes (|throttle|=NO) crwebinvoke message
207 - (void)setJsMessageQueueThrottled:(BOOL)throttle;
209 // Removes document load commands from the queue. Otherwise they could be
210 // handled after a new page load has begun, which would cause an unwanted
212 - (void)removeDocumentLoadCommandsFromQueue;
214 // Returns YES if the given URL has a scheme associated with JS->native calls.
215 - (BOOL)urlSchemeIsWebInvoke:(const GURL&)url;
217 // Returns window name given a message and its context.
218 - (NSString*)windowNameFromMessage:(base::DictionaryValue*)message
219 context:(NSDictionary*)context;
221 // Handles 'anchor.click' message.
222 - (BOOL)handleAnchorClickMessage:(base::DictionaryValue*)message
223 context:(NSDictionary*)context;
224 // Handles 'document.loaded' message.
225 - (BOOL)handleDocumentLoadedMessage:(base::DictionaryValue*)message
226 context:(NSDictionary*)context;
227 // Handles 'document.present' message.
228 - (BOOL)handleDocumentPresentMessage:(base::DictionaryValue*)message
229 context:(NSDictionary*)context;
230 // Handles 'document.retitled' message.
231 - (BOOL)handleDocumentRetitledMessage:(base::DictionaryValue*)message
232 context:(NSDictionary*)context;
233 // Handles 'window.close' message.
234 - (BOOL)handleWindowCloseMessage:(base::DictionaryValue*)message
235 context:(NSDictionary*)context;
236 // Handles 'window.document.write' message.
237 - (BOOL)handleWindowDocumentWriteMessage:(base::DictionaryValue*)message
238 context:(NSDictionary*)context;
239 // Handles 'window.location' message.
240 - (BOOL)handleWindowLocationMessage:(base::DictionaryValue*)message
241 context:(NSDictionary*)context;
242 // Handles 'window.open' message.
243 - (BOOL)handleWindowOpenMessage:(base::DictionaryValue*)message
244 context:(NSDictionary*)context;
245 // Handles 'window.stop' message.
246 - (BOOL)handleWindowStopMessage:(base::DictionaryValue*)message
247 context:(NSDictionary*)context;
248 // Handles 'window.unload' message.
249 - (BOOL)handleWindowUnloadMessage:(base::DictionaryValue*)message
250 context:(NSDictionary*)context;
255 // Utility to help catch unwanted JavaScript re-entries. An instance should
256 // be created on the stack any time JS will be executed.
257 // It uses an instance variable (passed in as a pointer to boolean) that needs
258 // to be initialized to false.
259 class ScopedReentryGuard {
261 explicit ScopedReentryGuard(BOOL* is_inside_javascript_context)
262 : is_inside_javascript_context_(is_inside_javascript_context) {
263 DCHECK(!*is_inside_javascript_context_);
264 *is_inside_javascript_context_ = YES;
266 ~ScopedReentryGuard() {
267 DCHECK(*is_inside_javascript_context_);
268 *is_inside_javascript_context_ = NO;
272 BOOL* is_inside_javascript_context_;
273 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedReentryGuard);
276 // Class allowing to selectively enable caching of |currentURL| on a
277 // CRWUIWebViewWebController. As long as an instance of this class lives,
278 // the CRWUIWebViewWebController passed as parameter will cache the result for
279 // |currentURL| calls.
280 class ScopedCachedCurrentUrl {
282 explicit ScopedCachedCurrentUrl(CRWUIWebViewWebController* web_controller)
283 : web_controller_(web_controller),
284 had_cached_current_url_([web_controller urlCachingEnabled]) {
285 if (!had_cached_current_url_)
286 [web_controller_ setURLCachingEnabled:YES];
289 ~ScopedCachedCurrentUrl() {
290 if (!had_cached_current_url_)
291 [web_controller_ setURLCachingEnabled:NO];
295 CRWUIWebViewWebController* web_controller_;
296 bool had_cached_current_url_;
297 DISALLOW_IMPLICIT_CONSTRUCTORS(ScopedCachedCurrentUrl);
300 // Normalizes the URL for the purposes of identifying the origin page (remove
301 // any parameters, fragments, etc.) and return an absolute string of the URL.
302 std::string NormalizedUrl(const GURL& url) {
303 GURL::Replacements replacements;
304 replacements.ClearQuery();
305 replacements.ClearRef();
306 replacements.ClearUsername();
307 replacements.ClearPassword();
308 GURL page_url(url.ReplaceComponents(replacements));
310 return page_url.spec();
313 // The maximum size of JSON message passed from JavaScript to ObjC.
314 // 256kB is an arbitrary number that was chosen to be a magnitude larger than
315 // any legitimate message.
316 const size_t kMaxMessageQueueSize = 262144;
320 @implementation CRWUIWebViewWebController
322 - (instancetype)initWithWebState:(scoped_ptr<web::WebStateImpl>)webState {
323 self = [super initWithWebState:webState.Pass()];
325 _jsInvokeParameterQueue.reset([[CRWJSInvokeParameterQueue alloc] init]);
327 NSNotificationCenter* defaultCenter = [NSNotificationCenter defaultCenter];
328 [defaultCenter addObserver:self
329 selector:@selector(moviePlayerDidEnterFullscreen:)
331 @"UIMoviePlayerControllerDidEnterFullscreenNotification"
333 [defaultCenter addObserver:self
334 selector:@selector(moviePlayerDidExitFullscreen:)
336 @"UIMoviePlayerControllerDidExitFullscreenNotification"
338 _recurringTaskDelegate = self;
340 // UIWebViews require a redirect network client in order to accurately
341 // detect server redirects.
342 redirect_client_factory_.reset(
343 [[CRWRedirectNetworkClientFactory alloc] initWithDelegate:self]);
344 // WeakNSObjects cannot be dereferenced outside of the main thread, and
345 // CRWWebController must be deallocated from the main thread. Keep a
346 // reference to self on the main thread and release it after successfully
347 // adding the redirect client factory to the RequestTracker on the IO
349 __block base::scoped_nsobject<CRWUIWebViewWebController> scopedSelf(
351 web::WebThread::PostTaskAndReply(
352 web::WebThread::IO, FROM_HERE, base::BindBlock(^{
353 // Only add the factory if there is a valid request tracker.
354 web::WebStateImpl* webState = [scopedSelf webStateImpl];
355 if (webState && webState->GetRequestTracker()) {
356 webState->GetRequestTracker()->AddNetworkClientFactory(
357 redirect_client_factory_);
368 [[NSNotificationCenter defaultCenter] removeObserver:self];
372 #pragma mark - CRWWebController public method implementations
374 - (void)loadCompleteWithSuccess:(BOOL)loadSuccess {
375 [super loadCompleteWithSuccess:loadSuccess];
376 [self removeDocumentLoadCommandsFromQueue];
379 - (BOOL)keyboardDisplayRequiresUserAction {
380 return [_uiWebView keyboardDisplayRequiresUserAction];
383 - (void)setKeyboardDisplayRequiresUserAction:(BOOL)requiresUserAction {
384 [_uiWebView setKeyboardDisplayRequiresUserAction:requiresUserAction];
387 - (void)evaluateUserJavaScript:(NSString*)script {
388 [self setUserInteractionRegistered:YES];
389 // A script which contains alert() call executed by UIWebView from gcd block
390 // freezes the app (crbug.com/444106), hence this uses the NSObject API.
391 [_uiWebView performSelectorOnMainThread:
392 @selector(stringByEvaluatingJavaScriptFromString:)
397 #pragma mark Overridden public methods
401 // Turn the timer back on, and do an immediate check for anything missed
402 // while the timer was off.
403 [self.recurringTaskDelegate runRecurringTask];
404 _continuousCheckTimer->Reset();
411 // Turn the timer off, to cut down on work being done by background tabs.
412 _continuousCheckTimer->Stop();
416 // The video player is not quit/dismissed when the home button is pressed and
417 // Chrome is backgrounded (crbug.com/277206).
418 if (_inFullscreenVideo)
419 [self exitFullscreenVideo];
426 // The timers must not exist at this point, otherwise this object will leak.
427 DCHECK(!_continuousCheckTimer);
428 DCHECK(!_lowerFrequencyTimer);
431 - (void)childWindowClosed:(NSString*)windowName {
432 // Get the substring of the window name after the hash.
433 NSRange range = [windowName rangeOfString:
434 base::SysUTF8ToNSString(web::kWindowNameSeparator)];
435 if (range.location != NSNotFound) {
436 NSString* target = [windowName substringFromIndex:(range.location + 1)];
437 [self stringByEvaluatingJavaScriptFromString:
438 [NSString stringWithFormat:@"__gCrWeb.windowClosed('%@');", target]];
443 #pragma mark Testing-Only Methods
445 - (void)injectWebViewContentView:(CRWWebViewContentView*)webViewContentView {
446 [super injectWebViewContentView:webViewContentView];
447 [self setWebView:static_cast<UIWebView*>(webViewContentView.webView)];
450 #pragma mark CRWJSInjectionEvaluatorMethods
452 - (void)evaluateJavaScript:(NSString*)script
453 stringResultHandler:(web::JavaScriptCompletion)handler {
454 NSString* safeScript = [self scriptByAddingWindowIDCheckForScript:script];
455 web::EvaluateJavaScript(_uiWebView, safeScript, handler);
458 - (web::WebViewType)webViewType {
459 return web::UI_WEB_VIEW_TYPE;
462 #pragma mark - Protected property implementations
465 return _uiWebView.get();
468 - (UIScrollView*)webScrollView {
469 return [_uiWebView scrollView];
472 - (BOOL)urlCachingEnabled {
473 return _urlCachingEnabled;
476 - (void)setURLCachingEnabled:(BOOL)enabled {
477 if (enabled == _urlCachingEnabled)
479 _urlCachingEnabled = enabled;
480 _cachedURL.first = GURL();
483 - (BOOL)ignoreURLVerificationFailures {
484 return _spoofableRequest;
488 return [self stringByEvaluatingJavaScriptFromString:
489 @"document.title.length ? document.title : ''"];
492 #pragma mark Protected method implementations
494 - (void)ensureWebViewCreated {
496 [self setWebView:[self createWebView]];
497 // Notify super class about created web view. -webViewDidChange is not
498 // called from -setWebView: as the latter used in unit tests with fake
499 // web view, which cannot be added to view hierarchy.
500 [self webViewDidChange];
504 - (void)resetWebView {
505 [self setWebView:nil];
508 - (GURL)webURLWithTrustLevel:(web::URLVerificationTrustLevel*)trustLevel {
509 if (_cachedURL.first.is_valid()) {
510 *trustLevel = _cachedURL.second;
511 return _cachedURL.first;
513 ScopedReentryGuard reentryGuard(&_inJavaScriptContext);
515 [CRWURLVerifyingProtocolHandler currentURLForWebView:_uiWebView
516 trustLevel:trustLevel];
518 // If verification succeeded, or the URL has changed, then the UIWebView is no
519 // longer in the initial state.
520 if (*trustLevel != web::URLVerificationTrustLevel::kNone ||
521 url != GURL(url::kAboutBlankURL))
522 _spoofableRequest = NO;
524 if (*trustLevel == web::URLVerificationTrustLevel::kAbsolute) {
525 _lastCorrectURLTime = base::TimeTicks::Now();
526 if (self.urlCachingEnabled) {
527 _cachedURL.first = url;
528 _cachedURL.second = *trustLevel;
530 } else if (*trustLevel == web::URLVerificationTrustLevel::kNone &&
531 (base::TimeTicks::Now() - _lastCorrectURLTime) <
532 base::TimeDelta::FromMilliseconds(
533 web::kContinuousCheckIntervalMSLow)) {
534 // URL is not trusted, but the last time it was trusted is within
535 // kContinuousCheckIntervalMSLow.
536 *trustLevel = web::URLVerificationTrustLevel::kMixed;
542 - (void)registerUserAgent {
543 web::BuildAndRegisterUserAgentForUIWebView(
544 self.webStateImpl->GetRequestGroupID(),
545 [self useDesktopUserAgent]);
548 // The core.js cannot pass messages back to obj-c if it is injected
549 // to |WEB_VIEW_DOCUMENT| because it does not support iframe creation used
550 // by core.js to communicate back. That functionality is only supported
551 // by |WEB_VIEW_HTML_DOCUMENT|. |WEB_VIEW_DOCUMENT| is used when displaying
552 // non-HTML contents (e.g. PDF documents).
553 - (web::WebViewDocumentType)webViewDocumentType {
554 // This happens during tests.
556 return web::WEB_VIEW_DOCUMENT_TYPE_GENERIC;
558 NSString* documentType =
559 [_uiWebView stringByEvaluatingJavaScriptFromString:
561 if ([documentType isEqualToString:@"[object HTMLDocument]"])
562 return web::WEB_VIEW_DOCUMENT_TYPE_HTML;
563 else if ([documentType isEqualToString:@"[object Document]"])
564 return web::WEB_VIEW_DOCUMENT_TYPE_GENERIC;
565 return web::WEB_VIEW_DOCUMENT_TYPE_UNKNOWN;
568 - (void)loadRequest:(NSMutableURLRequest*)request {
569 DCHECK(web::GetWebClient());
570 GURL requestURL = net::GURLWithNSURL(request.URL);
571 // If the request is for WebUI, add information to let the network stack
572 // access the requestGroupID.
573 if (web::GetWebClient()->IsAppSpecificURL(requestURL)) {
574 // Sub requests of a chrome:// page will not contain the user agent.
575 // Instead use the username part of the URL to allow the network stack to
576 // associate a request to the correct tab.
577 request.URL = web::AddRequestGroupIDToURL(
578 request.URL, self.webStateImpl->GetRequestGroupID());
580 [_uiWebView loadRequest:request];
583 - (void)loadWebHTMLString:(NSString*)html forURL:(const GURL&)URL {
584 [_uiWebView loadHTMLString:html baseURL:net::NSURLWithGURL(URL)];
587 - (BOOL)scriptHasBeenInjectedForClass:(Class)jsInjectionManagerClass
588 presenceBeacon:(NSString*)beacon {
589 NSString* beaconCheckScript = [NSString stringWithFormat:
590 @"try { typeof %@; } catch (e) { 'undefined'; }", beacon];
592 [self stringByEvaluatingJavaScriptFromString:beaconCheckScript];
593 return [result isEqualToString:@"object"];
596 - (void)injectScript:(NSString*)script forClass:(Class)JSInjectionManagerClass {
597 // Skip evaluation if there's no content (e.g., if what's being injected is
598 // an umbrella manager).
599 if ([script length]) {
600 [super injectScript:script forClass:JSInjectionManagerClass];
601 [self stringByEvaluatingJavaScriptFromString:script];
605 - (void)willLoadCurrentURLInWebView {
608 // This code uses non-documented API, but is not compiled in release.
609 id documentView = [_uiWebView valueForKey:@"documentView"];
610 id webView = [documentView valueForKey:@"webView"];
611 NSString* userAgent = [webView performSelector:@selector(userAgentForURL:)
614 const bool wrongRequestGroupID =
615 ![self.webStateImpl->GetRequestGroupID()
616 isEqualToString:web::ExtractRequestGroupIDFromUserAgent(userAgent)];
617 DLOG_IF(ERROR, wrongRequestGroupID) << "Incorrect user agent in UIWebView";
619 #endif // !defined(NDEBUG)
622 - (void)setPageChangeProbability:(web::PageChangeProbability)probability {
623 if (probability == web::PAGE_CHANGE_PROBABILITY_LOW) {
624 // Reduce check interval to precautionary frequency.
625 [self setContinuousCheckTimerInterval:
626 base::TimeDelta::FromMilliseconds(web::kContinuousCheckIntervalMSLow)];
628 // Increase the timer frequency, as a window change is anticipated shortly.
629 [self setContinuousCheckTimerInterval:
630 base::TimeDelta::FromMilliseconds(web::kContinuousCheckIntervalMSHigh)];
632 if (probability != web::PAGE_CHANGE_PROBABILITY_VERY_HIGH) {
633 // The timer frequency is automatically lowered after a set duration in
634 // case the guess was wrong, to avoid wedging in high-frequency mode.
635 base::Closure closure = base::BindBlock(^{
636 [self setContinuousCheckTimerInterval:
637 base::TimeDelta::FromMilliseconds(
638 web::kContinuousCheckIntervalMSLow)];
640 _lowerFrequencyTimer.reset(
641 new base::Timer(FROM_HERE,
642 base::TimeDelta::FromMilliseconds(
643 web::kContinuousCheckHighFrequencyMSMaxDuration),
644 closure, false /* not repeating */));
645 _lowerFrequencyTimer->Reset();
650 - (BOOL)checkForUnexpectedURLChange {
651 // The check makes no sense without an active web view.
655 // Change to UIWebView default page is not considered a 'real' change and
656 // URL changes are not reported.
657 if ([self isDefaultPage])
660 // Check if currentURL is unexpected (not the incoming page).
661 // This is necessary to notice page changes if core.js injection is disabled
662 // by a malicious page.
663 if (!self.URLOnStartLoading.is_empty() &&
664 [self currentURL] == self.URLOnStartLoading) {
668 // If the URL has changed, handle page load mechanics.
669 ScopedCachedCurrentUrl scopedCurrentURL(self);
670 [self webPageChanged];
671 [self checkDocumentLoaded];
672 [self titleDidChange];
677 - (void)abortWebLoad {
678 // Current load will not complete; this should be communicated upstream to
679 // the delegate, and flagged in the WebView so further messages can be
680 // prevented (which may be confused for messages from newer pages).
681 [_uiWebView stringByEvaluatingJavaScriptFromString:
682 @"document._cancelled = true;"];
683 [_uiWebView stopLoading];
686 - (void)resetLoadState {
691 - (void)setSuppressDialogsWithHelperScript:(NSString*)script {
692 [self stringByEvaluatingJavaScriptFromString:script];
695 - (void)checkDocumentLoaded {
697 [self stringByEvaluatingJavaScriptFromString:
698 @"document.readyState === 'loaded' || "
699 "document.readyState === 'complete'"];
700 if ([loaded isEqualToString:@"true"]) {
701 [self didFinishNavigation];
705 - (NSString*)currentReferrerString {
706 return [self stringByEvaluatingJavaScriptFromString:@"document.referrer"];
709 - (void)titleDidChange {
710 if (![self.delegate respondsToSelector:
711 @selector(webController:titleDidChange:)]) {
715 // Checking the URL trust level is expensive. For performance reasons, the
716 // current URL and the trust level cache must be enabled.
717 // NOTE: Adding a ScopedCachedCurrentUrl here is not the right way to solve
719 DCHECK(self.urlCachingEnabled);
721 // Change to UIWebView default page is not considered a 'real' change and
722 // title changes are not reported.
723 if ([self isDefaultPage])
726 // The title can be retrieved from the document only if the URL can be
728 web::URLVerificationTrustLevel trustLevel =
729 web::URLVerificationTrustLevel::kNone;
730 [self currentURLWithTrustLevel:&trustLevel];
731 if (trustLevel != web::URLVerificationTrustLevel::kAbsolute)
734 NSString* title = self.title;
736 [self.delegate webController:self titleDidChange:title];
739 - (void)teminateNetworkActivity {
740 [super terminateNetworkActivity];
741 _jsInvokeParameterQueue.reset([[CRWJSInvokeParameterQueue alloc] init]);
744 - (void)fetchWebPageSizeWithCompletionHandler:(void(^)(CGSize))handler {
750 // Ensure that JavaScript has been injected.
751 [self.recurringTaskDelegate runRecurringTask];
752 [super fetchWebPageSizeWithCompletionHandler:handler];
755 - (void)documentPresent {
756 if (self.loadPhase != web::PAGE_LOADED &&
757 self.loadPhase != web::LOAD_REQUESTED) {
761 ScopedCachedCurrentUrl scopedCurrentURL(self);
763 // This is a good time to check if the URL has changed.
764 BOOL urlChanged = [self checkForUnexpectedURLChange];
766 // This is a good time to check if the page has refreshed.
767 if (!urlChanged && self.windowId != self.lastSeenWindowID)
768 [self webPageChanged];
770 // Set initial title.
771 [self titleDidChange];
774 - (void)webPageChanged {
775 if (self.loadPhase != web::LOAD_REQUESTED ||
776 self.lastRegisteredRequestURL.is_empty() ||
777 self.lastRegisteredRequestURL != [self currentURL]) {
778 // The page change was unexpected (not already messaged to
779 // webWillStartLoadingURL), so fill in the load request.
780 [self generateMissingLoadRequestWithURL:[self currentURL]
781 referrer:[self currentReferrer]];
784 [super webPageChanged];
787 - (void)applyWebViewScrollZoomScaleFromZoomState:
788 (const web::PageZoomState&)zoomState {
789 // A UIWebView's scroll view uses zoom scales in a non-standard way. The
790 // scroll view's |zoomScale| property is always equal to 1.0, and the
791 // |minimumZoomScale| and |maximumZoomScale| properties are adjusted
792 // proportionally to reflect the relative zoom scale. Setting the |zoomScale|
793 // property here scales the page by the value set (i.e. setting zoomScale to
794 // 2.0 will update the zoom to twice its initial scale). The maximum-scale or
795 // minimum-scale meta tags of a page may have changed since the state was
796 // recorded, so clamp the zoom scale to the current range if necessary.
797 DCHECK(zoomState.IsValid());
798 CGFloat zoomScale = zoomState.IsLegacyFormat()
799 ? zoomState.zoom_scale()
800 : self.webScrollView.minimumZoomScale /
801 zoomState.minimum_zoom_scale();
802 if (zoomScale < self.webScrollView.minimumZoomScale)
803 zoomScale = self.webScrollView.minimumZoomScale;
804 if (zoomScale > self.webScrollView.maximumZoomScale)
805 zoomScale = self.webScrollView.maximumZoomScale;
806 self.webScrollView.zoomScale = zoomScale;
809 - (void)handleCancelledError:(NSError*)error {
810 // NSURLErrorCancelled errors generated by the Chrome net stack should be
811 // aborted. If the error was generated by the UIWebView, it will not have
812 // an underlying net error and will be automatically retried by the web view.
813 DCHECK_EQ(error.code, NSURLErrorCancelled);
814 NSError* underlyingError = base::ios::GetFinalUnderlyingErrorFromError(error);
815 NSString* netDomain = base::SysUTF8ToNSString(net::kErrorDomain);
816 BOOL shouldAbortLoadForCancelledError =
817 [underlyingError.domain isEqualToString:netDomain];
818 if (!shouldAbortLoadForCancelledError)
821 // NSURLCancelled errors with underlying errors are generated from the
822 // Chrome network stack. Abort the load in this case.
825 switch (underlyingError.code) {
826 case net::ERR_ABORTED:
827 // |NSURLErrorCancelled| errors with underlying net error code
828 // |net::ERR_ABORTED| are used by the Chrome network stack to
829 // indicate that the current load should be aborted and the pending
830 // entry should be discarded.
831 [[self sessionController] discardNonCommittedEntries];
833 case net::ERR_BLOCKED_BY_CLIENT:
834 // |NSURLErrorCancelled| errors with underlying net error code
835 // |net::ERR_BLOCKED_BY_CLIENT| are used by the Chrome network stack
836 // to indicate that the current load should be aborted and the pending
837 // entry should be kept.
844 #pragma mark - JS to ObjC messaging
846 - (void)respondToJSInvoke {
847 // This call is asynchronous. If the web view has been removed, there is
848 // nothing left to do, so just discard the queued messages and return.
850 _jsInvokeParameterQueue.reset([[CRWJSInvokeParameterQueue alloc] init]);
853 // Messages are queued and processed asynchronously. However, user
854 // may initiate JavaScript at arbitrary times (e.g. through Omnibox
855 // "javascript:alert('foo')"). This delays processing of queued messages
856 // until JavaScript execution is completed.
857 // TODO(pkl): This should have a unit test or UI Automation test case.
858 // See crbug.com/228125
859 if (_inJavaScriptContext) {
860 [self performSelector:@selector(respondToJSInvoke)
865 DCHECK(_jsInvokeParameterQueue);
866 while (![_jsInvokeParameterQueue isEmpty]) {
867 CRWJSInvokeParameters* parameters =
868 [_jsInvokeParameterQueue popInvokeParameters];
871 // TODO(stuartmorgan): Some messages (e.g., window.write) should be
872 // processed even if the page has already changed by the time they are
873 // received. crbug.com/228275
874 if ([parameters windowId] != [self windowId]) {
875 // If there is a windowID mismatch, the document has been changed since
876 // messages were added to the queue. Ignore the incoming messages.
877 DLOG(WARNING) << "Messages from JS ignored due to non-matching windowID: "
878 << [[parameters windowId] UTF8String]
879 << " != " << [[self windowId] UTF8String];
882 if (![self respondToMessageQueue:[parameters commandString]
883 userIsInteracting:[parameters userIsInteracting]
884 originURL:[parameters originURL]]) {
885 DLOG(WARNING) << "Messages from JS not handled due to invalid format";
890 - (void)handleWebInvokeURL:(const GURL&)url request:(NSURLRequest*)request {
891 DCHECK([self urlSchemeIsWebInvoke:url]);
892 NSURL* nsurl = request.URL;
893 // TODO(stuartmorgan): Remove the NSURL usage here. Will require a logic
894 // change since GURL doesn't parse non-standard URLs into host and fragment
895 if (![nsurl.host isEqualToString:[self windowId]]) {
896 // If there is a windowID mismatch, we may be under attack from a
897 // malicious page, so a defense is to reset the page.
898 DLOG(WARNING) << "Messages from JS ignored due to non-matching windowID: "
899 << nsurl.host << " != " << [[self windowId] UTF8String];
900 DLOG(WARNING) << "Page reset as security precaution";
901 [self performSelector:@selector(reload) withObject:nil afterDelay:0];
904 if (url.spec().length() > kMaxMessageQueueSize) {
905 DLOG(WARNING) << "Messages from JS ignored due to excessive length";
908 NSString* commandString = [[nsurl fragment]
909 stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
911 GURL originURL(net::GURLWithNSURL(request.mainDocumentURL));
913 if (url.SchemeIs("crwebinvokeimmediate")) {
914 [self respondToMessageQueue:commandString
915 userIsInteracting:[self userIsInteracting]
916 originURL:originURL];
918 [_jsInvokeParameterQueue addCommandString:commandString
919 userIsInteracting:[self userIsInteracting]
921 forWindowId:[super windowId]];
922 if (!_jsMessageQueueThrottled) {
923 [self performSelector:@selector(respondToJSInvoke)
930 - (void)setJsMessageQueueThrottled:(BOOL)throttle {
931 _jsMessageQueueThrottled = throttle;
933 [self respondToJSInvoke];
936 - (void)removeDocumentLoadCommandsFromQueue {
937 [_jsInvokeParameterQueue removeCommandString:@"document.present"];
938 [_jsInvokeParameterQueue removeCommandString:@"document.loaded"];
941 - (BOOL)urlSchemeIsWebInvoke:(const GURL&)url {
942 return url.SchemeIs("crwebinvoke") || url.SchemeIs("crwebinvokeimmediate");
945 - (CRWJSInvokeParameterQueue*)jsInvokeParameterQueue {
946 return _jsInvokeParameterQueue;
949 - (BOOL)respondToMessageQueue:(NSString*)messageQueue
950 userIsInteracting:(BOOL)userIsInteracting
951 originURL:(const GURL&)originURL {
952 ScopedCachedCurrentUrl scopedCurrentURL(self);
955 std::string errorMessage;
956 scoped_ptr<base::Value> inputJSONData(base::JSONReader::ReadAndReturnError(
957 base::SysNSStringToUTF8(messageQueue), false, &errorCode, &errorMessage));
959 DLOG(WARNING) << "JSON parse error: %s" << errorMessage.c_str();
962 // MessageQueues pass messages as a list.
963 base::ListValue* messages = nullptr;
964 if (!inputJSONData->GetAsList(&messages)) {
965 DLOG(WARNING) << "Message queue not a list";
968 for (size_t idx = 0; idx != messages->GetSize(); ++idx) {
969 // The same-origin check has to be done for every command to mitigate the
970 // risk of command sequences where the first command would change the page
971 // and the subsequent commands would have unlimited access to it.
972 if (originURL.GetOrigin() != self.currentURL.GetOrigin()) {
973 DLOG(WARNING) << "Message source URL origin: " << originURL.GetOrigin()
974 << " does not match current URL origin: "
975 << self.currentURL.GetOrigin();
979 base::DictionaryValue* message = nullptr;
980 if (!messages->GetDictionary(idx, &message)) {
981 DLOG(WARNING) << "Message could not be retrieved";
984 BOOL messageHandled = [self respondToMessage:message
985 userIsInteracting:userIsInteracting
986 originURL:originURL];
990 // If handling the message caused this page to be closed, stop processing
992 // TODO(stuartmorgan): Ideally messages should continue to be handled until
993 // the end of the event loop (e.g., window.close(); window.open(...);
994 // should do both things). That would require knowing which messages came
995 // in the same event loop, however.
996 if ([self isBeingDestroyed])
1002 - (SEL)selectorToHandleJavaScriptCommand:(const std::string&)command {
1003 static std::map<std::string, SEL>* handlers = nullptr;
1004 static dispatch_once_t onceToken;
1005 dispatch_once(&onceToken, ^{
1006 handlers = new std::map<std::string, SEL>();
1007 (*handlers)["anchor.click"] = @selector(handleAnchorClickMessage:context:);
1008 (*handlers)["document.loaded"] =
1009 @selector(handleDocumentLoadedMessage:context:);
1010 (*handlers)["document.present"] =
1011 @selector(handleDocumentPresentMessage:context:);
1012 (*handlers)["document.retitled"] =
1013 @selector(handleDocumentRetitledMessage:context:);
1014 (*handlers)["window.close"] = @selector(handleWindowCloseMessage:context:);
1015 (*handlers)["window.document.write"] =
1016 @selector(handleWindowDocumentWriteMessage:context:);
1017 (*handlers)["window.location"] =
1018 @selector(handleWindowLocationMessage:context:);
1019 (*handlers)["window.open"] = @selector(handleWindowOpenMessage:context:);
1020 (*handlers)["window.stop"] = @selector(handleWindowStopMessage:context:);
1021 (*handlers)["window.unload"] =
1022 @selector(handleWindowUnloadMessage:context:);
1025 auto iter = handlers->find(command);
1026 return iter != handlers->end()
1028 : [super selectorToHandleJavaScriptCommand:command];
1031 - (NSString*)windowNameFromMessage:(base::DictionaryValue*)message
1032 context:(NSDictionary*)context {
1034 if(!message->GetString("target", &target)) {
1035 DLOG(WARNING) << "JS message parameter not found: target";
1039 DCHECK(context[web::kOriginURLKey]);
1040 const GURL& originURL = net::GURLWithNSURL(context[web::kOriginURLKey]);
1042 // Unique string made for page/target combination.
1043 // Safe to delimit unique string with # since page references won't
1045 return base::SysUTF8ToNSString(
1046 NormalizedUrl(originURL) + web::kWindowNameSeparator + target);
1050 #pragma mark JavaScript message handlers
1052 - (BOOL)handleAnchorClickMessage:(base::DictionaryValue*)message
1053 context:(NSDictionary*)context {
1054 // Reset the external click request.
1055 [self resetExternalRequest];
1058 if (!message->GetString("href", &href)) {
1059 DLOG(WARNING) << "JS message parameter not found: href";
1062 const GURL targetURL(href);
1063 const GURL currentURL([self currentURL]);
1064 if (currentURL != targetURL) {
1065 if (web::UrlHasWebScheme(targetURL)) {
1066 // The referrer is not known yet, and will be updated later.
1067 const web::Referrer emptyReferrer;
1068 [self registerLoadRequest:targetURL
1069 referrer:emptyReferrer
1070 transition:ui::PAGE_TRANSITION_LINK];
1071 [self setPageChangeProbability:web::PAGE_CHANGE_PROBABILITY_HIGH];
1072 } else if (web::GetWebClient()->IsAppSpecificURL(targetURL) &&
1073 web::GetWebClient()->IsAppSpecificURL(currentURL)) {
1074 // Allow navigations between app-specific URLs
1075 [self removeWebViewAllowingCachedReconstruction:NO];
1076 ui::PageTransition pageTransitionLink =
1077 ui::PageTransitionFromInt(ui::PAGE_TRANSITION_LINK);
1078 const web::Referrer referrer(currentURL, web::ReferrerPolicyDefault);
1079 web::WebState::OpenURLParams openParams(targetURL, referrer, CURRENT_TAB,
1080 pageTransitionLink, true);
1081 [self.delegate openURLWithParams:openParams];
1087 - (BOOL)handleDocumentLoadedMessage:(base::DictionaryValue*)message
1088 context:(NSDictionary*)context {
1089 // Very early hashchange events can be missed, hence this extra explicit
1091 [self checkForUnexpectedURLChange];
1092 [self didFinishNavigation];
1096 - (BOOL)handleDocumentPresentMessage:(base::DictionaryValue*)message
1097 context:(NSDictionary*)context {
1098 NSString* documentCancelled =
1099 [self stringByEvaluatingJavaScriptFromString:@"document._cancelled"];
1100 if (![documentCancelled isEqualToString:@"true"])
1101 [self documentPresent];
1105 - (BOOL)handleDocumentRetitledMessage:(base::DictionaryValue*)message
1106 context:(NSDictionary*)context {
1107 [self titleDidChange];
1111 - (BOOL)handleWindowCloseMessage:(base::DictionaryValue*)message
1112 context:(NSDictionary*)context {
1113 NSString* windowName = [self windowNameFromMessage:message
1117 [[self scriptingInterfaceForWindowNamed:windowName] orderClose];
1121 - (BOOL)handleWindowDocumentWriteMessage:(base::DictionaryValue*)message
1122 context:(NSDictionary*)context {
1123 NSString* windowName = [self windowNameFromMessage:message
1128 if (!message->GetString("html", &HTML)) {
1129 DLOG(WARNING) << "JS message parameter not found: html";
1132 [[self scriptingInterfaceForWindowNamed:windowName]
1133 loadHTML:base::SysUTF8ToNSString(HTML)];
1137 - (BOOL)handleWindowLocationMessage:(base::DictionaryValue*)message
1138 context:(NSDictionary*)context {
1139 NSString* windowName = [self windowNameFromMessage:message
1143 std::string command;
1144 if (!message->GetString("command", &command)) {
1145 DLOG(WARNING) << "JS message parameter not found: command";
1149 if (!message->GetString("value", &value)) {
1150 DLOG(WARNING) << "JS message parameter not found: value";
1153 std::string escapedValue;
1154 base::EscapeJSONString(value, true, &escapedValue);
1156 [NSString stringWithFormat:@"<script>%s = %s;</script>",
1158 escapedValue.c_str()];
1159 [[self scriptingInterfaceForWindowNamed:windowName] loadHTML:HTML];
1163 - (BOOL)handleWindowOpenMessage:(base::DictionaryValue*)message
1164 context:(NSDictionary*)context {
1165 NSString* windowName = [self windowNameFromMessage:message
1169 std::string targetURL;
1170 if (!message->GetString("url", &targetURL)) {
1171 DLOG(WARNING) << "JS message parameter not found: url";
1174 std::string referrerPolicy;
1175 if (!message->GetString("referrerPolicy", &referrerPolicy)) {
1176 DLOG(WARNING) << "JS message parameter not found: referrerPolicy";
1179 GURL resolvedURL = targetURL.empty() ?
1181 GURL(net::GURLWithNSURL(context[web::kOriginURLKey])).Resolve(targetURL);
1182 DCHECK(&resolvedURL);
1184 windowInfo(resolvedURL,
1186 [self referrerPolicyFromString:referrerPolicy],
1187 [context[web::kUserIsInteractingKey] boolValue]);
1189 [self openPopupWithInfo:windowInfo];
1193 - (BOOL)handleWindowStopMessage:(base::DictionaryValue*)message
1194 context:(NSDictionary*)context {
1195 NSString* windowName = [self windowNameFromMessage:message
1199 [[self scriptingInterfaceForWindowNamed:windowName] stopLoading];
1203 - (BOOL)handleWindowUnloadMessage:(base::DictionaryValue*)message
1204 context:(NSDictionary*)context {
1205 [self setPageChangeProbability:web::PAGE_CHANGE_PROBABILITY_VERY_HIGH];
1209 #pragma mark Private methods
1211 - (BOOL)isDefaultPage {
1212 if ([[self stringByEvaluatingJavaScriptFromString:@"document._defaultPage"]
1213 isEqualToString:@"true"]) {
1214 return self.currentURL == self.defaultURL;
1219 - (BOOL)isLinkNavigation:(UIWebViewNavigationType)navigationType {
1220 switch (navigationType) {
1221 case UIWebViewNavigationTypeLinkClicked:
1223 case UIWebViewNavigationTypeOther:
1224 return [self userClickedRecently];
1230 - (void)setContinuousCheckTimerInterval:(const base::TimeDelta&)interval {
1231 // The timer should never be set when there's no web view.
1234 BOOL shouldStartTimer =
1235 !_continuousCheckTimer.get() || _continuousCheckTimer->IsRunning();
1236 base::Closure closure = base::BindBlock(^{
1237 // Only perform JS checks if CRWWebController is not already in JavaScript
1238 // context. This is possible when "javascript:..." is executed from
1239 // Omnibox and this block is run from the timer.
1240 if (!_inJavaScriptContext)
1241 [self.recurringTaskDelegate runRecurringTask];
1243 _continuousCheckTimer.reset(
1244 new base::Timer(FROM_HERE, interval, closure, true));
1245 if (shouldStartTimer)
1246 _continuousCheckTimer->Reset();
1247 if (_lowerFrequencyTimer &&
1248 interval == base::TimeDelta::FromMilliseconds(
1249 web::kContinuousCheckIntervalMSLow)) {
1250 _lowerFrequencyTimer.reset();
1254 - (NSString*)stringByEvaluatingJavaScriptFromString:(NSString*)script {
1258 ScopedReentryGuard reentryGuard(&_inJavaScriptContext);
1259 return [_uiWebView stringByEvaluatingJavaScriptFromString:script];
1262 - (NSString*)stringByEvaluatingUserJavaScriptFromString:(NSString*)script {
1263 [self setUserInteractionRegistered:YES];
1264 return [self stringByEvaluatingJavaScriptFromString:script];
1267 - (UIWebView*)createWebView {
1268 UIWebView* webView = web::CreateWebView(
1270 self.webStateImpl->GetRequestGroupID(),
1271 [self useDesktopUserAgent]);
1273 // Mark the document object of the default page as such, so that it is not
1274 // mistaken for a 'real' page by change detection mechanisms.
1275 [webView stringByEvaluatingJavaScriptFromString:
1276 @"document._defaultPage = true;"];
1278 [webView setScalesPageToFit:YES];
1279 // Turn off data-detectors. MobileSafari does the same thing.
1280 [webView setDataDetectorTypes:UIDataDetectorTypeNone];
1282 return [webView autorelease];
1285 - (void)setWebView:(UIWebView*)webView {
1286 DCHECK_NE(_uiWebView.get(), webView);
1287 // Per documentation, must clear the delegate before releasing the UIWebView
1288 // to avoid errant dangling pointers.
1289 [_uiWebView setDelegate:nil];
1290 _uiWebView.reset([webView retain]);
1291 [_uiWebView setDelegate:self];
1292 // Clear out the trusted URL cache.
1293 _lastCorrectURLTime = base::TimeTicks();
1294 _cachedURL.first = GURL();
1295 // Reset the spoofable state (see declaration comment).
1296 // TODO(stuartmorgan): Fix the fact that there's no guarantee that no
1297 // navigation has happened before the UIWebView is set here (ideally by
1298 // unifying the creation and setting flow).
1299 _spoofableRequest = YES;
1300 _inJavaScriptContext = NO;
1303 // Do initial injection even before loading another page, since the window
1304 // object is re-used.
1305 [self injectEarlyInjectionScripts];
1307 _continuousCheckTimer.reset();
1308 // This timer exists only to change the frequency of the main timer, so it
1309 // should not outlive the main timer.
1310 _lowerFrequencyTimer.reset();
1314 - (void)generateMissingDocumentLifecycleEvents {
1315 // The webView can be removed between this method being queued and invoked.
1318 if ([self webViewDocumentType] == web::WEB_VIEW_DOCUMENT_TYPE_GENERIC) {
1319 [self documentPresent];
1320 [self didFinishNavigation];
1324 - (void)generateMissingLoadRequestWithURL:(const GURL&)currentURL
1325 referrer:(const web::Referrer&)referrer {
1326 [self loadCancelled];
1327 // Initialize transition based on whether the request is user-initiated or
1328 // not. This is a best guess to replace lost transition type informationj.
1329 ui::PageTransition transition = self.userInteractionRegistered
1330 ? ui::PAGE_TRANSITION_LINK
1331 : ui::PAGE_TRANSITION_CLIENT_REDIRECT;
1332 // If the URL agrees with session state, use the session's transition.
1333 if (currentURL == [self currentNavigationURL]) {
1334 transition = [self currentTransition];
1337 [self registerLoadRequest:currentURL referrer:referrer transition:transition];
1340 - (id<CRWWebControllerScripting>)scriptingInterfaceForWindowNamed:
1342 if (![self.delegate respondsToSelector:
1343 @selector(webController:scriptingInterfaceForWindowNamed:)]) {
1346 return [self.delegate webController:self
1347 scriptingInterfaceForWindowNamed:name];
1350 #pragma mark FullscreenVideo
1352 - (void)moviePlayerDidEnterFullscreen:(NSNotification*)notification {
1353 _inFullscreenVideo = YES;
1356 - (void)moviePlayerDidExitFullscreen:(NSNotification*)notification {
1357 _inFullscreenVideo = NO;
1360 - (void)exitFullscreenVideo {
1361 [self stringByEvaluatingJavaScriptFromString:
1362 @"__gCrWeb.exitFullscreenVideo();"];
1366 #pragma mark CRWRecurringTaskDelegate
1368 // Checks for page changes are made continuously.
1369 - (void)runRecurringTask {
1373 [self injectEarlyInjectionScripts];
1374 [self checkForUnexpectedURLChange];
1378 #pragma mark CRWRedirectClientDelegate
1380 - (void)wasRedirectedToRequest:(NSURLRequest*)request
1381 redirectResponse:(NSURLResponse*)response {
1382 // This callback can be received after -close is called; ignore it.
1383 if (self.isBeingDestroyed)
1386 // Register the redirected load request if it originated from the main page
1388 GURL redirectedURL = net::GURLWithNSURL(response.URL);
1389 if ([self currentNavigationURL] == redirectedURL) {
1390 [self registerLoadRequest:net::GURLWithNSURL(request.URL)
1391 referrer:[self currentReferrer]
1392 transition:ui::PAGE_TRANSITION_SERVER_REDIRECT];
1397 #pragma mark UIWebViewDelegate Methods
1399 // Called when a load begins, and for subsequent subpages.
1400 - (BOOL)webView:(UIWebView*)webView
1401 shouldStartLoadWithRequest:(NSURLRequest*)request
1402 navigationType:(UIWebViewNavigationType)navigationType {
1403 DVLOG(5) << "webViewShouldStartLoadWithRequest "
1404 << net::FormatUrlRequestForLogging(request);
1406 if (self.isBeingDestroyed)
1409 GURL url = net::GURLWithNSURL(request.URL);
1411 // The crwebnull protocol is used where an element requires a URL but it
1412 // should not trigger any activity on the WebView.
1413 if (url.SchemeIs("crwebnull"))
1416 if ([self urlSchemeIsWebInvoke:url]) {
1417 [self handleWebInvokeURL:url request:request];
1421 // ##### IMPORTANT NOTE #####
1422 // Do not add new code above this line unless you're certain about what you're
1423 // doing with respect to JS re-entry.
1424 ScopedReentryGuard javaScriptReentryGuard(&_inJavaScriptContext);
1425 web::FrameInfo* targetFrame = nullptr; // No reliable way to get this info.
1426 BOOL isLinkClick = [self isLinkNavigation:navigationType];
1427 return [self shouldAllowLoadWithRequest:request
1428 targetFrame:targetFrame
1429 isLinkClick:isLinkClick];
1432 // Called at multiple points during a load, such as at the start of loading a
1433 // page, and every time an iframe loads. Not called again for server-side
1435 - (void)webViewDidStartLoad:(UIWebView *)webView {
1436 NSURLRequest* request = webView.request;
1437 DVLOG(5) << "webViewDidStartLoad "
1438 << net::FormatUrlRequestForLogging(request);
1439 // |webView:shouldStartLoad| may not be called or called with different URL
1440 // and mainDocURL for the request in certain page navigations. There
1441 // are at least 2 known page navigations where this occurs, in these cases it
1442 // is imperative the URL verification timer is started here.
1443 // The 2 known cases are:
1444 // 1) A malicious page suppressing core.js injection and calling
1445 // window.history.back() or window.history.forward()
1446 // 2) An iframe loading a URL using target=_blank.
1447 // TODO(shreyasv): crbug.com/349155. Understand further why this happens
1448 // in some case and not in others.
1449 if (webView != self.webView) {
1450 // This happens sometimes as tests are brought down.
1451 // TODO(jimblackler): work out why and fix the problem at source.
1452 LOG(WARNING) << " UIWebViewDelegate message received for inactive WebView.";
1455 DCHECK(!self.isBeingDestroyed);
1456 // Increment the number of pending loads. This will be balanced by either
1457 // a |-webViewDidFinishLoad:| or |-webView:didFailLoadWithError:|.
1459 [self.recurringTaskDelegate runRecurringTask];
1462 // Called when the page (or one of its subframes) finishes loading. This is
1463 // called multiple times during a page load, with varying frequency depending
1464 // on the action (going back, loading a page with frames, redirecting).
1465 // See http://goto/efrmm for a summary of why this is so painful.
1466 - (void)webViewDidFinishLoad:(UIWebView*)webView {
1467 DVLOG(5) << "webViewDidFinishLoad "
1468 << net::FormatUrlRequestForLogging(webView.request);
1469 DCHECK(!self.isHalted);
1470 // Occasionally this delegate is invoked as a side effect during core.js
1471 // injection. It is necessary to ensure we do not attempt to start the
1472 // injection process a second time.
1473 if (!_inJavaScriptContext)
1474 [self.recurringTaskDelegate runRecurringTask];
1476 [self performSelector:@selector(generateMissingDocumentLifecycleEvents)
1481 if ((_loadCount == _unloadCount) && (self.loadPhase != web::LOAD_REQUESTED))
1482 [self checkDocumentLoaded];
1485 // Called when there is an error loading the page. Some errors aren't actual
1486 // errors, but are caused by user actions such as stopping a page load
1488 - (void)webView:(UIWebView*)webView didFailLoadWithError:(NSError*)error {
1489 DVLOG(5) << "webViewDidFailLoadWithError "
1490 << net::FormatUrlRequestForLogging(webView.request);
1493 // Under unknown circumstances navigation item can be null. In that case the
1494 // state of web/ will not be valid and app will crash. Early return avoid a
1495 // crash (crbug.com/411912).
1496 if (!self.webStateImpl ||
1497 !self.webStateImpl->GetNavigationManagerImpl().GetVisibleItem()) {
1501 // There's no reliable way to know if a load is for the main frame, so make a
1502 // best-effort guess.
1503 // |_loadCount| is reset to 0 before starting loading a new page, and is
1504 // incremented in each call to |-webViewDidStartLoad:|. The main request
1505 // is the first one to be loaded, and thus has a |_loadCount| of 1.
1506 // Sub-requests have a |_loadCount| > 1.
1507 // An iframe loading after the main page also has a |_loadCount| of 1, as
1508 // |_loadCount| is reset at the end of the main page load. In that case,
1509 // |loadPhase_| is web::PAGE_LOADED (as opposed to web::PAGE_LOADING for a
1511 const bool isMainFrame = (_loadCount == 1 &&
1512 self.loadPhase != web::PAGE_LOADED);
1513 [self handleLoadError:error inMainFrame:isMainFrame];
1517 #pragma mark Testing methods
1519 -(id<CRWRecurringTaskDelegate>)recurringTaskDelegate {
1520 return _recurringTaskDelegate;