Pass FrameTreeNode (not RenderFrameHost) to NavigateToEntry.
[chromium-blink-merge.git] / content / browser / frame_host / navigator_impl.cc
blob547c5515f8f740f20db596244f4265a34057b461
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"
42 namespace content {
44 namespace {
46 FrameMsg_Navigate_Type::Value GetNavigationType(
47 BrowserContext* browser_context, const NavigationEntryImpl& entry,
48 NavigationController::ReloadType reload_type) {
49 switch (reload_type) {
50 case NavigationControllerImpl::RELOAD:
51 return FrameMsg_Navigate_Type::RELOAD;
52 case NavigationControllerImpl::RELOAD_IGNORING_CACHE:
53 return FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE;
54 case NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL:
55 return FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
56 case NavigationControllerImpl::NO_RELOAD:
57 break; // Fall through to rest of function.
60 // |RenderViewImpl::PopulateStateFromPendingNavigationParams| differentiates
61 // between |RESTORE_WITH_POST| and |RESTORE|.
62 if (entry.restore_type() ==
63 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY) {
64 if (entry.GetHasPostData())
65 return FrameMsg_Navigate_Type::RESTORE_WITH_POST;
66 return FrameMsg_Navigate_Type::RESTORE;
69 return FrameMsg_Navigate_Type::NORMAL;
72 RenderFrameHostManager* GetRenderManager(RenderFrameHostImpl* rfh) {
73 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
74 switches::kSitePerProcess))
75 return rfh->frame_tree_node()->render_manager();
77 return rfh->frame_tree_node()->frame_tree()->root()->render_manager();
80 void MakeNavigateParams(const NavigationEntryImpl& entry,
81 NavigationControllerImpl* controller,
82 NavigationController::ReloadType reload_type,
83 base::TimeTicks navigation_start,
84 FrameMsg_Navigate_Params* params) {
85 FrameMsg_UILoadMetricsReportType::Value report_type =
86 FrameMsg_UILoadMetricsReportType::NO_REPORT;
87 base::TimeTicks ui_timestamp = base::TimeTicks();
88 #if defined(OS_ANDROID)
89 if (!entry.intent_received_timestamp().is_null())
90 report_type = FrameMsg_UILoadMetricsReportType::REPORT_INTENT;
91 ui_timestamp = entry.intent_received_timestamp();
92 #endif
94 params->common_params = CommonNavigationParams(
95 entry.GetURL(), entry.GetReferrer(), entry.GetTransitionType(),
96 GetNavigationType(controller->GetBrowserContext(), entry, reload_type),
97 !entry.IsViewSourceMode(), ui_timestamp, report_type);
98 params->commit_params = CommitNavigationParams(
99 entry.GetPageState(), entry.GetIsOverridingUserAgent(), navigation_start);
100 params->is_post = entry.GetHasPostData();
101 params->extra_headers = entry.extra_headers();
102 if (entry.GetBrowserInitiatedPostData()) {
103 params->browser_initiated_post_data.assign(
104 entry.GetBrowserInitiatedPostData()->front(),
105 entry.GetBrowserInitiatedPostData()->front() +
106 entry.GetBrowserInitiatedPostData()->size());
109 if (!entry.GetBaseURLForDataURL().is_empty()) {
110 params->base_url_for_data_url = entry.GetBaseURLForDataURL();
111 params->history_url_for_data_url = entry.GetVirtualURL();
113 params->should_replace_current_entry = entry.should_replace_entry();
114 // This is used by the old performance infrastructure to set up DocumentState
115 // associated with the RenderView.
116 // TODO(ppi): make it go away.
117 params->request_time = base::Time::Now();
118 params->transferred_request_child_id =
119 entry.transferred_global_request_id().child_id;
120 params->transferred_request_request_id =
121 entry.transferred_global_request_id().request_id;
123 params->page_id = entry.GetPageID();
124 params->should_clear_history_list = entry.should_clear_history_list();
125 if (entry.should_clear_history_list()) {
126 // Set the history list related parameters to the same values a
127 // NavigationController would return before its first navigation. This will
128 // fully clear the RenderView's view of the session history.
129 params->pending_history_list_offset = -1;
130 params->current_history_list_offset = -1;
131 params->current_history_list_length = 0;
132 } else {
133 params->pending_history_list_offset = controller->GetIndexOfEntry(&entry);
134 params->current_history_list_offset =
135 controller->GetLastCommittedEntryIndex();
136 params->current_history_list_length = controller->GetEntryCount();
138 // Set the redirect chain to the navigation's redirects, unless we are
139 // returning to a completed navigation (whose previous redirects don't apply).
140 if (ui::PageTransitionIsNewNavigation(params->common_params.transition)) {
141 params->redirects = entry.GetRedirectChain();
142 } else {
143 params->redirects.clear();
146 params->can_load_local_resources = entry.GetCanLoadLocalResources();
147 params->frame_to_navigate = entry.GetFrameToNavigate();
150 } // namespace
152 struct NavigatorImpl::NavigationMetricsData {
153 NavigationMetricsData(base::TimeTicks start_time,
154 GURL url,
155 NavigationEntryImpl::RestoreType restore_type)
156 : start_time_(start_time), url_(url) {
157 is_restoring_from_last_session_ =
158 (restore_type ==
159 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY ||
160 restore_type == NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED);
163 base::TimeTicks start_time_;
164 GURL url_;
165 bool is_restoring_from_last_session_;
166 base::TimeTicks url_job_start_time_;
167 base::TimeDelta before_unload_delay_;
170 NavigatorImpl::NavigatorImpl(
171 NavigationControllerImpl* navigation_controller,
172 NavigatorDelegate* delegate)
173 : controller_(navigation_controller),
174 delegate_(delegate) {
177 NavigatorImpl::~NavigatorImpl() {}
179 NavigationController* NavigatorImpl::GetController() {
180 return controller_;
183 void NavigatorImpl::DidStartProvisionalLoad(
184 RenderFrameHostImpl* render_frame_host,
185 const GURL& url,
186 bool is_transition_navigation) {
187 bool is_error_page = (url.spec() == kUnreachableWebDataURL);
188 bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL);
189 GURL validated_url(url);
190 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
191 render_process_host->FilterURL(false, &validated_url);
193 bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame();
194 NavigationEntryImpl* pending_entry =
195 NavigationEntryImpl::FromNavigationEntry(controller_->GetPendingEntry());
196 if (is_main_frame) {
197 // If there is no browser-initiated pending entry for this navigation and it
198 // is not for the error URL, create a pending entry using the current
199 // SiteInstance, and ensure the address bar updates accordingly. We don't
200 // know the referrer or extra headers at this point, but the referrer will
201 // be set properly upon commit.
202 bool has_browser_initiated_pending_entry = pending_entry &&
203 !pending_entry->is_renderer_initiated();
204 if (!has_browser_initiated_pending_entry && !is_error_page) {
205 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
206 controller_->CreateNavigationEntry(validated_url,
207 content::Referrer(),
208 ui::PAGE_TRANSITION_LINK,
209 true /* is_renderer_initiated */,
210 std::string(),
211 controller_->GetBrowserContext()));
212 entry->set_site_instance(render_frame_host->GetSiteInstance());
213 // TODO(creis): If there's a pending entry already, find a safe way to
214 // update it instead of replacing it and copying over things like this.
215 if (pending_entry) {
216 entry->set_transferred_global_request_id(
217 pending_entry->transferred_global_request_id());
218 entry->set_should_replace_entry(pending_entry->should_replace_entry());
219 entry->SetRedirectChain(pending_entry->GetRedirectChain());
221 controller_->SetPendingEntry(entry);
222 if (delegate_)
223 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
226 if (delegate_ && is_transition_navigation)
227 delegate_->DidStartNavigationTransition(render_frame_host);
230 if (delegate_) {
231 // Notify the observer about the start of the provisional load.
232 delegate_->DidStartProvisionalLoad(
233 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc);
238 void NavigatorImpl::DidFailProvisionalLoadWithError(
239 RenderFrameHostImpl* render_frame_host,
240 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
241 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
242 << ", error_code: " << params.error_code
243 << ", error_description: " << params.error_description
244 << ", showing_repost_interstitial: " <<
245 params.showing_repost_interstitial
246 << ", frame_id: " << render_frame_host->GetRoutingID();
247 GURL validated_url(params.url);
248 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
249 render_process_host->FilterURL(false, &validated_url);
251 if (net::ERR_ABORTED == params.error_code) {
252 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
253 // This means that the interstitial won't be torn down properly, which is
254 // bad. But if we have an interstitial, go back to another tab type, and
255 // then load the same interstitial again, we could end up getting the first
256 // interstitial's "failed" message (as a result of the cancel) when we're on
257 // the second one. We can't tell this apart, so we think we're tearing down
258 // the current page which will cause a crash later on.
260 // http://code.google.com/p/chromium/issues/detail?id=2855
261 // Because this will not tear down the interstitial properly, if "back" is
262 // back to another tab type, the interstitial will still be somewhat alive
263 // in the previous tab type. If you navigate somewhere that activates the
264 // tab with the interstitial again, you'll see a flash before the new load
265 // commits of the interstitial page.
266 FrameTreeNode* root =
267 render_frame_host->frame_tree_node()->frame_tree()->root();
268 if (root->render_manager()->interstitial_page() != NULL) {
269 LOG(WARNING) << "Discarding message during interstitial.";
270 return;
273 // We used to cancel the pending renderer here for cross-site downloads.
274 // However, it's not safe to do that because the download logic repeatedly
275 // looks for this WebContents based on a render ID. Instead, we just
276 // leave the pending renderer around until the next navigation event
277 // (Navigate, DidNavigate, etc), which will clean it up properly.
279 // TODO(creis): Find a way to cancel any pending RFH here.
282 // We usually clear the pending entry when it fails, so that an arbitrary URL
283 // isn't left visible above a committed page. This must be enforced when
284 // the pending entry isn't visible (e.g., renderer-initiated navigations) to
285 // prevent URL spoofs for in-page navigations that don't go through
286 // DidStartProvisionalLoadForFrame.
288 // However, we do preserve the pending entry in some cases, such as on the
289 // initial navigation of an unmodified blank tab. We also allow the delegate
290 // to say when it's safe to leave aborted URLs in the omnibox, to let the user
291 // edit the URL and try again. This may be useful in cases that the committed
292 // page cannot be attacker-controlled. In these cases, we still allow the
293 // view to clear the pending entry and typed URL if the user requests
294 // (e.g., hitting Escape with focus in the address bar).
296 // Note: don't touch the transient entry, since an interstitial may exist.
297 bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() ||
298 delegate_->ShouldPreserveAbortedURLs();
299 if (controller_->GetPendingEntry() != controller_->GetVisibleEntry() ||
300 !should_preserve_entry) {
301 controller_->DiscardPendingEntry();
303 // Also force the UI to refresh.
304 controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
307 if (delegate_)
308 delegate_->DidFailProvisionalLoadWithError(render_frame_host, params);
311 void NavigatorImpl::DidFailLoadWithError(
312 RenderFrameHostImpl* render_frame_host,
313 const GURL& url,
314 int error_code,
315 const base::string16& error_description) {
316 if (delegate_) {
317 delegate_->DidFailLoadWithError(
318 render_frame_host, url, error_code,
319 error_description);
323 bool NavigatorImpl::NavigateToEntry(
324 FrameTreeNode* frame_tree_node,
325 const NavigationEntryImpl& entry,
326 NavigationController::ReloadType reload_type) {
327 TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
329 // The renderer will reject IPC messages with URLs longer than
330 // this limit, so don't attempt to navigate with a longer URL.
331 if (entry.GetURL().spec().size() > GetMaxURLChars()) {
332 LOG(WARNING) << "Refusing to load URL as it exceeds " << GetMaxURLChars()
333 << " characters.";
334 return false;
337 // This will be used to set the Navigation Timing API navigationStart
338 // parameter for browser navigations in new tabs (intents, tabs opened through
339 // "Open link in new tab"). We need to keep it above RFHM::Navigate() call to
340 // capture the time needed for the RenderFrameHost initialization.
341 base::TimeTicks navigation_start = base::TimeTicks::Now();
343 RenderFrameHostManager* manager = frame_tree_node->render_manager();
345 // PlzNavigate: the RenderFrameHosts are no longer asked to navigate.
346 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
347 switches::kEnableBrowserSideNavigation)) {
348 navigation_data_.reset(new NavigationMetricsData(
349 navigation_start, entry.GetURL(), entry.restore_type()));
350 RequestNavigation(frame_tree_node, entry, reload_type, navigation_start);
351 return true;
354 RenderFrameHostImpl* dest_render_frame_host = manager->Navigate(entry);
355 if (!dest_render_frame_host)
356 return false; // Unable to create the desired RenderFrameHost.
358 // Make sure no code called via RFHM::Navigate clears the pending entry.
359 CHECK_EQ(controller_->GetPendingEntry(), &entry);
361 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
362 // Double check that here.
363 CheckWebUIRendererDoesNotDisplayNormalURL(
364 dest_render_frame_host, entry.GetURL());
366 // Notify observers that we will navigate in this RenderFrame.
367 if (delegate_) {
368 delegate_->AboutToNavigateRenderFrame(frame_tree_node->current_frame_host(),
369 dest_render_frame_host);
372 // Create the navigation parameters.
373 // TODO(vitalybuka): Move this before AboutToNavigateRenderFrame once
374 // http://crbug.com/408684 is fixed.
375 FrameMsg_Navigate_Params navigate_params;
376 MakeNavigateParams(
377 entry, controller_, reload_type, navigation_start, &navigate_params);
379 // Navigate in the desired RenderFrameHost.
380 // We can skip this step in the rare case that this is a transfer navigation
381 // which began in the chosen RenderFrameHost, since the request has already
382 // been issued. In that case, simply resume the response.
383 bool is_transfer_to_same =
384 navigate_params.transferred_request_child_id != -1 &&
385 navigate_params.transferred_request_child_id ==
386 dest_render_frame_host->GetProcess()->GetID();
387 if (!is_transfer_to_same) {
388 navigation_data_.reset(new NavigationMetricsData(
389 navigation_start, entry.GetURL(), entry.restore_type()));
390 dest_render_frame_host->Navigate(navigate_params);
391 } else {
392 // No need to navigate again. Just resume the deferred request.
393 dest_render_frame_host->GetProcess()->ResumeDeferredNavigation(
394 GlobalRequestID(navigate_params.transferred_request_child_id,
395 navigate_params.transferred_request_request_id));
398 // Make sure no code called via RFH::Navigate clears the pending entry.
399 CHECK_EQ(controller_->GetPendingEntry(), &entry);
401 if (entry.GetPageID() == -1) {
402 // HACK!! This code suppresses javascript: URLs from being added to
403 // session history, which is what we want to do for javascript: URLs that
404 // do not generate content. What we really need is a message from the
405 // renderer telling us that a new page was not created. The same message
406 // could be used for mailto: URLs and the like.
407 if (entry.GetURL().SchemeIs(url::kJavaScriptScheme))
408 return false;
411 // Notify observers about navigation.
412 if (delegate_) {
413 delegate_->DidStartNavigationToPendingEntry(dest_render_frame_host,
414 entry.GetURL(),
415 reload_type);
418 return true;
421 bool NavigatorImpl::NavigateToPendingEntry(
422 FrameTreeNode* frame_tree_node,
423 NavigationController::ReloadType reload_type) {
424 return NavigateToEntry(
425 frame_tree_node,
426 *NavigationEntryImpl::FromNavigationEntry(controller_->GetPendingEntry()),
427 reload_type);
430 void NavigatorImpl::DidNavigate(
431 RenderFrameHostImpl* render_frame_host,
432 const FrameHostMsg_DidCommitProvisionalLoad_Params& input_params) {
433 // PlzNavigate
434 // The navigation request has been committed so the browser process doesn't
435 // need to care about it anymore.
436 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
437 switches::kEnableBrowserSideNavigation)) {
438 navigation_request_map_.erase(
439 render_frame_host->frame_tree_node()->frame_tree_node_id());
442 FrameHostMsg_DidCommitProvisionalLoad_Params params(input_params);
443 FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
444 bool use_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
445 switches::kSitePerProcess);
447 if (ui::PageTransitionIsMainFrame(params.transition)) {
448 if (delegate_) {
449 // When overscroll navigation gesture is enabled, a screenshot of the page
450 // in its current state is taken so that it can be used during the
451 // nav-gesture. It is necessary to take the screenshot here, before
452 // calling RenderFrameHostManager::DidNavigateMainFrame, because that can
453 // change WebContents::GetRenderViewHost to return the new host, instead
454 // of the one that may have just been swapped out.
455 if (delegate_->CanOverscrollContent()) {
456 // Don't take screenshots if we are staying on the same page. We want
457 // in-page navigations to be super fast, and taking a screenshot
458 // currently blocks GPU for a longer time than we are willing to
459 // tolerate in this use case.
460 if (!params.was_within_same_page)
461 controller_->TakeScreenshot();
464 // Run tasks that must execute just before the commit.
465 bool is_navigation_within_page = controller_->IsURLInPageNavigation(
466 params.url, params.was_within_same_page, render_frame_host);
467 delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
470 if (!use_site_per_process)
471 frame_tree->root()->render_manager()->DidNavigateFrame(
472 render_frame_host, params.gesture == NavigationGestureUser);
475 // Save the origin of the new page. Do this before calling
476 // DidNavigateFrame(), because the origin needs to be included in the SwapOut
477 // message, which is sent inside DidNavigateFrame(). SwapOut needs the
478 // origin because it creates a RenderFrameProxy that needs this to initialize
479 // its security context. This origin will also be sent to RenderFrameProxies
480 // created via ViewMsg_New and FrameMsg_NewFrameProxy.
481 render_frame_host->frame_tree_node()->set_current_origin(params.origin);
483 // When using --site-per-process, we notify the RFHM for all navigations,
484 // not just main frame navigations.
485 if (use_site_per_process) {
486 FrameTreeNode* frame = render_frame_host->frame_tree_node();
487 frame->render_manager()->DidNavigateFrame(
488 render_frame_host, params.gesture == NavigationGestureUser);
491 // Update the site of the SiteInstance if it doesn't have one yet, unless
492 // assigning a site is not necessary for this URL. In that case, the
493 // SiteInstance can still be considered unused until a navigation to a real
494 // page.
495 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
496 if (!site_instance->HasSite() &&
497 ShouldAssignSiteForURL(params.url)) {
498 site_instance->SetSite(params.url);
501 // Need to update MIME type here because it's referred to in
502 // UpdateNavigationCommands() called by RendererDidNavigate() to
503 // determine whether or not to enable the encoding menu.
504 // It's updated only for the main frame. For a subframe,
505 // RenderView::UpdateURL does not set params.contents_mime_type.
506 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
507 // TODO(jungshik): Add a test for the encoding menu to avoid
508 // regressing it again.
509 // TODO(nasko): Verify the correctness of the above comment, since some of the
510 // code doesn't exist anymore. Also, move this code in the
511 // PageTransitionIsMainFrame code block above.
512 if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
513 delegate_->SetMainFrameMimeType(params.contents_mime_type);
515 LoadCommittedDetails details;
516 bool did_navigate = controller_->RendererDidNavigate(render_frame_host,
517 params, &details);
519 // For now, keep track of each frame's URL in its FrameTreeNode. This lets
520 // us estimate our process count for implementing OOP iframes.
521 // TODO(creis): Remove this when we track which pages commit in each frame.
522 render_frame_host->frame_tree_node()->set_current_url(params.url);
524 // Send notification about committed provisional loads. This notification is
525 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
526 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
527 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
528 DCHECK_EQ(!render_frame_host->GetParent(),
529 did_navigate ? details.is_main_frame : false);
530 ui::PageTransition transition_type = params.transition;
531 // Whether or not a page transition was triggered by going backward or
532 // forward in the history is only stored in the navigation controller's
533 // entry list.
534 if (did_navigate &&
535 (controller_->GetLastCommittedEntry()->GetTransitionType() &
536 ui::PAGE_TRANSITION_FORWARD_BACK)) {
537 transition_type = ui::PageTransitionFromInt(
538 params.transition | ui::PAGE_TRANSITION_FORWARD_BACK);
541 delegate_->DidCommitProvisionalLoad(render_frame_host,
542 params.url,
543 transition_type);
546 if (!did_navigate)
547 return; // No navigation happened.
549 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
550 // for the appropriate notification (best) or you can add it to
551 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
552 // necessary, please).
554 // TODO(carlosk): Move this out when PlzNavigate implementation properly calls
555 // the observer methods.
556 RecordNavigationMetrics(details, params, site_instance);
558 // Run post-commit tasks.
559 if (delegate_) {
560 if (details.is_main_frame) {
561 delegate_->DidNavigateMainFramePostCommit(render_frame_host,
562 details, params);
565 delegate_->DidNavigateAnyFramePostCommit(
566 render_frame_host, details, params);
570 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
571 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
572 // still be used for a normal web site.
573 if (url == GURL(url::kAboutBlankURL))
574 return false;
576 // The embedder will then have the opportunity to determine if the URL
577 // should "use up" the SiteInstance.
578 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
581 void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
582 const GURL& url,
583 SiteInstance* source_site_instance,
584 const Referrer& referrer,
585 WindowOpenDisposition disposition,
586 bool should_replace_current_entry,
587 bool user_gesture) {
588 SiteInstance* current_site_instance =
589 GetRenderManager(render_frame_host)->current_frame_host()->
590 GetSiteInstance();
591 // If this came from a swapped out RenderFrameHost, we only allow the request
592 // if we are still in the same BrowsingInstance.
593 // TODO(creis): Move this to RenderFrameProxyHost::OpenURL.
594 if (render_frame_host->is_swapped_out() &&
595 !render_frame_host->GetSiteInstance()->IsRelatedSiteInstance(
596 current_site_instance)) {
597 return;
600 // Delegate to RequestTransferURL because this is just the generic
601 // case where |old_request_id| is empty.
602 // TODO(creis): Pass the redirect_chain into this method to support client
603 // redirects. http://crbug.com/311721.
604 std::vector<GURL> redirect_chain;
605 RequestTransferURL(render_frame_host, url, source_site_instance,
606 redirect_chain, referrer, ui::PAGE_TRANSITION_LINK,
607 disposition, GlobalRequestID(),
608 should_replace_current_entry, user_gesture);
611 void NavigatorImpl::RequestTransferURL(
612 RenderFrameHostImpl* render_frame_host,
613 const GURL& url,
614 SiteInstance* source_site_instance,
615 const std::vector<GURL>& redirect_chain,
616 const Referrer& referrer,
617 ui::PageTransition page_transition,
618 WindowOpenDisposition disposition,
619 const GlobalRequestID& transferred_global_request_id,
620 bool should_replace_current_entry,
621 bool user_gesture) {
622 GURL dest_url(url);
623 SiteInstance* current_site_instance =
624 GetRenderManager(render_frame_host)->current_frame_host()->
625 GetSiteInstance();
626 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
627 current_site_instance, url)) {
628 dest_url = GURL(url::kAboutBlankURL);
631 int64 frame_tree_node_id = -1;
632 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
633 switches::kSitePerProcess)) {
634 frame_tree_node_id =
635 render_frame_host->frame_tree_node()->frame_tree_node_id();
637 OpenURLParams params(
638 dest_url, referrer, frame_tree_node_id, disposition, page_transition,
639 true /* is_renderer_initiated */);
640 params.source_site_instance = source_site_instance;
641 if (redirect_chain.size() > 0)
642 params.redirect_chain = redirect_chain;
643 params.transferred_global_request_id = transferred_global_request_id;
644 params.should_replace_current_entry = should_replace_current_entry;
645 params.user_gesture = user_gesture;
647 if (GetRenderManager(render_frame_host)->web_ui()) {
648 // Web UI pages sometimes want to override the page transition type for
649 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
650 // automatically generated suggestions). We don't override other types
651 // like TYPED because they have different implications (e.g., autocomplete).
652 if (ui::PageTransitionCoreTypeIs(
653 params.transition, ui::PAGE_TRANSITION_LINK))
654 params.transition =
655 GetRenderManager(render_frame_host)->web_ui()->
656 GetLinkTransitionType();
658 // Note also that we hide the referrer for Web UI pages. We don't really
659 // want web sites to see a referrer of "chrome://blah" (and some
660 // chrome: URLs might have search terms or other stuff we don't want to
661 // send to the site), so we send no referrer.
662 params.referrer = Referrer();
664 // Navigations in Web UI pages count as browser-initiated navigations.
665 params.is_renderer_initiated = false;
668 if (delegate_)
669 delegate_->RequestOpenURL(render_frame_host, params);
672 // PlzNavigate
673 void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
674 bool proceed) {
675 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
676 switches::kEnableBrowserSideNavigation));
677 DCHECK(frame_tree_node);
679 NavigationRequest* navigation_request =
680 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
682 // The NavigationRequest may have been canceled while the renderer was
683 // executing the BeforeUnload event.
684 if (!navigation_request)
685 return;
687 DCHECK_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
688 navigation_request->state());
690 if (proceed)
691 BeginNavigation(frame_tree_node);
692 else
693 CancelNavigation(frame_tree_node);
696 // PlzNavigate
697 void NavigatorImpl::OnBeginNavigation(
698 FrameTreeNode* frame_tree_node,
699 const CommonNavigationParams& common_params,
700 const BeginNavigationParams& begin_params,
701 scoped_refptr<ResourceRequestBody> body) {
702 // This is a renderer-initiated navigation.
703 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
704 switches::kEnableBrowserSideNavigation));
705 DCHECK(frame_tree_node);
707 NavigationRequest* ongoing_navigation_request =
708 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
710 // The renderer-initiated navigation request is ignored iff a) there is an
711 // ongoing request b) which is browser or user-initiated and c) the renderer
712 // request is not user-initiated.
713 if (ongoing_navigation_request &&
714 (ongoing_navigation_request->browser_initiated() ||
715 ongoing_navigation_request->begin_params().has_user_gesture) &&
716 !begin_params.has_user_gesture) {
717 return;
720 // In all other cases the current navigation, if any, is canceled and a new
721 // NavigationRequest is created and stored in the map. Actual cancellation
722 // happens when the existing request map entry is replaced and destroyed.
723 scoped_ptr<NavigationRequest> navigation_request =
724 NavigationRequest::CreateRendererInitiated(
725 frame_tree_node, common_params, begin_params, body);
726 navigation_request_map_.set(
727 frame_tree_node->frame_tree_node_id(), navigation_request.Pass());
729 if (frame_tree_node->IsMainFrame())
730 navigation_data_.reset();
732 BeginNavigation(frame_tree_node);
735 // PlzNavigate
736 void NavigatorImpl::CommitNavigation(FrameTreeNode* frame_tree_node,
737 ResourceResponse* response,
738 scoped_ptr<StreamHandle> body) {
739 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
740 switches::kEnableBrowserSideNavigation));
742 // HTTP 204 (No Content) and HTTP 205 (Reset Content) responses should not
743 // commit; they leave the frame showing the previous page.
744 if (response->head.headers.get() &&
745 (response->head.headers->response_code() == 204 ||
746 response->head.headers->response_code() == 205)) {
747 CancelNavigation(frame_tree_node);
748 return;
751 NavigationRequest* navigation_request =
752 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
753 DCHECK(navigation_request);
755 // Select an appropriate renderer to commit the navigation.
756 RenderFrameHostImpl* render_frame_host =
757 frame_tree_node->render_manager()->GetFrameHostForNavigation(
758 *navigation_request);
759 CheckWebUIRendererDoesNotDisplayNormalURL(
760 render_frame_host, navigation_request->common_params().url);
762 render_frame_host->CommitNavigation(response, body.Pass(),
763 navigation_request->common_params(),
764 navigation_request->commit_params());
767 // PlzNavigate
768 void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) {
769 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
770 switches::kEnableBrowserSideNavigation));
771 navigation_request_map_.erase(frame_tree_node->frame_tree_node_id());
772 if (frame_tree_node->IsMainFrame())
773 navigation_data_.reset();
774 // TODO(carlosk): move this cleanup into the NavigationRequest destructor once
775 // we properly cancel ongoing navigations.
776 frame_tree_node->render_manager()->CleanUpNavigation();
779 // PlzNavigate
780 NavigationRequest* NavigatorImpl::GetNavigationRequestForNodeForTesting(
781 FrameTreeNode* frame_tree_node) {
782 return navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
785 bool NavigatorImpl::IsWaitingForBeforeUnloadACK(
786 FrameTreeNode* frame_tree_node) {
787 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
788 switches::kEnableBrowserSideNavigation));
789 NavigationRequest* request =
790 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
791 if (!request)
792 return false;
793 return request->state() == NavigationRequest::WAITING_FOR_RENDERER_RESPONSE;
796 void NavigatorImpl::LogResourceRequestTime(
797 base::TimeTicks timestamp, const GURL& url) {
798 if (navigation_data_ && navigation_data_->url_ == url) {
799 navigation_data_->url_job_start_time_ = timestamp;
800 UMA_HISTOGRAM_TIMES(
801 "Navigation.TimeToURLJobStart",
802 navigation_data_->url_job_start_time_ - navigation_data_->start_time_);
806 void NavigatorImpl::LogBeforeUnloadTime(
807 const base::TimeTicks& renderer_before_unload_start_time,
808 const base::TimeTicks& renderer_before_unload_end_time) {
809 // Only stores the beforeunload delay if we're tracking a browser initiated
810 // navigation and it happened later than the navigation request.
811 if (navigation_data_ &&
812 renderer_before_unload_start_time > navigation_data_->start_time_) {
813 navigation_data_->before_unload_delay_ =
814 renderer_before_unload_end_time - renderer_before_unload_start_time;
818 void NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL(
819 RenderFrameHostImpl* render_frame_host,
820 const GURL& url) {
821 int enabled_bindings =
822 render_frame_host->render_view_host()->GetEnabledBindings();
823 bool is_allowed_in_web_ui_renderer =
824 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
825 controller_->GetBrowserContext(), url);
826 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
827 !is_allowed_in_web_ui_renderer) {
828 // Log the URL to help us diagnose any future failures of this CHECK.
829 GetContentClient()->SetActiveURL(url);
830 CHECK(0);
834 // PlzNavigate
835 void NavigatorImpl::RequestNavigation(
836 FrameTreeNode* frame_tree_node,
837 const NavigationEntryImpl& entry,
838 NavigationController::ReloadType reload_type,
839 base::TimeTicks navigation_start) {
840 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
841 switches::kEnableBrowserSideNavigation));
842 DCHECK(frame_tree_node);
843 int64 frame_tree_node_id = frame_tree_node->frame_tree_node_id();
844 FrameMsg_Navigate_Type::Value navigation_type =
845 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
846 scoped_ptr<NavigationRequest> navigation_request =
847 NavigationRequest::CreateBrowserInitiated(
848 frame_tree_node, entry, navigation_type, navigation_start);
849 // TODO(clamy): Check if navigations are blocked and if so store the
850 // parameters.
852 // If there is an ongoing request, replace it.
853 navigation_request_map_.set(frame_tree_node_id, navigation_request.Pass());
855 // Have the current renderer execute its beforeUnload event if needed. If it
856 // is not needed (eg. the renderer is not live), BeginNavigation should get
857 // called.
858 NavigationRequest* request_to_send =
859 navigation_request_map_.get(frame_tree_node_id);
860 request_to_send->SetWaitingForRendererResponse();
861 frame_tree_node->current_frame_host()->DispatchBeforeUnload(true);
864 void NavigatorImpl::BeginNavigation(FrameTreeNode* frame_tree_node) {
865 NavigationRequest* navigation_request =
866 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
868 // A browser-initiated navigation could have been cancelled while it was
869 // waiting for the BeforeUnload event to execute.
870 if (!navigation_request)
871 return;
873 // First start the request on the IO thread.
874 navigation_request->BeginNavigation();
876 // Then notify the RenderFrameHostManager so it can speculatively create a
877 // RenderFrameHost (and potentially a new renderer process) in parallel.
878 frame_tree_node->render_manager()->BeginNavigation(*navigation_request);
881 void NavigatorImpl::RecordNavigationMetrics(
882 const LoadCommittedDetails& details,
883 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
884 SiteInstance* site_instance) {
885 DCHECK(site_instance->HasProcess());
887 if (!details.is_in_page)
888 RecordAction(base::UserMetricsAction("FrameLoad"));
890 if (!details.is_main_frame || !navigation_data_ ||
891 navigation_data_->url_job_start_time_.is_null() ||
892 navigation_data_->url_ != params.original_request_url) {
893 return;
896 base::TimeDelta time_to_commit =
897 base::TimeTicks::Now() - navigation_data_->start_time_;
898 UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit);
900 time_to_commit -= navigation_data_->before_unload_delay_;
901 base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ -
902 navigation_data_->start_time_ -
903 navigation_data_->before_unload_delay_;
904 if (navigation_data_->is_restoring_from_last_session_) {
905 UMA_HISTOGRAM_TIMES(
906 "Navigation.TimeToCommit_SessionRestored_BeforeUnloadDiscounted",
907 time_to_commit);
908 UMA_HISTOGRAM_TIMES(
909 "Navigation.TimeToURLJobStart_SessionRestored_BeforeUnloadDiscounted",
910 time_to_network);
911 navigation_data_.reset();
912 return;
914 bool navigation_created_new_renderer_process =
915 site_instance->GetProcess()->GetInitTimeForNavigationMetrics() >
916 navigation_data_->start_time_;
917 if (navigation_created_new_renderer_process) {
918 UMA_HISTOGRAM_TIMES(
919 "Navigation.TimeToCommit_NewRenderer_BeforeUnloadDiscounted",
920 time_to_commit);
921 UMA_HISTOGRAM_TIMES(
922 "Navigation.TimeToURLJobStart_NewRenderer_BeforeUnloadDiscounted",
923 time_to_network);
924 } else {
925 UMA_HISTOGRAM_TIMES(
926 "Navigation.TimeToCommit_ExistingRenderer_BeforeUnloadDiscounted",
927 time_to_commit);
928 UMA_HISTOGRAM_TIMES(
929 "Navigation.TimeToURLJobStart_ExistingRenderer_BeforeUnloadDiscounted",
930 time_to_network);
932 navigation_data_.reset();
935 } // namespace content