Fix the commit type for out-of-process iframes.
[chromium-blink-merge.git] / content / browser / frame_host / navigator_impl.cc
blob8219a3d79518bc95ca9ff998a620c0f149838a86
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_error_page = (url.spec() == kUnreachableWebDataURL);
122 bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL);
123 GURL validated_url(url);
124 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
125 render_process_host->FilterURL(false, &validated_url);
127 bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame();
128 NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
129 if (is_main_frame) {
130 // If there is no browser-initiated pending entry for this navigation and it
131 // is not for the error URL, create a pending entry using the current
132 // SiteInstance, and ensure the address bar updates accordingly. We don't
133 // know the referrer or extra headers at this point, but the referrer will
134 // be set properly upon commit.
135 bool has_browser_initiated_pending_entry = pending_entry &&
136 !pending_entry->is_renderer_initiated();
137 if (!has_browser_initiated_pending_entry && !is_error_page) {
138 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
139 controller_->CreateNavigationEntry(validated_url,
140 content::Referrer(),
141 ui::PAGE_TRANSITION_LINK,
142 true /* is_renderer_initiated */,
143 std::string(),
144 controller_->GetBrowserContext()));
145 entry->set_site_instance(render_frame_host->GetSiteInstance());
146 // TODO(creis): If there's a pending entry already, find a safe way to
147 // update it instead of replacing it and copying over things like this.
148 if (pending_entry) {
149 entry->set_transferred_global_request_id(
150 pending_entry->transferred_global_request_id());
151 entry->set_should_replace_entry(pending_entry->should_replace_entry());
152 entry->SetRedirectChain(pending_entry->GetRedirectChain());
154 controller_->SetPendingEntry(entry);
155 if (delegate_)
156 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
160 if (delegate_) {
161 // Notify the observer about the start of the provisional load.
162 delegate_->DidStartProvisionalLoad(
163 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc);
168 void NavigatorImpl::DidFailProvisionalLoadWithError(
169 RenderFrameHostImpl* render_frame_host,
170 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
171 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
172 << ", error_code: " << params.error_code
173 << ", error_description: " << params.error_description
174 << ", showing_repost_interstitial: " <<
175 params.showing_repost_interstitial
176 << ", frame_id: " << render_frame_host->GetRoutingID();
177 GURL validated_url(params.url);
178 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
179 render_process_host->FilterURL(false, &validated_url);
181 if (net::ERR_ABORTED == params.error_code) {
182 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
183 // This means that the interstitial won't be torn down properly, which is
184 // bad. But if we have an interstitial, go back to another tab type, and
185 // then load the same interstitial again, we could end up getting the first
186 // interstitial's "failed" message (as a result of the cancel) when we're on
187 // the second one. We can't tell this apart, so we think we're tearing down
188 // the current page which will cause a crash later on.
190 // http://code.google.com/p/chromium/issues/detail?id=2855
191 // Because this will not tear down the interstitial properly, if "back" is
192 // back to another tab type, the interstitial will still be somewhat alive
193 // in the previous tab type. If you navigate somewhere that activates the
194 // tab with the interstitial again, you'll see a flash before the new load
195 // commits of the interstitial page.
196 FrameTreeNode* root =
197 render_frame_host->frame_tree_node()->frame_tree()->root();
198 if (root->render_manager()->interstitial_page() != NULL) {
199 LOG(WARNING) << "Discarding message during interstitial.";
200 return;
203 // We used to cancel the pending renderer here for cross-site downloads.
204 // However, it's not safe to do that because the download logic repeatedly
205 // looks for this WebContents based on a render ID. Instead, we just
206 // leave the pending renderer around until the next navigation event
207 // (Navigate, DidNavigate, etc), which will clean it up properly.
209 // TODO(creis): Find a way to cancel any pending RFH here.
212 // We usually clear the pending entry when it fails, so that an arbitrary URL
213 // isn't left visible above a committed page. This must be enforced when
214 // the pending entry isn't visible (e.g., renderer-initiated navigations) to
215 // prevent URL spoofs for in-page navigations that don't go through
216 // DidStartProvisionalLoadForFrame.
218 // However, we do preserve the pending entry in some cases, such as on the
219 // initial navigation of an unmodified blank tab. We also allow the delegate
220 // to say when it's safe to leave aborted URLs in the omnibox, to let the user
221 // edit the URL and try again. This may be useful in cases that the committed
222 // page cannot be attacker-controlled. In these cases, we still allow the
223 // view to clear the pending entry and typed URL if the user requests
224 // (e.g., hitting Escape with focus in the address bar).
226 // Note: don't touch the transient entry, since an interstitial may exist.
227 bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() ||
228 delegate_->ShouldPreserveAbortedURLs();
229 if (controller_->GetPendingEntry() != controller_->GetVisibleEntry() ||
230 !should_preserve_entry) {
231 controller_->DiscardPendingEntry(true);
233 // Also force the UI to refresh.
234 controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
237 if (delegate_)
238 delegate_->DidFailProvisionalLoadWithError(render_frame_host, params);
241 void NavigatorImpl::DidFailLoadWithError(
242 RenderFrameHostImpl* render_frame_host,
243 const GURL& url,
244 int error_code,
245 const base::string16& error_description) {
246 if (delegate_) {
247 delegate_->DidFailLoadWithError(
248 render_frame_host, url, error_code,
249 error_description);
253 bool NavigatorImpl::NavigateToEntry(
254 FrameTreeNode* frame_tree_node,
255 const NavigationEntryImpl& entry,
256 NavigationController::ReloadType reload_type) {
257 TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
259 // The renderer will reject IPC messages with URLs longer than
260 // this limit, so don't attempt to navigate with a longer URL.
261 if (entry.GetURL().spec().size() > GetMaxURLChars()) {
262 LOG(WARNING) << "Refusing to load URL as it exceeds " << GetMaxURLChars()
263 << " characters.";
264 return false;
267 // This will be used to set the Navigation Timing API navigationStart
268 // parameter for browser navigations in new tabs (intents, tabs opened through
269 // "Open link in new tab"). We need to keep it above RFHM::Navigate() call to
270 // capture the time needed for the RenderFrameHost initialization.
271 base::TimeTicks navigation_start = base::TimeTicks::Now();
273 RenderFrameHostManager* manager = frame_tree_node->render_manager();
275 // PlzNavigate: the RenderFrameHosts are no longer asked to navigate.
276 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
277 switches::kEnableBrowserSideNavigation)) {
278 navigation_data_.reset(new NavigationMetricsData(
279 navigation_start, entry.GetURL(), entry.restore_type()));
280 RequestNavigation(frame_tree_node, entry, reload_type, navigation_start);
282 // Notify observers about navigation.
283 if (delegate_)
284 delegate_->DidStartNavigationToPendingEntry(entry.GetURL(), reload_type);
286 return true;
289 RenderFrameHostImpl* dest_render_frame_host = manager->Navigate(entry);
290 if (!dest_render_frame_host)
291 return false; // Unable to create the desired RenderFrameHost.
293 // Make sure no code called via RFHM::Navigate clears the pending entry.
294 CHECK_EQ(controller_->GetPendingEntry(), &entry);
296 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
297 // Double check that here.
298 CheckWebUIRendererDoesNotDisplayNormalURL(
299 dest_render_frame_host, entry.GetURL());
301 // Notify observers that we will navigate in this RenderFrame.
302 if (delegate_) {
303 delegate_->AboutToNavigateRenderFrame(frame_tree_node->current_frame_host(),
304 dest_render_frame_host);
307 // Navigate in the desired RenderFrameHost.
308 // We can skip this step in the rare case that this is a transfer navigation
309 // which began in the chosen RenderFrameHost, since the request has already
310 // been issued. In that case, simply resume the response.
311 bool is_transfer_to_same =
312 entry.transferred_global_request_id().child_id != -1 &&
313 entry.transferred_global_request_id().child_id ==
314 dest_render_frame_host->GetProcess()->GetID();
315 if (!is_transfer_to_same) {
316 navigation_data_.reset(new NavigationMetricsData(
317 navigation_start, entry.GetURL(), entry.restore_type()));
318 // Create the navigation parameters.
319 // TODO(vitalybuka): Move this before AboutToNavigateRenderFrame once
320 // http://crbug.com/408684 is fixed.
321 FrameMsg_Navigate_Type::Value navigation_type =
322 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
323 dest_render_frame_host->Navigate(
324 entry.ConstructCommonNavigationParams(navigation_type),
325 entry.ConstructStartNavigationParams(),
326 entry.ConstructRequestNavigationParams(
327 navigation_start,
328 controller_->HasCommittedRealLoad(frame_tree_node),
329 controller_->GetPendingEntryIndex() == -1,
330 controller_->GetIndexOfEntry(&entry),
331 controller_->GetLastCommittedEntryIndex(),
332 controller_->GetEntryCount()));
333 } else {
334 // No need to navigate again. Just resume the deferred request.
335 dest_render_frame_host->GetProcess()->ResumeDeferredNavigation(
336 entry.transferred_global_request_id());
339 // Make sure no code called via RFH::Navigate clears the pending entry.
340 CHECK_EQ(controller_->GetPendingEntry(), &entry);
342 if (entry.GetPageID() == -1) {
343 // HACK!! This code suppresses javascript: URLs from being added to
344 // session history, which is what we want to do for javascript: URLs that
345 // do not generate content. What we really need is a message from the
346 // renderer telling us that a new page was not created. The same message
347 // could be used for mailto: URLs and the like.
348 if (entry.GetURL().SchemeIs(url::kJavaScriptScheme))
349 return false;
352 // Notify observers about navigation.
353 if (delegate_)
354 delegate_->DidStartNavigationToPendingEntry(entry.GetURL(), reload_type);
356 return true;
359 bool NavigatorImpl::NavigateToPendingEntry(
360 FrameTreeNode* frame_tree_node,
361 NavigationController::ReloadType reload_type) {
362 return NavigateToEntry(frame_tree_node, *controller_->GetPendingEntry(),
363 reload_type);
366 void NavigatorImpl::DidNavigate(
367 RenderFrameHostImpl* render_frame_host,
368 const FrameHostMsg_DidCommitProvisionalLoad_Params& input_params) {
369 // PlzNavigate
370 // The navigation request has been committed so the browser process doesn't
371 // need to care about it anymore.
372 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
373 switches::kEnableBrowserSideNavigation)) {
374 render_frame_host->frame_tree_node()->ResetNavigationRequest(true);
377 FrameHostMsg_DidCommitProvisionalLoad_Params params(input_params);
378 FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
379 bool use_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
380 switches::kSitePerProcess);
382 if (ui::PageTransitionIsMainFrame(params.transition)) {
383 if (delegate_) {
384 // When overscroll navigation gesture is enabled, a screenshot of the page
385 // in its current state is taken so that it can be used during the
386 // nav-gesture. It is necessary to take the screenshot here, before
387 // calling RenderFrameHostManager::DidNavigateMainFrame, because that can
388 // change WebContents::GetRenderViewHost to return the new host, instead
389 // of the one that may have just been swapped out.
390 if (delegate_->CanOverscrollContent()) {
391 // Don't take screenshots if we are staying on the same page. We want
392 // in-page navigations to be super fast, and taking a screenshot
393 // currently blocks GPU for a longer time than we are willing to
394 // tolerate in this use case.
395 if (!params.was_within_same_page)
396 controller_->TakeScreenshot();
399 // Run tasks that must execute just before the commit.
400 bool is_navigation_within_page = controller_->IsURLInPageNavigation(
401 params.url, params.was_within_same_page, render_frame_host);
402 delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
405 if (!use_site_per_process)
406 frame_tree->root()->render_manager()->DidNavigateFrame(
407 render_frame_host, params.gesture == NavigationGestureUser);
410 // Save the origin of the new page. Do this before calling
411 // DidNavigateFrame(), because the origin needs to be included in the SwapOut
412 // message, which is sent inside DidNavigateFrame(). SwapOut needs the
413 // origin because it creates a RenderFrameProxy that needs this to initialize
414 // its security context. This origin will also be sent to RenderFrameProxies
415 // created via ViewMsg_New and FrameMsg_NewFrameProxy.
416 render_frame_host->frame_tree_node()->SetCurrentOrigin(params.origin);
418 // When using --site-per-process, we notify the RFHM for all navigations,
419 // not just main frame navigations.
420 if (use_site_per_process) {
421 FrameTreeNode* frame = render_frame_host->frame_tree_node();
422 frame->render_manager()->DidNavigateFrame(
423 render_frame_host, params.gesture == NavigationGestureUser);
426 // Update the site of the SiteInstance if it doesn't have one yet, unless
427 // assigning a site is not necessary for this URL. In that case, the
428 // SiteInstance can still be considered unused until a navigation to a real
429 // page.
430 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
431 if (!site_instance->HasSite() &&
432 ShouldAssignSiteForURL(params.url)) {
433 site_instance->SetSite(params.url);
436 // Need to update MIME type here because it's referred to in
437 // UpdateNavigationCommands() called by RendererDidNavigate() to
438 // determine whether or not to enable the encoding menu.
439 // It's updated only for the main frame. For a subframe,
440 // RenderView::UpdateURL does not set params.contents_mime_type.
441 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
442 // TODO(jungshik): Add a test for the encoding menu to avoid
443 // regressing it again.
444 // TODO(nasko): Verify the correctness of the above comment, since some of the
445 // code doesn't exist anymore. Also, move this code in the
446 // PageTransitionIsMainFrame code block above.
447 if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
448 delegate_->SetMainFrameMimeType(params.contents_mime_type);
450 LoadCommittedDetails details;
451 bool did_navigate = controller_->RendererDidNavigate(render_frame_host,
452 params, &details);
454 // For now, keep track of each frame's URL in its FrameTreeNode. This lets
455 // us estimate our process count for implementing OOP iframes.
456 // TODO(creis): Remove this when we track which pages commit in each frame.
457 render_frame_host->frame_tree_node()->set_current_url(params.url);
459 // Send notification about committed provisional loads. This notification is
460 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
461 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
462 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
463 DCHECK_EQ(!render_frame_host->GetParent(),
464 did_navigate ? details.is_main_frame : false);
465 ui::PageTransition transition_type = params.transition;
466 // Whether or not a page transition was triggered by going backward or
467 // forward in the history is only stored in the navigation controller's
468 // entry list.
469 if (did_navigate &&
470 (controller_->GetLastCommittedEntry()->GetTransitionType() &
471 ui::PAGE_TRANSITION_FORWARD_BACK)) {
472 transition_type = ui::PageTransitionFromInt(
473 params.transition | ui::PAGE_TRANSITION_FORWARD_BACK);
476 delegate_->DidCommitProvisionalLoad(render_frame_host,
477 params.url,
478 transition_type);
481 if (!did_navigate)
482 return; // No navigation happened.
484 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
485 // for the appropriate notification (best) or you can add it to
486 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
487 // necessary, please).
489 // TODO(carlosk): Move this out when PlzNavigate implementation properly calls
490 // the observer methods.
491 RecordNavigationMetrics(details, params, site_instance);
493 // Run post-commit tasks.
494 if (delegate_) {
495 if (details.is_main_frame) {
496 delegate_->DidNavigateMainFramePostCommit(render_frame_host,
497 details, params);
500 delegate_->DidNavigateAnyFramePostCommit(
501 render_frame_host, details, params);
505 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
506 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
507 // still be used for a normal web site.
508 if (url == GURL(url::kAboutBlankURL))
509 return false;
511 // The embedder will then have the opportunity to determine if the URL
512 // should "use up" the SiteInstance.
513 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
516 void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
517 const GURL& url,
518 SiteInstance* source_site_instance,
519 const Referrer& referrer,
520 WindowOpenDisposition disposition,
521 bool should_replace_current_entry,
522 bool user_gesture) {
523 SiteInstance* current_site_instance =
524 GetRenderManager(render_frame_host)->current_frame_host()->
525 GetSiteInstance();
526 // If this came from a swapped out RenderFrameHost, we only allow the request
527 // if we are still in the same BrowsingInstance.
528 // TODO(creis): Move this to RenderFrameProxyHost::OpenURL.
529 if (render_frame_host->is_swapped_out() &&
530 !render_frame_host->GetSiteInstance()->IsRelatedSiteInstance(
531 current_site_instance)) {
532 return;
535 // Delegate to RequestTransferURL because this is just the generic
536 // case where |old_request_id| is empty.
537 // TODO(creis): Pass the redirect_chain into this method to support client
538 // redirects. http://crbug.com/311721.
539 std::vector<GURL> redirect_chain;
540 RequestTransferURL(render_frame_host, url, source_site_instance,
541 redirect_chain, referrer, ui::PAGE_TRANSITION_LINK,
542 disposition, GlobalRequestID(),
543 should_replace_current_entry, user_gesture);
546 void NavigatorImpl::RequestTransferURL(
547 RenderFrameHostImpl* render_frame_host,
548 const GURL& url,
549 SiteInstance* source_site_instance,
550 const std::vector<GURL>& redirect_chain,
551 const Referrer& referrer,
552 ui::PageTransition page_transition,
553 WindowOpenDisposition disposition,
554 const GlobalRequestID& transferred_global_request_id,
555 bool should_replace_current_entry,
556 bool user_gesture) {
557 GURL dest_url(url);
558 SiteInstance* current_site_instance =
559 GetRenderManager(render_frame_host)->current_frame_host()->
560 GetSiteInstance();
561 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
562 current_site_instance, url)) {
563 dest_url = GURL(url::kAboutBlankURL);
566 int frame_tree_node_id = -1;
568 // Send the navigation to the current FrameTreeNode if it's destined for a
569 // subframe in the current tab. We'll assume it's for the main frame
570 // (possibly of a new or different WebContents) otherwise.
571 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
572 switches::kSitePerProcess) &&
573 disposition == CURRENT_TAB &&
574 render_frame_host->GetParent()) {
575 frame_tree_node_id =
576 render_frame_host->frame_tree_node()->frame_tree_node_id();
579 OpenURLParams params(
580 dest_url, referrer, frame_tree_node_id, disposition, page_transition,
581 true /* is_renderer_initiated */);
582 params.source_site_instance = source_site_instance;
583 if (redirect_chain.size() > 0)
584 params.redirect_chain = redirect_chain;
585 params.transferred_global_request_id = transferred_global_request_id;
586 params.should_replace_current_entry = should_replace_current_entry;
587 params.user_gesture = user_gesture;
589 if (GetRenderManager(render_frame_host)->web_ui()) {
590 // Web UI pages sometimes want to override the page transition type for
591 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
592 // automatically generated suggestions). We don't override other types
593 // like TYPED because they have different implications (e.g., autocomplete).
594 if (ui::PageTransitionCoreTypeIs(
595 params.transition, ui::PAGE_TRANSITION_LINK))
596 params.transition =
597 GetRenderManager(render_frame_host)->web_ui()->
598 GetLinkTransitionType();
600 // Note also that we hide the referrer for Web UI pages. We don't really
601 // want web sites to see a referrer of "chrome://blah" (and some
602 // chrome: URLs might have search terms or other stuff we don't want to
603 // send to the site), so we send no referrer.
604 params.referrer = Referrer();
606 // Navigations in Web UI pages count as browser-initiated navigations.
607 params.is_renderer_initiated = false;
610 if (delegate_)
611 delegate_->RequestOpenURL(render_frame_host, params);
614 // PlzNavigate
615 void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
616 bool proceed) {
617 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
618 switches::kEnableBrowserSideNavigation));
619 DCHECK(frame_tree_node);
621 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
623 // The NavigationRequest may have been canceled while the renderer was
624 // executing the BeforeUnload event.
625 if (!navigation_request)
626 return;
628 DCHECK_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
629 navigation_request->state());
631 if (proceed)
632 BeginNavigation(frame_tree_node);
633 else
634 CancelNavigation(frame_tree_node);
637 // PlzNavigate
638 void NavigatorImpl::OnBeginNavigation(
639 FrameTreeNode* frame_tree_node,
640 const CommonNavigationParams& common_params,
641 const BeginNavigationParams& begin_params,
642 scoped_refptr<ResourceRequestBody> body) {
643 // This is a renderer-initiated navigation.
644 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
645 switches::kEnableBrowserSideNavigation));
646 DCHECK(frame_tree_node);
648 NavigationRequest* ongoing_navigation_request =
649 frame_tree_node->navigation_request();
651 // The renderer-initiated navigation request is ignored iff a) there is an
652 // ongoing request b) which is browser or user-initiated and c) the renderer
653 // request is not user-initiated.
654 if (ongoing_navigation_request &&
655 (ongoing_navigation_request->browser_initiated() ||
656 ongoing_navigation_request->begin_params().has_user_gesture) &&
657 !begin_params.has_user_gesture) {
658 return;
661 // In all other cases the current navigation, if any, is canceled and a new
662 // NavigationRequest is created for the node.
663 scoped_ptr<NavigationRequest> navigation_request =
664 NavigationRequest::CreateRendererInitiated(
665 frame_tree_node, common_params, begin_params, body,
666 controller_->GetLastCommittedEntryIndex(),
667 controller_->GetEntryCount());
668 frame_tree_node->SetNavigationRequest(navigation_request.Pass());
670 if (frame_tree_node->IsMainFrame())
671 navigation_data_.reset();
673 BeginNavigation(frame_tree_node);
676 // PlzNavigate
677 void NavigatorImpl::CommitNavigation(FrameTreeNode* frame_tree_node,
678 ResourceResponse* response,
679 scoped_ptr<StreamHandle> body) {
680 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
681 switches::kEnableBrowserSideNavigation));
683 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
684 DCHECK(navigation_request);
685 DCHECK(response ||
686 !NavigationRequest::ShouldMakeNetworkRequest(
687 navigation_request->common_params().url));
689 // HTTP 204 (No Content) and HTTP 205 (Reset Content) responses should not
690 // commit; they leave the frame showing the previous page.
691 if (response && response->head.headers.get() &&
692 (response->head.headers->response_code() == 204 ||
693 response->head.headers->response_code() == 205)) {
694 CancelNavigation(frame_tree_node);
695 return;
698 // Select an appropriate renderer to commit the navigation.
699 RenderFrameHostImpl* render_frame_host =
700 frame_tree_node->render_manager()->GetFrameHostForNavigation(
701 *navigation_request);
703 // The renderer can exit view source mode when any error or cancellation
704 // happen. When reusing the same renderer, overwrite to recover the mode.
705 if (navigation_request->is_view_source() &&
706 render_frame_host ==
707 frame_tree_node->render_manager()->current_frame_host()) {
708 DCHECK(!render_frame_host->GetParent());
709 render_frame_host->render_view_host()->Send(
710 new ViewMsg_EnableViewSourceMode(
711 render_frame_host->render_view_host()->GetRoutingID()));
714 CheckWebUIRendererDoesNotDisplayNormalURL(
715 render_frame_host, navigation_request->common_params().url);
717 render_frame_host->CommitNavigation(response, body.Pass(),
718 navigation_request->common_params(),
719 navigation_request->request_params());
722 // PlzNavigate
723 void NavigatorImpl::FailedNavigation(FrameTreeNode* frame_tree_node,
724 bool has_stale_copy_in_cache,
725 int error_code) {
726 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
727 switches::kEnableBrowserSideNavigation));
729 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
730 DCHECK(navigation_request);
732 // If the request was canceled by the user do not show an error page.
733 if (error_code == net::ERR_ABORTED) {
734 frame_tree_node->ResetNavigationRequest(false);
735 return;
738 // Select an appropriate renderer to show the error page.
739 RenderFrameHostImpl* render_frame_host =
740 frame_tree_node->render_manager()->GetFrameHostForNavigation(
741 *navigation_request);
742 CheckWebUIRendererDoesNotDisplayNormalURL(
743 render_frame_host, navigation_request->common_params().url);
745 render_frame_host->FailedNavigation(navigation_request->common_params(),
746 navigation_request->request_params(),
747 has_stale_copy_in_cache, error_code);
750 // PlzNavigate
751 void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) {
752 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
753 switches::kEnableBrowserSideNavigation));
754 frame_tree_node->ResetNavigationRequest(false);
755 if (frame_tree_node->IsMainFrame())
756 navigation_data_.reset();
759 bool NavigatorImpl::IsWaitingForBeforeUnloadACK(
760 FrameTreeNode* frame_tree_node) {
761 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
762 switches::kEnableBrowserSideNavigation));
763 NavigationRequest* request = frame_tree_node->navigation_request();
764 if (!request)
765 return false;
766 return request->state() == NavigationRequest::WAITING_FOR_RENDERER_RESPONSE;
769 void NavigatorImpl::LogResourceRequestTime(
770 base::TimeTicks timestamp, const GURL& url) {
771 if (navigation_data_ && navigation_data_->url_ == url) {
772 navigation_data_->url_job_start_time_ = timestamp;
773 UMA_HISTOGRAM_TIMES(
774 "Navigation.TimeToURLJobStart",
775 navigation_data_->url_job_start_time_ - navigation_data_->start_time_);
779 void NavigatorImpl::LogBeforeUnloadTime(
780 const base::TimeTicks& renderer_before_unload_start_time,
781 const base::TimeTicks& renderer_before_unload_end_time) {
782 // Only stores the beforeunload delay if we're tracking a browser initiated
783 // navigation and it happened later than the navigation request.
784 if (navigation_data_ &&
785 renderer_before_unload_start_time > navigation_data_->start_time_) {
786 navigation_data_->before_unload_delay_ =
787 renderer_before_unload_end_time - renderer_before_unload_start_time;
791 void NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL(
792 RenderFrameHostImpl* render_frame_host,
793 const GURL& url) {
794 int enabled_bindings =
795 render_frame_host->render_view_host()->GetEnabledBindings();
796 bool is_allowed_in_web_ui_renderer =
797 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
798 controller_->GetBrowserContext(), url);
799 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
800 !is_allowed_in_web_ui_renderer) {
801 // Log the URL to help us diagnose any future failures of this CHECK.
802 GetContentClient()->SetActiveURL(url);
803 CHECK(0);
807 // PlzNavigate
808 void NavigatorImpl::RequestNavigation(
809 FrameTreeNode* frame_tree_node,
810 const NavigationEntryImpl& entry,
811 NavigationController::ReloadType reload_type,
812 base::TimeTicks navigation_start) {
813 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
814 switches::kEnableBrowserSideNavigation));
815 DCHECK(frame_tree_node);
816 FrameMsg_Navigate_Type::Value navigation_type =
817 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
818 scoped_ptr<NavigationRequest> navigation_request =
819 NavigationRequest::CreateBrowserInitiated(frame_tree_node, entry,
820 navigation_type,
821 navigation_start, controller_);
822 frame_tree_node->SetNavigationRequest(navigation_request.Pass());
824 // Have the current renderer execute its beforeUnload event if needed. If it
825 // is not needed (eg. the renderer is not live), BeginNavigation should get
826 // called.
827 frame_tree_node->navigation_request()->SetWaitingForRendererResponse();
828 frame_tree_node->current_frame_host()->DispatchBeforeUnload(true);
831 void NavigatorImpl::BeginNavigation(FrameTreeNode* frame_tree_node) {
832 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
834 // A browser-initiated navigation could have been cancelled while it was
835 // waiting for the BeforeUnload event to execute.
836 if (!navigation_request)
837 return;
839 // Start the request.
840 if (navigation_request->BeginNavigation()) {
841 // If the request was sent to the IO thread, notify the
842 // RenderFrameHostManager so it can speculatively create a RenderFrameHost
843 // (and potentially a new renderer process) in parallel.
844 frame_tree_node->render_manager()->BeginNavigation(*navigation_request);
848 void NavigatorImpl::RecordNavigationMetrics(
849 const LoadCommittedDetails& details,
850 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
851 SiteInstance* site_instance) {
852 DCHECK(site_instance->HasProcess());
854 if (!details.is_in_page)
855 RecordAction(base::UserMetricsAction("FrameLoad"));
857 if (!details.is_main_frame || !navigation_data_ ||
858 navigation_data_->url_job_start_time_.is_null() ||
859 navigation_data_->url_ != params.original_request_url) {
860 return;
863 base::TimeDelta time_to_commit =
864 base::TimeTicks::Now() - navigation_data_->start_time_;
865 UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit);
867 time_to_commit -= navigation_data_->before_unload_delay_;
868 base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ -
869 navigation_data_->start_time_ -
870 navigation_data_->before_unload_delay_;
871 if (navigation_data_->is_restoring_from_last_session_) {
872 UMA_HISTOGRAM_TIMES(
873 "Navigation.TimeToCommit_SessionRestored_BeforeUnloadDiscounted",
874 time_to_commit);
875 UMA_HISTOGRAM_TIMES(
876 "Navigation.TimeToURLJobStart_SessionRestored_BeforeUnloadDiscounted",
877 time_to_network);
878 navigation_data_.reset();
879 return;
881 bool navigation_created_new_renderer_process =
882 site_instance->GetProcess()->GetInitTimeForNavigationMetrics() >
883 navigation_data_->start_time_;
884 if (navigation_created_new_renderer_process) {
885 UMA_HISTOGRAM_TIMES(
886 "Navigation.TimeToCommit_NewRenderer_BeforeUnloadDiscounted",
887 time_to_commit);
888 UMA_HISTOGRAM_TIMES(
889 "Navigation.TimeToURLJobStart_NewRenderer_BeforeUnloadDiscounted",
890 time_to_network);
891 } else {
892 UMA_HISTOGRAM_TIMES(
893 "Navigation.TimeToCommit_ExistingRenderer_BeforeUnloadDiscounted",
894 time_to_commit);
895 UMA_HISTOGRAM_TIMES(
896 "Navigation.TimeToURLJobStart_ExistingRenderer_BeforeUnloadDiscounted",
897 time_to_network);
899 navigation_data_.reset();
902 } // namespace content