Fix various typos, error handling for GN auto-roller.
[chromium-blink-merge.git] / content / browser / frame_host / navigator_impl.cc
blob878c9b10e20fca87cfd327659e8697de169c7306
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/site_isolation_policy.h"
25 #include "content/common/view_messages.h"
26 #include "content/public/browser/browser_context.h"
27 #include "content/public/browser/content_browser_client.h"
28 #include "content/public/browser/global_request_id.h"
29 #include "content/public/browser/invalidate_type.h"
30 #include "content/public/browser/navigation_controller.h"
31 #include "content/public/browser/navigation_details.h"
32 #include "content/public/browser/page_navigator.h"
33 #include "content/public/browser/render_view_host.h"
34 #include "content/public/browser/stream_handle.h"
35 #include "content/public/browser/user_metrics.h"
36 #include "content/public/common/bindings_policy.h"
37 #include "content/public/common/content_client.h"
38 #include "content/public/common/content_switches.h"
39 #include "content/public/common/resource_response.h"
40 #include "content/public/common/url_constants.h"
41 #include "content/public/common/url_utils.h"
42 #include "net/base/net_errors.h"
44 namespace content {
46 namespace {
48 FrameMsg_Navigate_Type::Value GetNavigationType(
49 BrowserContext* browser_context, const NavigationEntryImpl& entry,
50 NavigationController::ReloadType reload_type) {
51 switch (reload_type) {
52 case NavigationControllerImpl::RELOAD:
53 return FrameMsg_Navigate_Type::RELOAD;
54 case NavigationControllerImpl::RELOAD_IGNORING_CACHE:
55 return FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE;
56 case NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL:
57 return FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
58 case NavigationControllerImpl::NO_RELOAD:
59 break; // Fall through to rest of function.
62 // |RenderViewImpl::PopulateStateFromPendingNavigationParams| differentiates
63 // between |RESTORE_WITH_POST| and |RESTORE|.
64 if (entry.restore_type() ==
65 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY) {
66 if (entry.GetHasPostData())
67 return FrameMsg_Navigate_Type::RESTORE_WITH_POST;
68 return FrameMsg_Navigate_Type::RESTORE;
71 return FrameMsg_Navigate_Type::NORMAL;
74 RenderFrameHostManager* GetRenderManager(RenderFrameHostImpl* rfh) {
75 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
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 if (is_main_frame && !is_error_page)
129 DidStartMainFrameNavigation(validated_url,
130 render_frame_host->GetSiteInstance());
132 if (delegate_) {
133 // Notify the observer about the start of the provisional load.
134 delegate_->DidStartProvisionalLoad(
135 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc);
140 void NavigatorImpl::DidFailProvisionalLoadWithError(
141 RenderFrameHostImpl* render_frame_host,
142 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
143 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
144 << ", error_code: " << params.error_code
145 << ", error_description: " << params.error_description
146 << ", showing_repost_interstitial: " <<
147 params.showing_repost_interstitial
148 << ", frame_id: " << render_frame_host->GetRoutingID();
149 GURL validated_url(params.url);
150 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
151 render_process_host->FilterURL(false, &validated_url);
153 if (net::ERR_ABORTED == params.error_code) {
154 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
155 // This means that the interstitial won't be torn down properly, which is
156 // bad. But if we have an interstitial, go back to another tab type, and
157 // then load the same interstitial again, we could end up getting the first
158 // interstitial's "failed" message (as a result of the cancel) when we're on
159 // the second one. We can't tell this apart, so we think we're tearing down
160 // the current page which will cause a crash later on.
162 // http://code.google.com/p/chromium/issues/detail?id=2855
163 // Because this will not tear down the interstitial properly, if "back" is
164 // back to another tab type, the interstitial will still be somewhat alive
165 // in the previous tab type. If you navigate somewhere that activates the
166 // tab with the interstitial again, you'll see a flash before the new load
167 // commits of the interstitial page.
168 FrameTreeNode* root =
169 render_frame_host->frame_tree_node()->frame_tree()->root();
170 if (root->render_manager()->interstitial_page() != NULL) {
171 LOG(WARNING) << "Discarding message during interstitial.";
172 return;
175 // We used to cancel the pending renderer here for cross-site downloads.
176 // However, it's not safe to do that because the download logic repeatedly
177 // looks for this WebContents based on a render ID. Instead, we just
178 // leave the pending renderer around until the next navigation event
179 // (Navigate, DidNavigate, etc), which will clean it up properly.
181 // TODO(creis): Find a way to cancel any pending RFH here.
184 // We usually clear the pending entry when it fails, so that an arbitrary URL
185 // isn't left visible above a committed page. This must be enforced when
186 // the pending entry isn't visible (e.g., renderer-initiated navigations) to
187 // prevent URL spoofs for in-page navigations that don't go through
188 // DidStartProvisionalLoadForFrame.
190 // However, we do preserve the pending entry in some cases, such as on the
191 // initial navigation of an unmodified blank tab. We also allow the delegate
192 // to say when it's safe to leave aborted URLs in the omnibox, to let the user
193 // edit the URL and try again. This may be useful in cases that the committed
194 // page cannot be attacker-controlled. In these cases, we still allow the
195 // view to clear the pending entry and typed URL if the user requests
196 // (e.g., hitting Escape with focus in the address bar).
198 // Note: don't touch the transient entry, since an interstitial may exist.
199 bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() ||
200 delegate_->ShouldPreserveAbortedURLs();
201 if (controller_->GetPendingEntry() != controller_->GetVisibleEntry() ||
202 !should_preserve_entry) {
203 controller_->DiscardPendingEntry(true);
205 // Also force the UI to refresh.
206 controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
209 if (delegate_)
210 delegate_->DidFailProvisionalLoadWithError(render_frame_host, params);
213 void NavigatorImpl::DidFailLoadWithError(
214 RenderFrameHostImpl* render_frame_host,
215 const GURL& url,
216 int error_code,
217 const base::string16& error_description,
218 bool was_ignored_by_handler) {
219 if (delegate_) {
220 delegate_->DidFailLoadWithError(
221 render_frame_host, url, error_code,
222 error_description, was_ignored_by_handler);
226 bool NavigatorImpl::NavigateToEntry(
227 FrameTreeNode* frame_tree_node,
228 const FrameNavigationEntry& frame_entry,
229 const NavigationEntryImpl& entry,
230 NavigationController::ReloadType reload_type,
231 bool is_same_document_history_load) {
232 TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
234 GURL dest_url = frame_entry.url();
235 Referrer dest_referrer = frame_entry.referrer();
236 if (reload_type ==
237 NavigationController::ReloadType::RELOAD_ORIGINAL_REQUEST_URL &&
238 entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
239 // We may have been redirected when navigating to the current URL.
240 // Use the URL the user originally intended to visit, if it's valid and if a
241 // POST wasn't involved; the latter case avoids issues with sending data to
242 // the wrong page.
243 dest_url = entry.GetOriginalRequestURL();
244 dest_referrer = Referrer();
247 // The renderer will reject IPC messages with URLs longer than
248 // this limit, so don't attempt to navigate with a longer URL.
249 if (dest_url.spec().size() > GetMaxURLChars()) {
250 LOG(WARNING) << "Refusing to load URL as it exceeds " << GetMaxURLChars()
251 << " characters.";
252 return false;
255 // This will be used to set the Navigation Timing API navigationStart
256 // parameter for browser navigations in new tabs (intents, tabs opened through
257 // "Open link in new tab"). We need to keep it above RFHM::Navigate() call to
258 // capture the time needed for the RenderFrameHost initialization.
259 base::TimeTicks navigation_start = base::TimeTicks::Now();
261 RenderFrameHostManager* manager = frame_tree_node->render_manager();
263 // PlzNavigate: the RenderFrameHosts are no longer asked to navigate.
264 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
265 switches::kEnableBrowserSideNavigation)) {
266 navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
267 entry.restore_type()));
268 RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry,
269 entry, reload_type, is_same_document_history_load,
270 navigation_start);
272 // Notify observers about navigation.
273 if (delegate_)
274 delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);
276 return true;
279 RenderFrameHostImpl* dest_render_frame_host =
280 manager->Navigate(dest_url, frame_entry, entry);
281 if (!dest_render_frame_host)
282 return false; // Unable to create the desired RenderFrameHost.
284 // Make sure no code called via RFHM::Navigate clears the pending entry.
285 CHECK_EQ(controller_->GetPendingEntry(), &entry);
287 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
288 // Double check that here.
289 CheckWebUIRendererDoesNotDisplayNormalURL(dest_render_frame_host, dest_url);
291 // Notify observers that we will navigate in this RenderFrame.
292 if (delegate_) {
293 delegate_->AboutToNavigateRenderFrame(frame_tree_node->current_frame_host(),
294 dest_render_frame_host);
297 // Navigate in the desired RenderFrameHost.
298 // We can skip this step in the rare case that this is a transfer navigation
299 // which began in the chosen RenderFrameHost, since the request has already
300 // been issued. In that case, simply resume the response.
301 bool is_transfer_to_same =
302 entry.transferred_global_request_id().child_id != -1 &&
303 entry.transferred_global_request_id().child_id ==
304 dest_render_frame_host->GetProcess()->GetID();
305 if (!is_transfer_to_same) {
306 navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
307 entry.restore_type()));
308 // Create the navigation parameters.
309 FrameMsg_Navigate_Type::Value navigation_type =
310 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
311 dest_render_frame_host->Navigate(
312 entry.ConstructCommonNavigationParams(dest_url, dest_referrer,
313 frame_entry, navigation_type),
314 entry.ConstructStartNavigationParams(),
315 entry.ConstructRequestNavigationParams(
316 frame_entry, navigation_start, is_same_document_history_load,
317 frame_tree_node->has_committed_real_load(),
318 controller_->GetPendingEntryIndex() == -1,
319 controller_->GetIndexOfEntry(&entry),
320 controller_->GetLastCommittedEntryIndex(),
321 controller_->GetEntryCount()));
322 } else {
323 // No need to navigate again. Just resume the deferred request.
324 dest_render_frame_host->GetProcess()->ResumeDeferredNavigation(
325 entry.transferred_global_request_id());
328 // Make sure no code called via RFH::Navigate clears the pending entry.
329 CHECK_EQ(controller_->GetPendingEntry(), &entry);
331 if (controller_->GetPendingEntryIndex() == -1 &&
332 dest_url.SchemeIs(url::kJavaScriptScheme)) {
333 // If the pending entry index is -1 (which means a new navigation rather
334 // than a history one), and the user typed in a javascript: URL, don't add
335 // it to the session history.
337 // This is a hack. What we really want is to avoid adding to the history any
338 // URL that doesn't generate content, and what would be great would be if we
339 // had a message from the renderer telling us that a new page was not
340 // created. The same message could be used for mailto: URLs and the like.
341 return false;
344 // Notify observers about navigation.
345 if (delegate_) {
346 delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);
349 return true;
352 bool NavigatorImpl::NavigateToPendingEntry(
353 FrameTreeNode* frame_tree_node,
354 const FrameNavigationEntry& frame_entry,
355 NavigationController::ReloadType reload_type,
356 bool is_same_document_history_load) {
357 return NavigateToEntry(frame_tree_node, frame_entry,
358 *controller_->GetPendingEntry(), reload_type,
359 is_same_document_history_load);
362 void NavigatorImpl::DidNavigate(
363 RenderFrameHostImpl* render_frame_host,
364 const FrameHostMsg_DidCommitProvisionalLoad_Params& input_params) {
365 FrameHostMsg_DidCommitProvisionalLoad_Params params(input_params);
366 FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
367 bool oopifs_possible = SiteIsolationPolicy::AreCrossProcessFramesPossible();
369 if (ui::PageTransitionIsMainFrame(params.transition)) {
370 if (delegate_) {
371 // When overscroll navigation gesture is enabled, a screenshot of the page
372 // in its current state is taken so that it can be used during the
373 // nav-gesture. It is necessary to take the screenshot here, before
374 // calling RenderFrameHostManager::DidNavigateMainFrame, because that can
375 // change WebContents::GetRenderViewHost to return the new host, instead
376 // of the one that may have just been swapped out.
377 if (delegate_->CanOverscrollContent()) {
378 // Don't take screenshots if we are staying on the same page. We want
379 // in-page navigations to be super fast, and taking a screenshot
380 // currently blocks GPU for a longer time than we are willing to
381 // tolerate in this use case.
382 if (!params.was_within_same_page)
383 controller_->TakeScreenshot();
386 // Run tasks that must execute just before the commit.
387 bool is_navigation_within_page = controller_->IsURLInPageNavigation(
388 params.url, params.was_within_same_page, render_frame_host);
389 delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
392 if (!oopifs_possible)
393 frame_tree->root()->render_manager()->DidNavigateFrame(
394 render_frame_host, params.gesture == NavigationGestureUser);
397 // Save the origin of the new page. Do this before calling
398 // DidNavigateFrame(), because the origin needs to be included in the SwapOut
399 // message, which is sent inside DidNavigateFrame(). SwapOut needs the
400 // origin because it creates a RenderFrameProxy that needs this to initialize
401 // its security context. This origin will also be sent to RenderFrameProxies
402 // created via ViewMsg_New and FrameMsg_NewFrameProxy.
403 render_frame_host->frame_tree_node()->SetCurrentOrigin(params.origin);
405 // When using --site-per-process, we notify the RFHM for all navigations,
406 // not just main frame navigations.
407 if (oopifs_possible) {
408 FrameTreeNode* frame = render_frame_host->frame_tree_node();
409 frame->render_manager()->DidNavigateFrame(
410 render_frame_host, params.gesture == NavigationGestureUser);
413 // Update the site of the SiteInstance if it doesn't have one yet, unless
414 // assigning a site is not necessary for this URL. In that case, the
415 // SiteInstance can still be considered unused until a navigation to a real
416 // page.
417 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
418 if (!site_instance->HasSite() &&
419 ShouldAssignSiteForURL(params.url)) {
420 site_instance->SetSite(params.url);
423 // Need to update MIME type here because it's referred to in
424 // UpdateNavigationCommands() called by RendererDidNavigate() to
425 // determine whether or not to enable the encoding menu.
426 // It's updated only for the main frame. For a subframe,
427 // RenderView::UpdateURL does not set params.contents_mime_type.
428 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
429 // TODO(jungshik): Add a test for the encoding menu to avoid
430 // regressing it again.
431 // TODO(nasko): Verify the correctness of the above comment, since some of the
432 // code doesn't exist anymore. Also, move this code in the
433 // PageTransitionIsMainFrame code block above.
434 if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
435 delegate_->SetMainFrameMimeType(params.contents_mime_type);
437 LoadCommittedDetails details;
438 bool did_navigate = controller_->RendererDidNavigate(render_frame_host,
439 params, &details);
441 // Keep track of each frame's URL in its FrameTreeNode.
442 render_frame_host->frame_tree_node()->SetCurrentURL(params.url);
444 // Send notification about committed provisional loads. This notification is
445 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
446 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
447 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
448 DCHECK_EQ(!render_frame_host->GetParent(),
449 did_navigate ? details.is_main_frame : false);
450 ui::PageTransition transition_type = params.transition;
451 // Whether or not a page transition was triggered by going backward or
452 // forward in the history is only stored in the navigation controller's
453 // entry list.
454 if (did_navigate &&
455 (controller_->GetLastCommittedEntry()->GetTransitionType() &
456 ui::PAGE_TRANSITION_FORWARD_BACK)) {
457 transition_type = ui::PageTransitionFromInt(
458 params.transition | ui::PAGE_TRANSITION_FORWARD_BACK);
461 delegate_->DidCommitProvisionalLoad(render_frame_host,
462 params.url,
463 transition_type);
466 if (!did_navigate)
467 return; // No navigation happened.
469 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
470 // for the appropriate notification (best) or you can add it to
471 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
472 // necessary, please).
474 // TODO(carlosk): Move this out when PlzNavigate implementation properly calls
475 // the observer methods.
476 RecordNavigationMetrics(details, params, site_instance);
478 // Run post-commit tasks.
479 if (delegate_) {
480 if (details.is_main_frame) {
481 delegate_->DidNavigateMainFramePostCommit(render_frame_host,
482 details, params);
485 delegate_->DidNavigateAnyFramePostCommit(
486 render_frame_host, details, params);
490 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
491 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
492 // still be used for a normal web site.
493 if (url == GURL(url::kAboutBlankURL))
494 return false;
496 // The embedder will then have the opportunity to determine if the URL
497 // should "use up" the SiteInstance.
498 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
501 void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
502 const GURL& url,
503 SiteInstance* source_site_instance,
504 const Referrer& referrer,
505 WindowOpenDisposition disposition,
506 bool should_replace_current_entry,
507 bool user_gesture) {
508 SiteInstance* current_site_instance =
509 GetRenderManager(render_frame_host)->current_frame_host()->
510 GetSiteInstance();
511 // If this came from a swapped out RenderFrameHost, we only allow the request
512 // if we are still in the same BrowsingInstance.
513 // TODO(creis): Move this to RenderFrameProxyHost::OpenURL.
514 if (render_frame_host->is_swapped_out() &&
515 !render_frame_host->GetSiteInstance()->IsRelatedSiteInstance(
516 current_site_instance)) {
517 return;
520 // Delegate to RequestTransferURL because this is just the generic
521 // case where |old_request_id| is empty.
522 // TODO(creis): Pass the redirect_chain into this method to support client
523 // redirects. http://crbug.com/311721.
524 std::vector<GURL> redirect_chain;
525 RequestTransferURL(render_frame_host, url, source_site_instance,
526 redirect_chain, referrer, ui::PAGE_TRANSITION_LINK,
527 disposition, GlobalRequestID(),
528 should_replace_current_entry, user_gesture);
531 void NavigatorImpl::RequestTransferURL(
532 RenderFrameHostImpl* render_frame_host,
533 const GURL& url,
534 SiteInstance* source_site_instance,
535 const std::vector<GURL>& redirect_chain,
536 const Referrer& referrer,
537 ui::PageTransition page_transition,
538 WindowOpenDisposition disposition,
539 const GlobalRequestID& transferred_global_request_id,
540 bool should_replace_current_entry,
541 bool user_gesture) {
542 GURL dest_url(url);
543 SiteInstance* current_site_instance =
544 GetRenderManager(render_frame_host)->current_frame_host()->
545 GetSiteInstance();
546 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
547 current_site_instance, url)) {
548 dest_url = GURL(url::kAboutBlankURL);
551 int frame_tree_node_id = -1;
553 // Send the navigation to the current FrameTreeNode if it's destined for a
554 // subframe in the current tab. We'll assume it's for the main frame
555 // (possibly of a new or different WebContents) otherwise.
556 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() &&
557 disposition == CURRENT_TAB && render_frame_host->GetParent()) {
558 frame_tree_node_id =
559 render_frame_host->frame_tree_node()->frame_tree_node_id();
562 OpenURLParams params(
563 dest_url, referrer, frame_tree_node_id, disposition, page_transition,
564 true /* is_renderer_initiated */);
565 params.source_site_instance = source_site_instance;
566 if (redirect_chain.size() > 0)
567 params.redirect_chain = redirect_chain;
568 params.transferred_global_request_id = transferred_global_request_id;
569 params.should_replace_current_entry = should_replace_current_entry;
570 params.user_gesture = user_gesture;
572 if (GetRenderManager(render_frame_host)->web_ui()) {
573 // Web UI pages sometimes want to override the page transition type for
574 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
575 // automatically generated suggestions). We don't override other types
576 // like TYPED because they have different implications (e.g., autocomplete).
577 if (ui::PageTransitionCoreTypeIs(
578 params.transition, ui::PAGE_TRANSITION_LINK))
579 params.transition =
580 GetRenderManager(render_frame_host)->web_ui()->
581 GetLinkTransitionType();
583 // Note also that we hide the referrer for Web UI pages. We don't really
584 // want web sites to see a referrer of "chrome://blah" (and some
585 // chrome: URLs might have search terms or other stuff we don't want to
586 // send to the site), so we send no referrer.
587 params.referrer = Referrer();
589 // Navigations in Web UI pages count as browser-initiated navigations.
590 params.is_renderer_initiated = false;
593 if (delegate_)
594 delegate_->RequestOpenURL(render_frame_host, params);
597 // PlzNavigate
598 void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
599 bool proceed) {
600 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
601 switches::kEnableBrowserSideNavigation));
602 DCHECK(frame_tree_node);
604 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
606 // The NavigationRequest may have been canceled while the renderer was
607 // executing the BeforeUnload event.
608 if (!navigation_request)
609 return;
611 DCHECK_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
612 navigation_request->state());
614 // If the navigation is allowed to proceed, send the request to the IO thread.
615 if (proceed)
616 navigation_request->BeginNavigation();
617 else
618 CancelNavigation(frame_tree_node);
621 // PlzNavigate
622 void NavigatorImpl::OnBeginNavigation(
623 FrameTreeNode* frame_tree_node,
624 const CommonNavigationParams& common_params,
625 const BeginNavigationParams& begin_params,
626 scoped_refptr<ResourceRequestBody> body) {
627 // TODO(clamy): the url sent by the renderer should be validated with
628 // FilterURL.
629 // This is a renderer-initiated navigation.
630 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
631 switches::kEnableBrowserSideNavigation));
632 DCHECK(frame_tree_node);
634 NavigationRequest* ongoing_navigation_request =
635 frame_tree_node->navigation_request();
637 // The renderer-initiated navigation request is ignored iff a) there is an
638 // ongoing request b) which is browser or user-initiated and c) the renderer
639 // request is not user-initiated.
640 if (ongoing_navigation_request &&
641 (ongoing_navigation_request->browser_initiated() ||
642 ongoing_navigation_request->begin_params().has_user_gesture) &&
643 !begin_params.has_user_gesture) {
644 return;
647 // In all other cases the current navigation, if any, is canceled and a new
648 // NavigationRequest is created for the node.
649 frame_tree_node->CreatedNavigationRequest(
650 NavigationRequest::CreateRendererInitiated(
651 frame_tree_node, common_params, begin_params, body,
652 controller_->GetLastCommittedEntryIndex(),
653 controller_->GetEntryCount()));
654 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
656 if (frame_tree_node->IsMainFrame()) {
657 // Renderer-initiated main-frame navigations that need to swap processes
658 // will go to the browser via a OpenURL call, and then be handled by the
659 // same code path as browser-initiated navigations. For renderer-initiated
660 // main frame navigation that start via a BeginNavigation IPC, the
661 // RenderFrameHost will not be swapped. Therefore it is safe to call
662 // DidStartMainFrameNavigation with the SiteInstance from the current
663 // RenderFrameHost.
664 DidStartMainFrameNavigation(
665 common_params.url,
666 frame_tree_node->current_frame_host()->GetSiteInstance());
667 navigation_data_.reset();
670 navigation_request->BeginNavigation();
673 // PlzNavigate
674 void NavigatorImpl::CommitNavigation(FrameTreeNode* frame_tree_node,
675 ResourceResponse* response,
676 scoped_ptr<StreamHandle> body) {
677 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
678 switches::kEnableBrowserSideNavigation));
680 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
681 DCHECK(navigation_request);
682 DCHECK(response ||
683 !ShouldMakeNetworkRequestForURL(
684 navigation_request->common_params().url));
686 // HTTP 204 (No Content) and HTTP 205 (Reset Content) responses should not
687 // commit; they leave the frame showing the previous page.
688 if (response && response->head.headers.get() &&
689 (response->head.headers->response_code() == 204 ||
690 response->head.headers->response_code() == 205)) {
691 CancelNavigation(frame_tree_node);
692 return;
695 // Select an appropriate renderer to commit the navigation.
696 RenderFrameHostImpl* render_frame_host =
697 frame_tree_node->render_manager()->GetFrameHostForNavigation(
698 *navigation_request);
700 // The renderer can exit view source mode when any error or cancellation
701 // happen. When reusing the same renderer, overwrite to recover the mode.
702 if (navigation_request->is_view_source() &&
703 render_frame_host ==
704 frame_tree_node->render_manager()->current_frame_host()) {
705 DCHECK(!render_frame_host->GetParent());
706 render_frame_host->render_view_host()->Send(
707 new ViewMsg_EnableViewSourceMode(
708 render_frame_host->render_view_host()->GetRoutingID()));
711 CheckWebUIRendererDoesNotDisplayNormalURL(
712 render_frame_host, navigation_request->common_params().url);
714 render_frame_host->CommitNavigation(response, body.Pass(),
715 navigation_request->common_params(),
716 navigation_request->request_params());
720 // PlzNavigate
721 void NavigatorImpl::FailedNavigation(FrameTreeNode* frame_tree_node,
722 bool has_stale_copy_in_cache,
723 int error_code) {
724 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
725 switches::kEnableBrowserSideNavigation));
727 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
728 DCHECK(navigation_request);
730 // If the request was canceled by the user do not show an error page.
731 if (error_code == net::ERR_ABORTED) {
732 frame_tree_node->ResetNavigationRequest(false);
733 return;
736 // Select an appropriate renderer to show the error page.
737 RenderFrameHostImpl* render_frame_host =
738 frame_tree_node->render_manager()->GetFrameHostForNavigation(
739 *navigation_request);
740 CheckWebUIRendererDoesNotDisplayNormalURL(
741 render_frame_host, navigation_request->common_params().url);
743 render_frame_host->FailedNavigation(navigation_request->common_params(),
744 navigation_request->request_params(),
745 has_stale_copy_in_cache, error_code);
748 // PlzNavigate
749 void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) {
750 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
751 switches::kEnableBrowserSideNavigation));
752 frame_tree_node->ResetNavigationRequest(false);
753 if (frame_tree_node->IsMainFrame())
754 navigation_data_.reset();
757 void NavigatorImpl::LogResourceRequestTime(
758 base::TimeTicks timestamp, const GURL& url) {
759 if (navigation_data_ && navigation_data_->url_ == url) {
760 navigation_data_->url_job_start_time_ = timestamp;
761 UMA_HISTOGRAM_TIMES(
762 "Navigation.TimeToURLJobStart",
763 navigation_data_->url_job_start_time_ - navigation_data_->start_time_);
767 void NavigatorImpl::LogBeforeUnloadTime(
768 const base::TimeTicks& renderer_before_unload_start_time,
769 const base::TimeTicks& renderer_before_unload_end_time) {
770 // Only stores the beforeunload delay if we're tracking a browser initiated
771 // navigation and it happened later than the navigation request.
772 if (navigation_data_ &&
773 renderer_before_unload_start_time > navigation_data_->start_time_) {
774 navigation_data_->before_unload_delay_ =
775 renderer_before_unload_end_time - renderer_before_unload_start_time;
779 void NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL(
780 RenderFrameHostImpl* render_frame_host,
781 const GURL& url) {
782 int enabled_bindings =
783 render_frame_host->render_view_host()->GetEnabledBindings();
784 bool is_allowed_in_web_ui_renderer =
785 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
786 controller_->GetBrowserContext(), url);
787 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
788 !is_allowed_in_web_ui_renderer) {
789 // Log the URL to help us diagnose any future failures of this CHECK.
790 GetContentClient()->SetActiveURL(url);
791 CHECK(0);
795 // PlzNavigate
796 void NavigatorImpl::RequestNavigation(
797 FrameTreeNode* frame_tree_node,
798 const GURL& dest_url,
799 const Referrer& dest_referrer,
800 const FrameNavigationEntry& frame_entry,
801 const NavigationEntryImpl& entry,
802 NavigationController::ReloadType reload_type,
803 bool is_same_document_history_load,
804 base::TimeTicks navigation_start) {
805 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
806 switches::kEnableBrowserSideNavigation));
807 DCHECK(frame_tree_node);
809 // This value must be set here because creating a NavigationRequest might
810 // change the renderer live/non-live status and change this result.
811 bool should_dispatch_beforeunload =
812 frame_tree_node->current_frame_host()->ShouldDispatchBeforeUnload();
813 FrameMsg_Navigate_Type::Value navigation_type =
814 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
815 frame_tree_node->CreatedNavigationRequest(
816 NavigationRequest::CreateBrowserInitiated(
817 frame_tree_node, dest_url, dest_referrer, frame_entry, entry,
818 navigation_type, is_same_document_history_load, navigation_start,
819 controller_));
820 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
822 // Have the current renderer execute its beforeunload event if needed. If it
823 // is not needed (when beforeunload dispatch is not needed or this navigation
824 // is synchronous and same-site) then NavigationRequest::BeginNavigation
825 // should be directly called instead.
826 if (should_dispatch_beforeunload &&
827 ShouldMakeNetworkRequestForURL(
828 navigation_request->common_params().url)) {
829 navigation_request->SetWaitingForRendererResponse();
830 frame_tree_node->current_frame_host()->DispatchBeforeUnload(true);
831 } else {
832 navigation_request->BeginNavigation();
836 void NavigatorImpl::RecordNavigationMetrics(
837 const LoadCommittedDetails& details,
838 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
839 SiteInstance* site_instance) {
840 DCHECK(site_instance->HasProcess());
842 if (!details.is_in_page)
843 RecordAction(base::UserMetricsAction("FrameLoad"));
845 if (!details.is_main_frame || !navigation_data_ ||
846 navigation_data_->url_job_start_time_.is_null() ||
847 navigation_data_->url_ != params.original_request_url) {
848 return;
851 base::TimeDelta time_to_commit =
852 base::TimeTicks::Now() - navigation_data_->start_time_;
853 UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit);
855 time_to_commit -= navigation_data_->before_unload_delay_;
856 base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ -
857 navigation_data_->start_time_ -
858 navigation_data_->before_unload_delay_;
859 if (navigation_data_->is_restoring_from_last_session_) {
860 UMA_HISTOGRAM_TIMES(
861 "Navigation.TimeToCommit_SessionRestored_BeforeUnloadDiscounted",
862 time_to_commit);
863 UMA_HISTOGRAM_TIMES(
864 "Navigation.TimeToURLJobStart_SessionRestored_BeforeUnloadDiscounted",
865 time_to_network);
866 navigation_data_.reset();
867 return;
869 bool navigation_created_new_renderer_process =
870 site_instance->GetProcess()->GetInitTimeForNavigationMetrics() >
871 navigation_data_->start_time_;
872 if (navigation_created_new_renderer_process) {
873 UMA_HISTOGRAM_TIMES(
874 "Navigation.TimeToCommit_NewRenderer_BeforeUnloadDiscounted",
875 time_to_commit);
876 UMA_HISTOGRAM_TIMES(
877 "Navigation.TimeToURLJobStart_NewRenderer_BeforeUnloadDiscounted",
878 time_to_network);
879 } else {
880 UMA_HISTOGRAM_TIMES(
881 "Navigation.TimeToCommit_ExistingRenderer_BeforeUnloadDiscounted",
882 time_to_commit);
883 UMA_HISTOGRAM_TIMES(
884 "Navigation.TimeToURLJobStart_ExistingRenderer_BeforeUnloadDiscounted",
885 time_to_network);
887 navigation_data_.reset();
890 void NavigatorImpl::DidStartMainFrameNavigation(
891 const GURL& url,
892 SiteInstanceImpl* site_instance) {
893 // If there is no browser-initiated pending entry for this navigation and it
894 // is not for the error URL, create a pending entry using the current
895 // SiteInstance, and ensure the address bar updates accordingly. We don't
896 // know the referrer or extra headers at this point, but the referrer will
897 // be set properly upon commit.
898 NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
899 bool has_browser_initiated_pending_entry =
900 pending_entry && !pending_entry->is_renderer_initiated();
901 if (!has_browser_initiated_pending_entry) {
902 scoped_ptr<NavigationEntryImpl> entry =
903 NavigationEntryImpl::FromNavigationEntry(
904 controller_->CreateNavigationEntry(
905 url, content::Referrer(), ui::PAGE_TRANSITION_LINK,
906 true /* is_renderer_initiated */, std::string(),
907 controller_->GetBrowserContext()));
908 entry->set_site_instance(site_instance);
909 // TODO(creis): If there's a pending entry already, find a safe way to
910 // update it instead of replacing it and copying over things like this.
911 if (pending_entry) {
912 entry->set_transferred_global_request_id(
913 pending_entry->transferred_global_request_id());
914 entry->set_should_replace_entry(pending_entry->should_replace_entry());
915 entry->SetRedirectChain(pending_entry->GetRedirectChain());
917 controller_->SetPendingEntry(entry.Pass());
918 if (delegate_)
919 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
923 } // namespace content