Fix broken path in extensions/common/PRESUBMIT.py
[chromium-blink-merge.git] / content / browser / frame_host / navigator_impl.cc
blob52ed3c0d4a237ff3e6c41c63b2d6a3845a831a68
1 // Copyright 2013 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 #include "content/browser/frame_host/navigator_impl.h"
7 #include "base/command_line.h"
8 #include "base/metrics/histogram.h"
9 #include "base/time/time.h"
10 #include "content/browser/frame_host/frame_tree.h"
11 #include "content/browser/frame_host/frame_tree_node.h"
12 #include "content/browser/frame_host/navigation_controller_impl.h"
13 #include "content/browser/frame_host/navigation_entry_impl.h"
14 #include "content/browser/frame_host/navigation_request.h"
15 #include "content/browser/frame_host/navigation_request_info.h"
16 #include "content/browser/frame_host/navigator_delegate.h"
17 #include "content/browser/frame_host/render_frame_host_impl.h"
18 #include "content/browser/renderer_host/render_view_host_impl.h"
19 #include "content/browser/site_instance_impl.h"
20 #include "content/browser/webui/web_ui_controller_factory_registry.h"
21 #include "content/browser/webui/web_ui_impl.h"
22 #include "content/common/frame_messages.h"
23 #include "content/common/navigation_params.h"
24 #include "content/common/view_messages.h"
25 #include "content/public/browser/browser_context.h"
26 #include "content/public/browser/content_browser_client.h"
27 #include "content/public/browser/global_request_id.h"
28 #include "content/public/browser/invalidate_type.h"
29 #include "content/public/browser/navigation_controller.h"
30 #include "content/public/browser/navigation_details.h"
31 #include "content/public/browser/page_navigator.h"
32 #include "content/public/browser/render_view_host.h"
33 #include "content/public/browser/stream_handle.h"
34 #include "content/public/browser/user_metrics.h"
35 #include "content/public/common/bindings_policy.h"
36 #include "content/public/common/content_client.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/resource_response.h"
39 #include "content/public/common/url_constants.h"
40 #include "content/public/common/url_utils.h"
41 #include "net/base/net_errors.h"
43 namespace content {
45 namespace {
47 FrameMsg_Navigate_Type::Value GetNavigationType(
48 BrowserContext* browser_context, const NavigationEntryImpl& entry,
49 NavigationController::ReloadType reload_type) {
50 switch (reload_type) {
51 case NavigationControllerImpl::RELOAD:
52 return FrameMsg_Navigate_Type::RELOAD;
53 case NavigationControllerImpl::RELOAD_IGNORING_CACHE:
54 return FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE;
55 case NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL:
56 return FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
57 case NavigationControllerImpl::NO_RELOAD:
58 break; // Fall through to rest of function.
61 // |RenderViewImpl::PopulateStateFromPendingNavigationParams| differentiates
62 // between |RESTORE_WITH_POST| and |RESTORE|.
63 if (entry.restore_type() ==
64 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY) {
65 if (entry.GetHasPostData())
66 return FrameMsg_Navigate_Type::RESTORE_WITH_POST;
67 return FrameMsg_Navigate_Type::RESTORE;
70 return FrameMsg_Navigate_Type::NORMAL;
73 RenderFrameHostManager* GetRenderManager(RenderFrameHostImpl* rfh) {
74 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
75 switches::kSitePerProcess))
76 return rfh->frame_tree_node()->render_manager();
78 return rfh->frame_tree_node()->frame_tree()->root()->render_manager();
81 } // namespace
83 struct NavigatorImpl::NavigationMetricsData {
84 NavigationMetricsData(base::TimeTicks start_time,
85 GURL url,
86 NavigationEntryImpl::RestoreType restore_type)
87 : start_time_(start_time), url_(url) {
88 is_restoring_from_last_session_ =
89 (restore_type ==
90 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY ||
91 restore_type == NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED);
94 base::TimeTicks start_time_;
95 GURL url_;
96 bool is_restoring_from_last_session_;
97 base::TimeTicks url_job_start_time_;
98 base::TimeDelta before_unload_delay_;
101 NavigatorImpl::NavigatorImpl(
102 NavigationControllerImpl* navigation_controller,
103 NavigatorDelegate* delegate)
104 : controller_(navigation_controller),
105 delegate_(delegate) {
108 NavigatorImpl::~NavigatorImpl() {}
110 NavigatorDelegate* NavigatorImpl::GetDelegate() {
111 return delegate_;
114 NavigationController* NavigatorImpl::GetController() {
115 return controller_;
118 void NavigatorImpl::DidStartProvisionalLoad(
119 RenderFrameHostImpl* render_frame_host,
120 const GURL& url,
121 bool is_transition_navigation) {
122 bool is_error_page = (url.spec() == kUnreachableWebDataURL);
123 bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL);
124 GURL validated_url(url);
125 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
126 render_process_host->FilterURL(false, &validated_url);
128 bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame();
129 NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
130 if (is_main_frame) {
131 // If there is no browser-initiated pending entry for this navigation and it
132 // is not for the error URL, create a pending entry using the current
133 // SiteInstance, and ensure the address bar updates accordingly. We don't
134 // know the referrer or extra headers at this point, but the referrer will
135 // be set properly upon commit.
136 bool has_browser_initiated_pending_entry = pending_entry &&
137 !pending_entry->is_renderer_initiated();
138 if (!has_browser_initiated_pending_entry && !is_error_page) {
139 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
140 controller_->CreateNavigationEntry(validated_url,
141 content::Referrer(),
142 ui::PAGE_TRANSITION_LINK,
143 true /* is_renderer_initiated */,
144 std::string(),
145 controller_->GetBrowserContext()));
146 entry->set_site_instance(render_frame_host->GetSiteInstance());
147 // TODO(creis): If there's a pending entry already, find a safe way to
148 // update it instead of replacing it and copying over things like this.
149 if (pending_entry) {
150 entry->set_transferred_global_request_id(
151 pending_entry->transferred_global_request_id());
152 entry->set_should_replace_entry(pending_entry->should_replace_entry());
153 entry->SetRedirectChain(pending_entry->GetRedirectChain());
155 controller_->SetPendingEntry(entry);
156 if (delegate_)
157 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
160 if (delegate_ && is_transition_navigation)
161 delegate_->DidStartNavigationTransition(render_frame_host);
164 if (delegate_) {
165 // Notify the observer about the start of the provisional load.
166 delegate_->DidStartProvisionalLoad(
167 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc);
172 void NavigatorImpl::DidFailProvisionalLoadWithError(
173 RenderFrameHostImpl* render_frame_host,
174 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
175 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
176 << ", error_code: " << params.error_code
177 << ", error_description: " << params.error_description
178 << ", showing_repost_interstitial: " <<
179 params.showing_repost_interstitial
180 << ", frame_id: " << render_frame_host->GetRoutingID();
181 GURL validated_url(params.url);
182 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
183 render_process_host->FilterURL(false, &validated_url);
185 if (net::ERR_ABORTED == params.error_code) {
186 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
187 // This means that the interstitial won't be torn down properly, which is
188 // bad. But if we have an interstitial, go back to another tab type, and
189 // then load the same interstitial again, we could end up getting the first
190 // interstitial's "failed" message (as a result of the cancel) when we're on
191 // the second one. We can't tell this apart, so we think we're tearing down
192 // the current page which will cause a crash later on.
194 // http://code.google.com/p/chromium/issues/detail?id=2855
195 // Because this will not tear down the interstitial properly, if "back" is
196 // back to another tab type, the interstitial will still be somewhat alive
197 // in the previous tab type. If you navigate somewhere that activates the
198 // tab with the interstitial again, you'll see a flash before the new load
199 // commits of the interstitial page.
200 FrameTreeNode* root =
201 render_frame_host->frame_tree_node()->frame_tree()->root();
202 if (root->render_manager()->interstitial_page() != NULL) {
203 LOG(WARNING) << "Discarding message during interstitial.";
204 return;
207 // We used to cancel the pending renderer here for cross-site downloads.
208 // However, it's not safe to do that because the download logic repeatedly
209 // looks for this WebContents based on a render ID. Instead, we just
210 // leave the pending renderer around until the next navigation event
211 // (Navigate, DidNavigate, etc), which will clean it up properly.
213 // TODO(creis): Find a way to cancel any pending RFH here.
216 // We usually clear the pending entry when it fails, so that an arbitrary URL
217 // isn't left visible above a committed page. This must be enforced when
218 // the pending entry isn't visible (e.g., renderer-initiated navigations) to
219 // prevent URL spoofs for in-page navigations that don't go through
220 // DidStartProvisionalLoadForFrame.
222 // However, we do preserve the pending entry in some cases, such as on the
223 // initial navigation of an unmodified blank tab. We also allow the delegate
224 // to say when it's safe to leave aborted URLs in the omnibox, to let the user
225 // edit the URL and try again. This may be useful in cases that the committed
226 // page cannot be attacker-controlled. In these cases, we still allow the
227 // view to clear the pending entry and typed URL if the user requests
228 // (e.g., hitting Escape with focus in the address bar).
230 // Note: don't touch the transient entry, since an interstitial may exist.
231 bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() ||
232 delegate_->ShouldPreserveAbortedURLs();
233 if (controller_->GetPendingEntry() != controller_->GetVisibleEntry() ||
234 !should_preserve_entry) {
235 controller_->DiscardPendingEntry(true);
237 // Also force the UI to refresh.
238 controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
241 if (delegate_)
242 delegate_->DidFailProvisionalLoadWithError(render_frame_host, params);
245 void NavigatorImpl::DidFailLoadWithError(
246 RenderFrameHostImpl* render_frame_host,
247 const GURL& url,
248 int error_code,
249 const base::string16& error_description) {
250 if (delegate_) {
251 delegate_->DidFailLoadWithError(
252 render_frame_host, url, error_code,
253 error_description);
257 bool NavigatorImpl::NavigateToEntry(
258 FrameTreeNode* frame_tree_node,
259 const NavigationEntryImpl& entry,
260 NavigationController::ReloadType reload_type) {
261 TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
263 // The renderer will reject IPC messages with URLs longer than
264 // this limit, so don't attempt to navigate with a longer URL.
265 if (entry.GetURL().spec().size() > GetMaxURLChars()) {
266 LOG(WARNING) << "Refusing to load URL as it exceeds " << GetMaxURLChars()
267 << " characters.";
268 return false;
271 // This will be used to set the Navigation Timing API navigationStart
272 // parameter for browser navigations in new tabs (intents, tabs opened through
273 // "Open link in new tab"). We need to keep it above RFHM::Navigate() call to
274 // capture the time needed for the RenderFrameHost initialization.
275 base::TimeTicks navigation_start = base::TimeTicks::Now();
277 RenderFrameHostManager* manager = frame_tree_node->render_manager();
279 // PlzNavigate: the RenderFrameHosts are no longer asked to navigate.
280 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
281 switches::kEnableBrowserSideNavigation)) {
282 navigation_data_.reset(new NavigationMetricsData(
283 navigation_start, entry.GetURL(), entry.restore_type()));
284 RequestNavigation(frame_tree_node, entry, reload_type, navigation_start);
286 // Notify observers about navigation.
287 if (delegate_)
288 delegate_->DidStartNavigationToPendingEntry(entry.GetURL(), reload_type);
290 return true;
293 RenderFrameHostImpl* dest_render_frame_host = manager->Navigate(entry);
294 if (!dest_render_frame_host)
295 return false; // Unable to create the desired RenderFrameHost.
297 // Make sure no code called via RFHM::Navigate clears the pending entry.
298 CHECK_EQ(controller_->GetPendingEntry(), &entry);
300 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
301 // Double check that here.
302 CheckWebUIRendererDoesNotDisplayNormalURL(
303 dest_render_frame_host, entry.GetURL());
305 // Notify observers that we will navigate in this RenderFrame.
306 if (delegate_) {
307 delegate_->AboutToNavigateRenderFrame(frame_tree_node->current_frame_host(),
308 dest_render_frame_host);
311 // Navigate in the desired RenderFrameHost.
312 // We can skip this step in the rare case that this is a transfer navigation
313 // which began in the chosen RenderFrameHost, since the request has already
314 // been issued. In that case, simply resume the response.
315 bool is_transfer_to_same =
316 entry.transferred_global_request_id().child_id != -1 &&
317 entry.transferred_global_request_id().child_id ==
318 dest_render_frame_host->GetProcess()->GetID();
319 if (!is_transfer_to_same) {
320 navigation_data_.reset(new NavigationMetricsData(
321 navigation_start, entry.GetURL(), entry.restore_type()));
322 // Create the navigation parameters.
323 // TODO(vitalybuka): Move this before AboutToNavigateRenderFrame once
324 // http://crbug.com/408684 is fixed.
325 FrameMsg_Navigate_Type::Value navigation_type =
326 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
327 dest_render_frame_host->Navigate(
328 entry.ConstructCommonNavigationParams(navigation_type),
329 entry.ConstructStartNavigationParams(),
330 entry.ConstructRequestNavigationParams(
331 navigation_start,
332 controller_->GetPendingEntryIndex() == -1,
333 controller_->GetIndexOfEntry(&entry),
334 controller_->GetLastCommittedEntryIndex(),
335 controller_->GetEntryCount()));
336 } else {
337 // No need to navigate again. Just resume the deferred request.
338 dest_render_frame_host->GetProcess()->ResumeDeferredNavigation(
339 entry.transferred_global_request_id());
342 // Make sure no code called via RFH::Navigate clears the pending entry.
343 CHECK_EQ(controller_->GetPendingEntry(), &entry);
345 if (entry.GetPageID() == -1) {
346 // HACK!! This code suppresses javascript: URLs from being added to
347 // session history, which is what we want to do for javascript: URLs that
348 // do not generate content. What we really need is a message from the
349 // renderer telling us that a new page was not created. The same message
350 // could be used for mailto: URLs and the like.
351 if (entry.GetURL().SchemeIs(url::kJavaScriptScheme))
352 return false;
355 // Notify observers about navigation.
356 if (delegate_)
357 delegate_->DidStartNavigationToPendingEntry(entry.GetURL(), reload_type);
359 return true;
362 bool NavigatorImpl::NavigateToPendingEntry(
363 FrameTreeNode* frame_tree_node,
364 NavigationController::ReloadType reload_type) {
365 return NavigateToEntry(frame_tree_node, *controller_->GetPendingEntry(),
366 reload_type);
369 void NavigatorImpl::DidNavigate(
370 RenderFrameHostImpl* render_frame_host,
371 const FrameHostMsg_DidCommitProvisionalLoad_Params& input_params) {
372 // PlzNavigate
373 // The navigation request has been committed so the browser process doesn't
374 // need to care about it anymore.
375 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
376 switches::kEnableBrowserSideNavigation)) {
377 render_frame_host->frame_tree_node()->ResetNavigationRequest(true);
380 FrameHostMsg_DidCommitProvisionalLoad_Params params(input_params);
381 FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
382 bool use_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
383 switches::kSitePerProcess);
385 if (ui::PageTransitionIsMainFrame(params.transition)) {
386 if (delegate_) {
387 // When overscroll navigation gesture is enabled, a screenshot of the page
388 // in its current state is taken so that it can be used during the
389 // nav-gesture. It is necessary to take the screenshot here, before
390 // calling RenderFrameHostManager::DidNavigateMainFrame, because that can
391 // change WebContents::GetRenderViewHost to return the new host, instead
392 // of the one that may have just been swapped out.
393 if (delegate_->CanOverscrollContent()) {
394 // Don't take screenshots if we are staying on the same page. We want
395 // in-page navigations to be super fast, and taking a screenshot
396 // currently blocks GPU for a longer time than we are willing to
397 // tolerate in this use case.
398 if (!params.was_within_same_page)
399 controller_->TakeScreenshot();
402 // Run tasks that must execute just before the commit.
403 bool is_navigation_within_page = controller_->IsURLInPageNavigation(
404 params.url, params.was_within_same_page, render_frame_host);
405 delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
408 if (!use_site_per_process)
409 frame_tree->root()->render_manager()->DidNavigateFrame(
410 render_frame_host, params.gesture == NavigationGestureUser);
413 // Save the origin of the new page. Do this before calling
414 // DidNavigateFrame(), because the origin needs to be included in the SwapOut
415 // message, which is sent inside DidNavigateFrame(). SwapOut needs the
416 // origin because it creates a RenderFrameProxy that needs this to initialize
417 // its security context. This origin will also be sent to RenderFrameProxies
418 // created via ViewMsg_New and FrameMsg_NewFrameProxy.
419 render_frame_host->frame_tree_node()->SetCurrentOrigin(params.origin);
421 // When using --site-per-process, we notify the RFHM for all navigations,
422 // not just main frame navigations.
423 if (use_site_per_process) {
424 FrameTreeNode* frame = render_frame_host->frame_tree_node();
425 frame->render_manager()->DidNavigateFrame(
426 render_frame_host, params.gesture == NavigationGestureUser);
429 // Update the site of the SiteInstance if it doesn't have one yet, unless
430 // assigning a site is not necessary for this URL. In that case, the
431 // SiteInstance can still be considered unused until a navigation to a real
432 // page.
433 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
434 if (!site_instance->HasSite() &&
435 ShouldAssignSiteForURL(params.url)) {
436 site_instance->SetSite(params.url);
439 // Need to update MIME type here because it's referred to in
440 // UpdateNavigationCommands() called by RendererDidNavigate() to
441 // determine whether or not to enable the encoding menu.
442 // It's updated only for the main frame. For a subframe,
443 // RenderView::UpdateURL does not set params.contents_mime_type.
444 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
445 // TODO(jungshik): Add a test for the encoding menu to avoid
446 // regressing it again.
447 // TODO(nasko): Verify the correctness of the above comment, since some of the
448 // code doesn't exist anymore. Also, move this code in the
449 // PageTransitionIsMainFrame code block above.
450 if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
451 delegate_->SetMainFrameMimeType(params.contents_mime_type);
453 LoadCommittedDetails details;
454 bool did_navigate = controller_->RendererDidNavigate(render_frame_host,
455 params, &details);
457 // For now, keep track of each frame's URL in its FrameTreeNode. This lets
458 // us estimate our process count for implementing OOP iframes.
459 // TODO(creis): Remove this when we track which pages commit in each frame.
460 render_frame_host->frame_tree_node()->set_current_url(params.url);
462 // Send notification about committed provisional loads. This notification is
463 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
464 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
465 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
466 DCHECK_EQ(!render_frame_host->GetParent(),
467 did_navigate ? details.is_main_frame : false);
468 ui::PageTransition transition_type = params.transition;
469 // Whether or not a page transition was triggered by going backward or
470 // forward in the history is only stored in the navigation controller's
471 // entry list.
472 if (did_navigate &&
473 (controller_->GetLastCommittedEntry()->GetTransitionType() &
474 ui::PAGE_TRANSITION_FORWARD_BACK)) {
475 transition_type = ui::PageTransitionFromInt(
476 params.transition | ui::PAGE_TRANSITION_FORWARD_BACK);
479 delegate_->DidCommitProvisionalLoad(render_frame_host,
480 params.url,
481 transition_type);
484 if (!did_navigate)
485 return; // No navigation happened.
487 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
488 // for the appropriate notification (best) or you can add it to
489 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
490 // necessary, please).
492 // TODO(carlosk): Move this out when PlzNavigate implementation properly calls
493 // the observer methods.
494 RecordNavigationMetrics(details, params, site_instance);
496 // Run post-commit tasks.
497 if (delegate_) {
498 if (details.is_main_frame) {
499 delegate_->DidNavigateMainFramePostCommit(render_frame_host,
500 details, params);
503 delegate_->DidNavigateAnyFramePostCommit(
504 render_frame_host, details, params);
508 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
509 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
510 // still be used for a normal web site.
511 if (url == GURL(url::kAboutBlankURL))
512 return false;
514 // The embedder will then have the opportunity to determine if the URL
515 // should "use up" the SiteInstance.
516 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
519 void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
520 const GURL& url,
521 SiteInstance* source_site_instance,
522 const Referrer& referrer,
523 WindowOpenDisposition disposition,
524 bool should_replace_current_entry,
525 bool user_gesture) {
526 SiteInstance* current_site_instance =
527 GetRenderManager(render_frame_host)->current_frame_host()->
528 GetSiteInstance();
529 // If this came from a swapped out RenderFrameHost, we only allow the request
530 // if we are still in the same BrowsingInstance.
531 // TODO(creis): Move this to RenderFrameProxyHost::OpenURL.
532 if (render_frame_host->is_swapped_out() &&
533 !render_frame_host->GetSiteInstance()->IsRelatedSiteInstance(
534 current_site_instance)) {
535 return;
538 // Delegate to RequestTransferURL because this is just the generic
539 // case where |old_request_id| is empty.
540 // TODO(creis): Pass the redirect_chain into this method to support client
541 // redirects. http://crbug.com/311721.
542 std::vector<GURL> redirect_chain;
543 RequestTransferURL(render_frame_host, url, source_site_instance,
544 redirect_chain, referrer, ui::PAGE_TRANSITION_LINK,
545 disposition, GlobalRequestID(),
546 should_replace_current_entry, user_gesture);
549 void NavigatorImpl::RequestTransferURL(
550 RenderFrameHostImpl* render_frame_host,
551 const GURL& url,
552 SiteInstance* source_site_instance,
553 const std::vector<GURL>& redirect_chain,
554 const Referrer& referrer,
555 ui::PageTransition page_transition,
556 WindowOpenDisposition disposition,
557 const GlobalRequestID& transferred_global_request_id,
558 bool should_replace_current_entry,
559 bool user_gesture) {
560 GURL dest_url(url);
561 SiteInstance* current_site_instance =
562 GetRenderManager(render_frame_host)->current_frame_host()->
563 GetSiteInstance();
564 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
565 current_site_instance, url)) {
566 dest_url = GURL(url::kAboutBlankURL);
569 int frame_tree_node_id = -1;
571 // Send the navigation to the current FrameTreeNode if it's destined for a
572 // subframe in the current tab. We'll assume it's for the main frame
573 // (possibly of a new or different WebContents) otherwise.
574 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
575 switches::kSitePerProcess) &&
576 disposition == CURRENT_TAB &&
577 render_frame_host->GetParent()) {
578 frame_tree_node_id =
579 render_frame_host->frame_tree_node()->frame_tree_node_id();
582 OpenURLParams params(
583 dest_url, referrer, frame_tree_node_id, disposition, page_transition,
584 true /* is_renderer_initiated */);
585 params.source_site_instance = source_site_instance;
586 if (redirect_chain.size() > 0)
587 params.redirect_chain = redirect_chain;
588 params.transferred_global_request_id = transferred_global_request_id;
589 params.should_replace_current_entry = should_replace_current_entry;
590 params.user_gesture = user_gesture;
592 if (GetRenderManager(render_frame_host)->web_ui()) {
593 // Web UI pages sometimes want to override the page transition type for
594 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
595 // automatically generated suggestions). We don't override other types
596 // like TYPED because they have different implications (e.g., autocomplete).
597 if (ui::PageTransitionCoreTypeIs(
598 params.transition, ui::PAGE_TRANSITION_LINK))
599 params.transition =
600 GetRenderManager(render_frame_host)->web_ui()->
601 GetLinkTransitionType();
603 // Note also that we hide the referrer for Web UI pages. We don't really
604 // want web sites to see a referrer of "chrome://blah" (and some
605 // chrome: URLs might have search terms or other stuff we don't want to
606 // send to the site), so we send no referrer.
607 params.referrer = Referrer();
609 // Navigations in Web UI pages count as browser-initiated navigations.
610 params.is_renderer_initiated = false;
613 if (delegate_)
614 delegate_->RequestOpenURL(render_frame_host, params);
617 // PlzNavigate
618 void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
619 bool proceed) {
620 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
621 switches::kEnableBrowserSideNavigation));
622 DCHECK(frame_tree_node);
624 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
626 // The NavigationRequest may have been canceled while the renderer was
627 // executing the BeforeUnload event.
628 if (!navigation_request)
629 return;
631 DCHECK_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
632 navigation_request->state());
634 if (proceed)
635 BeginNavigation(frame_tree_node);
636 else
637 CancelNavigation(frame_tree_node);
640 // PlzNavigate
641 void NavigatorImpl::OnBeginNavigation(
642 FrameTreeNode* frame_tree_node,
643 const CommonNavigationParams& common_params,
644 const BeginNavigationParams& begin_params,
645 scoped_refptr<ResourceRequestBody> body) {
646 // This is a renderer-initiated navigation.
647 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
648 switches::kEnableBrowserSideNavigation));
649 DCHECK(frame_tree_node);
651 NavigationRequest* ongoing_navigation_request =
652 frame_tree_node->navigation_request();
654 // The renderer-initiated navigation request is ignored iff a) there is an
655 // ongoing request b) which is browser or user-initiated and c) the renderer
656 // request is not user-initiated.
657 if (ongoing_navigation_request &&
658 (ongoing_navigation_request->browser_initiated() ||
659 ongoing_navigation_request->begin_params().has_user_gesture) &&
660 !begin_params.has_user_gesture) {
661 return;
664 // In all other cases the current navigation, if any, is canceled and a new
665 // NavigationRequest is created for the node.
666 scoped_ptr<NavigationRequest> navigation_request =
667 NavigationRequest::CreateRendererInitiated(
668 frame_tree_node, common_params, begin_params, body,
669 controller_->GetLastCommittedEntryIndex(),
670 controller_->GetEntryCount());
671 frame_tree_node->SetNavigationRequest(navigation_request.Pass());
673 if (frame_tree_node->IsMainFrame())
674 navigation_data_.reset();
676 BeginNavigation(frame_tree_node);
679 // PlzNavigate
680 void NavigatorImpl::CommitNavigation(FrameTreeNode* frame_tree_node,
681 ResourceResponse* response,
682 scoped_ptr<StreamHandle> body) {
683 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
684 switches::kEnableBrowserSideNavigation));
686 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
687 DCHECK(navigation_request);
688 DCHECK(response ||
689 !NavigationRequest::ShouldMakeNetworkRequest(
690 navigation_request->common_params().url));
692 // HTTP 204 (No Content) and HTTP 205 (Reset Content) responses should not
693 // commit; they leave the frame showing the previous page.
694 if (response && response->head.headers.get() &&
695 (response->head.headers->response_code() == 204 ||
696 response->head.headers->response_code() == 205)) {
697 CancelNavigation(frame_tree_node);
698 return;
701 // Select an appropriate renderer to commit the navigation.
702 RenderFrameHostImpl* render_frame_host =
703 frame_tree_node->render_manager()->GetFrameHostForNavigation(
704 *navigation_request);
706 // The renderer can exit view source mode when any error or cancellation
707 // happen. When reusing the same renderer, overwrite to recover the mode.
708 if (navigation_request->is_view_source() &&
709 render_frame_host ==
710 frame_tree_node->render_manager()->current_frame_host()) {
711 DCHECK(!render_frame_host->GetParent());
712 render_frame_host->render_view_host()->Send(
713 new ViewMsg_EnableViewSourceMode(
714 render_frame_host->render_view_host()->GetRoutingID()));
717 CheckWebUIRendererDoesNotDisplayNormalURL(
718 render_frame_host, navigation_request->common_params().url);
720 render_frame_host->CommitNavigation(response, body.Pass(),
721 navigation_request->common_params(),
722 navigation_request->request_params());
725 // PlzNavigate
726 void NavigatorImpl::FailedNavigation(FrameTreeNode* frame_tree_node,
727 bool has_stale_copy_in_cache,
728 int error_code) {
729 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
730 switches::kEnableBrowserSideNavigation));
732 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
733 DCHECK(navigation_request);
735 // If the request was canceled by the user do not show an error page.
736 if (error_code == net::ERR_ABORTED) {
737 frame_tree_node->ResetNavigationRequest(false);
738 return;
741 // Select an appropriate renderer to show the error page.
742 RenderFrameHostImpl* render_frame_host =
743 frame_tree_node->render_manager()->GetFrameHostForNavigation(
744 *navigation_request);
745 CheckWebUIRendererDoesNotDisplayNormalURL(
746 render_frame_host, navigation_request->common_params().url);
748 render_frame_host->FailedNavigation(navigation_request->common_params(),
749 navigation_request->request_params(),
750 has_stale_copy_in_cache, error_code);
753 // PlzNavigate
754 void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) {
755 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
756 switches::kEnableBrowserSideNavigation));
757 frame_tree_node->ResetNavigationRequest(false);
758 if (frame_tree_node->IsMainFrame())
759 navigation_data_.reset();
762 bool NavigatorImpl::IsWaitingForBeforeUnloadACK(
763 FrameTreeNode* frame_tree_node) {
764 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
765 switches::kEnableBrowserSideNavigation));
766 NavigationRequest* request = frame_tree_node->navigation_request();
767 if (!request)
768 return false;
769 return request->state() == NavigationRequest::WAITING_FOR_RENDERER_RESPONSE;
772 void NavigatorImpl::LogResourceRequestTime(
773 base::TimeTicks timestamp, const GURL& url) {
774 if (navigation_data_ && navigation_data_->url_ == url) {
775 navigation_data_->url_job_start_time_ = timestamp;
776 UMA_HISTOGRAM_TIMES(
777 "Navigation.TimeToURLJobStart",
778 navigation_data_->url_job_start_time_ - navigation_data_->start_time_);
782 void NavigatorImpl::LogBeforeUnloadTime(
783 const base::TimeTicks& renderer_before_unload_start_time,
784 const base::TimeTicks& renderer_before_unload_end_time) {
785 // Only stores the beforeunload delay if we're tracking a browser initiated
786 // navigation and it happened later than the navigation request.
787 if (navigation_data_ &&
788 renderer_before_unload_start_time > navigation_data_->start_time_) {
789 navigation_data_->before_unload_delay_ =
790 renderer_before_unload_end_time - renderer_before_unload_start_time;
794 void NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL(
795 RenderFrameHostImpl* render_frame_host,
796 const GURL& url) {
797 int enabled_bindings =
798 render_frame_host->render_view_host()->GetEnabledBindings();
799 bool is_allowed_in_web_ui_renderer =
800 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
801 controller_->GetBrowserContext(), url);
802 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
803 !is_allowed_in_web_ui_renderer) {
804 // Log the URL to help us diagnose any future failures of this CHECK.
805 GetContentClient()->SetActiveURL(url);
806 CHECK(0);
810 // PlzNavigate
811 void NavigatorImpl::RequestNavigation(
812 FrameTreeNode* frame_tree_node,
813 const NavigationEntryImpl& entry,
814 NavigationController::ReloadType reload_type,
815 base::TimeTicks navigation_start) {
816 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
817 switches::kEnableBrowserSideNavigation));
818 DCHECK(frame_tree_node);
819 FrameMsg_Navigate_Type::Value navigation_type =
820 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
821 scoped_ptr<NavigationRequest> navigation_request =
822 NavigationRequest::CreateBrowserInitiated(frame_tree_node, entry,
823 navigation_type,
824 navigation_start, controller_);
825 frame_tree_node->SetNavigationRequest(navigation_request.Pass());
827 // Have the current renderer execute its beforeUnload event if needed. If it
828 // is not needed (eg. the renderer is not live), BeginNavigation should get
829 // called.
830 frame_tree_node->navigation_request()->SetWaitingForRendererResponse();
831 frame_tree_node->current_frame_host()->DispatchBeforeUnload(true);
834 void NavigatorImpl::BeginNavigation(FrameTreeNode* frame_tree_node) {
835 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
837 // A browser-initiated navigation could have been cancelled while it was
838 // waiting for the BeforeUnload event to execute.
839 if (!navigation_request)
840 return;
842 // Start the request.
843 if (navigation_request->BeginNavigation()) {
844 // If the request was sent to the IO thread, notify the
845 // RenderFrameHostManager so it can speculatively create a RenderFrameHost
846 // (and potentially a new renderer process) in parallel.
847 frame_tree_node->render_manager()->BeginNavigation(*navigation_request);
851 void NavigatorImpl::RecordNavigationMetrics(
852 const LoadCommittedDetails& details,
853 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
854 SiteInstance* site_instance) {
855 DCHECK(site_instance->HasProcess());
857 if (!details.is_in_page)
858 RecordAction(base::UserMetricsAction("FrameLoad"));
860 if (!details.is_main_frame || !navigation_data_ ||
861 navigation_data_->url_job_start_time_.is_null() ||
862 navigation_data_->url_ != params.original_request_url) {
863 return;
866 base::TimeDelta time_to_commit =
867 base::TimeTicks::Now() - navigation_data_->start_time_;
868 UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit);
870 time_to_commit -= navigation_data_->before_unload_delay_;
871 base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ -
872 navigation_data_->start_time_ -
873 navigation_data_->before_unload_delay_;
874 if (navigation_data_->is_restoring_from_last_session_) {
875 UMA_HISTOGRAM_TIMES(
876 "Navigation.TimeToCommit_SessionRestored_BeforeUnloadDiscounted",
877 time_to_commit);
878 UMA_HISTOGRAM_TIMES(
879 "Navigation.TimeToURLJobStart_SessionRestored_BeforeUnloadDiscounted",
880 time_to_network);
881 navigation_data_.reset();
882 return;
884 bool navigation_created_new_renderer_process =
885 site_instance->GetProcess()->GetInitTimeForNavigationMetrics() >
886 navigation_data_->start_time_;
887 if (navigation_created_new_renderer_process) {
888 UMA_HISTOGRAM_TIMES(
889 "Navigation.TimeToCommit_NewRenderer_BeforeUnloadDiscounted",
890 time_to_commit);
891 UMA_HISTOGRAM_TIMES(
892 "Navigation.TimeToURLJobStart_NewRenderer_BeforeUnloadDiscounted",
893 time_to_network);
894 } else {
895 UMA_HISTOGRAM_TIMES(
896 "Navigation.TimeToCommit_ExistingRenderer_BeforeUnloadDiscounted",
897 time_to_commit);
898 UMA_HISTOGRAM_TIMES(
899 "Navigation.TimeToURLJobStart_ExistingRenderer_BeforeUnloadDiscounted",
900 time_to_network);
902 navigation_data_.reset();
905 } // namespace content