Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / content / browser / frame_host / navigator_impl.cc
blob5e54fdf04c281aa736aa58cb2fcaea1b32fb296a
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 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 use_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
368 switches::kSitePerProcess);
370 if (ui::PageTransitionIsMainFrame(params.transition)) {
371 if (delegate_) {
372 // When overscroll navigation gesture is enabled, a screenshot of the page
373 // in its current state is taken so that it can be used during the
374 // nav-gesture. It is necessary to take the screenshot here, before
375 // calling RenderFrameHostManager::DidNavigateMainFrame, because that can
376 // change WebContents::GetRenderViewHost to return the new host, instead
377 // of the one that may have just been swapped out.
378 if (delegate_->CanOverscrollContent()) {
379 // Don't take screenshots if we are staying on the same page. We want
380 // in-page navigations to be super fast, and taking a screenshot
381 // currently blocks GPU for a longer time than we are willing to
382 // tolerate in this use case.
383 if (!params.was_within_same_page)
384 controller_->TakeScreenshot();
387 // Run tasks that must execute just before the commit.
388 bool is_navigation_within_page = controller_->IsURLInPageNavigation(
389 params.url, params.was_within_same_page, render_frame_host);
390 delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
393 if (!use_site_per_process)
394 frame_tree->root()->render_manager()->DidNavigateFrame(
395 render_frame_host, params.gesture == NavigationGestureUser);
398 // Save the origin of the new page. Do this before calling
399 // DidNavigateFrame(), because the origin needs to be included in the SwapOut
400 // message, which is sent inside DidNavigateFrame(). SwapOut needs the
401 // origin because it creates a RenderFrameProxy that needs this to initialize
402 // its security context. This origin will also be sent to RenderFrameProxies
403 // created via ViewMsg_New and FrameMsg_NewFrameProxy.
404 render_frame_host->frame_tree_node()->SetCurrentOrigin(params.origin);
406 // When using --site-per-process, we notify the RFHM for all navigations,
407 // not just main frame navigations.
408 if (use_site_per_process) {
409 FrameTreeNode* frame = render_frame_host->frame_tree_node();
410 frame->render_manager()->DidNavigateFrame(
411 render_frame_host, params.gesture == NavigationGestureUser);
414 // Update the site of the SiteInstance if it doesn't have one yet, unless
415 // assigning a site is not necessary for this URL. In that case, the
416 // SiteInstance can still be considered unused until a navigation to a real
417 // page.
418 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
419 if (!site_instance->HasSite() &&
420 ShouldAssignSiteForURL(params.url)) {
421 site_instance->SetSite(params.url);
424 // Need to update MIME type here because it's referred to in
425 // UpdateNavigationCommands() called by RendererDidNavigate() to
426 // determine whether or not to enable the encoding menu.
427 // It's updated only for the main frame. For a subframe,
428 // RenderView::UpdateURL does not set params.contents_mime_type.
429 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
430 // TODO(jungshik): Add a test for the encoding menu to avoid
431 // regressing it again.
432 // TODO(nasko): Verify the correctness of the above comment, since some of the
433 // code doesn't exist anymore. Also, move this code in the
434 // PageTransitionIsMainFrame code block above.
435 if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
436 delegate_->SetMainFrameMimeType(params.contents_mime_type);
438 LoadCommittedDetails details;
439 bool did_navigate = controller_->RendererDidNavigate(render_frame_host,
440 params, &details);
442 // Keep track of each frame's URL in its FrameTreeNode.
443 render_frame_host->frame_tree_node()->SetCurrentURL(params.url);
445 // Send notification about committed provisional loads. This notification is
446 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
447 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
448 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
449 DCHECK_EQ(!render_frame_host->GetParent(),
450 did_navigate ? details.is_main_frame : false);
451 ui::PageTransition transition_type = params.transition;
452 // Whether or not a page transition was triggered by going backward or
453 // forward in the history is only stored in the navigation controller's
454 // entry list.
455 if (did_navigate &&
456 (controller_->GetLastCommittedEntry()->GetTransitionType() &
457 ui::PAGE_TRANSITION_FORWARD_BACK)) {
458 transition_type = ui::PageTransitionFromInt(
459 params.transition | ui::PAGE_TRANSITION_FORWARD_BACK);
462 delegate_->DidCommitProvisionalLoad(render_frame_host,
463 params.url,
464 transition_type);
467 if (!did_navigate)
468 return; // No navigation happened.
470 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
471 // for the appropriate notification (best) or you can add it to
472 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
473 // necessary, please).
475 // TODO(carlosk): Move this out when PlzNavigate implementation properly calls
476 // the observer methods.
477 RecordNavigationMetrics(details, params, site_instance);
479 // Run post-commit tasks.
480 if (delegate_) {
481 if (details.is_main_frame) {
482 delegate_->DidNavigateMainFramePostCommit(render_frame_host,
483 details, params);
486 delegate_->DidNavigateAnyFramePostCommit(
487 render_frame_host, details, params);
491 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
492 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
493 // still be used for a normal web site.
494 if (url == GURL(url::kAboutBlankURL))
495 return false;
497 // The embedder will then have the opportunity to determine if the URL
498 // should "use up" the SiteInstance.
499 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
502 void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
503 const GURL& url,
504 SiteInstance* source_site_instance,
505 const Referrer& referrer,
506 WindowOpenDisposition disposition,
507 bool should_replace_current_entry,
508 bool user_gesture) {
509 SiteInstance* current_site_instance =
510 GetRenderManager(render_frame_host)->current_frame_host()->
511 GetSiteInstance();
512 // If this came from a swapped out RenderFrameHost, we only allow the request
513 // if we are still in the same BrowsingInstance.
514 // TODO(creis): Move this to RenderFrameProxyHost::OpenURL.
515 if (render_frame_host->is_swapped_out() &&
516 !render_frame_host->GetSiteInstance()->IsRelatedSiteInstance(
517 current_site_instance)) {
518 return;
521 // Delegate to RequestTransferURL because this is just the generic
522 // case where |old_request_id| is empty.
523 // TODO(creis): Pass the redirect_chain into this method to support client
524 // redirects. http://crbug.com/311721.
525 std::vector<GURL> redirect_chain;
526 RequestTransferURL(render_frame_host, url, source_site_instance,
527 redirect_chain, referrer, ui::PAGE_TRANSITION_LINK,
528 disposition, GlobalRequestID(),
529 should_replace_current_entry, user_gesture);
532 void NavigatorImpl::RequestTransferURL(
533 RenderFrameHostImpl* render_frame_host,
534 const GURL& url,
535 SiteInstance* source_site_instance,
536 const std::vector<GURL>& redirect_chain,
537 const Referrer& referrer,
538 ui::PageTransition page_transition,
539 WindowOpenDisposition disposition,
540 const GlobalRequestID& transferred_global_request_id,
541 bool should_replace_current_entry,
542 bool user_gesture) {
543 GURL dest_url(url);
544 SiteInstance* current_site_instance =
545 GetRenderManager(render_frame_host)->current_frame_host()->
546 GetSiteInstance();
547 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
548 current_site_instance, url)) {
549 dest_url = GURL(url::kAboutBlankURL);
552 int frame_tree_node_id = -1;
554 // Send the navigation to the current FrameTreeNode if it's destined for a
555 // subframe in the current tab. We'll assume it's for the main frame
556 // (possibly of a new or different WebContents) otherwise.
557 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
558 switches::kSitePerProcess) &&
559 disposition == CURRENT_TAB &&
560 render_frame_host->GetParent()) {
561 frame_tree_node_id =
562 render_frame_host->frame_tree_node()->frame_tree_node_id();
565 OpenURLParams params(
566 dest_url, referrer, frame_tree_node_id, disposition, page_transition,
567 true /* is_renderer_initiated */);
568 params.source_site_instance = source_site_instance;
569 if (redirect_chain.size() > 0)
570 params.redirect_chain = redirect_chain;
571 params.transferred_global_request_id = transferred_global_request_id;
572 params.should_replace_current_entry = should_replace_current_entry;
573 params.user_gesture = user_gesture;
575 if (GetRenderManager(render_frame_host)->web_ui()) {
576 // Web UI pages sometimes want to override the page transition type for
577 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
578 // automatically generated suggestions). We don't override other types
579 // like TYPED because they have different implications (e.g., autocomplete).
580 if (ui::PageTransitionCoreTypeIs(
581 params.transition, ui::PAGE_TRANSITION_LINK))
582 params.transition =
583 GetRenderManager(render_frame_host)->web_ui()->
584 GetLinkTransitionType();
586 // Note also that we hide the referrer for Web UI pages. We don't really
587 // want web sites to see a referrer of "chrome://blah" (and some
588 // chrome: URLs might have search terms or other stuff we don't want to
589 // send to the site), so we send no referrer.
590 params.referrer = Referrer();
592 // Navigations in Web UI pages count as browser-initiated navigations.
593 params.is_renderer_initiated = false;
596 if (delegate_)
597 delegate_->RequestOpenURL(render_frame_host, params);
600 // PlzNavigate
601 void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
602 bool proceed) {
603 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
604 switches::kEnableBrowserSideNavigation));
605 DCHECK(frame_tree_node);
607 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
609 // The NavigationRequest may have been canceled while the renderer was
610 // executing the BeforeUnload event.
611 if (!navigation_request)
612 return;
614 DCHECK_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
615 navigation_request->state());
617 // If the navigation is allowed to proceed, send the request to the IO thread.
618 if (proceed)
619 navigation_request->BeginNavigation();
620 else
621 CancelNavigation(frame_tree_node);
624 // PlzNavigate
625 void NavigatorImpl::OnBeginNavigation(
626 FrameTreeNode* frame_tree_node,
627 const CommonNavigationParams& common_params,
628 const BeginNavigationParams& begin_params,
629 scoped_refptr<ResourceRequestBody> body) {
630 // TODO(clamy): the url sent by the renderer should be validated with
631 // FilterURL.
632 // This is a renderer-initiated navigation.
633 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
634 switches::kEnableBrowserSideNavigation));
635 DCHECK(frame_tree_node);
637 NavigationRequest* ongoing_navigation_request =
638 frame_tree_node->navigation_request();
640 // The renderer-initiated navigation request is ignored iff a) there is an
641 // ongoing request b) which is browser or user-initiated and c) the renderer
642 // request is not user-initiated.
643 if (ongoing_navigation_request &&
644 (ongoing_navigation_request->browser_initiated() ||
645 ongoing_navigation_request->begin_params().has_user_gesture) &&
646 !begin_params.has_user_gesture) {
647 return;
650 // In all other cases the current navigation, if any, is canceled and a new
651 // NavigationRequest is created for the node.
652 frame_tree_node->CreatedNavigationRequest(
653 NavigationRequest::CreateRendererInitiated(
654 frame_tree_node, common_params, begin_params, body,
655 controller_->GetLastCommittedEntryIndex(),
656 controller_->GetEntryCount()));
657 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
659 if (frame_tree_node->IsMainFrame()) {
660 // Renderer-initiated main-frame navigations that need to swap processes
661 // will go to the browser via a OpenURL call, and then be handled by the
662 // same code path as browser-initiated navigations. For renderer-initiated
663 // main frame navigation that start via a BeginNavigation IPC, the
664 // RenderFrameHost will not be swapped. Therefore it is safe to call
665 // DidStartMainFrameNavigation with the SiteInstance from the current
666 // RenderFrameHost.
667 DidStartMainFrameNavigation(
668 common_params.url,
669 frame_tree_node->current_frame_host()->GetSiteInstance());
670 navigation_data_.reset();
673 navigation_request->BeginNavigation();
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 !ShouldMakeNetworkRequestForURL(
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());
723 // PlzNavigate
724 void NavigatorImpl::FailedNavigation(FrameTreeNode* frame_tree_node,
725 bool has_stale_copy_in_cache,
726 int error_code) {
727 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
728 switches::kEnableBrowserSideNavigation));
730 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
731 DCHECK(navigation_request);
733 // If the request was canceled by the user do not show an error page.
734 if (error_code == net::ERR_ABORTED) {
735 frame_tree_node->ResetNavigationRequest(false);
736 return;
739 // Select an appropriate renderer to show the error page.
740 RenderFrameHostImpl* render_frame_host =
741 frame_tree_node->render_manager()->GetFrameHostForNavigation(
742 *navigation_request);
743 CheckWebUIRendererDoesNotDisplayNormalURL(
744 render_frame_host, navigation_request->common_params().url);
746 render_frame_host->FailedNavigation(navigation_request->common_params(),
747 navigation_request->request_params(),
748 has_stale_copy_in_cache, error_code);
751 // PlzNavigate
752 void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) {
753 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
754 switches::kEnableBrowserSideNavigation));
755 frame_tree_node->ResetNavigationRequest(false);
756 if (frame_tree_node->IsMainFrame())
757 navigation_data_.reset();
760 void NavigatorImpl::LogResourceRequestTime(
761 base::TimeTicks timestamp, const GURL& url) {
762 if (navigation_data_ && navigation_data_->url_ == url) {
763 navigation_data_->url_job_start_time_ = timestamp;
764 UMA_HISTOGRAM_TIMES(
765 "Navigation.TimeToURLJobStart",
766 navigation_data_->url_job_start_time_ - navigation_data_->start_time_);
770 void NavigatorImpl::LogBeforeUnloadTime(
771 const base::TimeTicks& renderer_before_unload_start_time,
772 const base::TimeTicks& renderer_before_unload_end_time) {
773 // Only stores the beforeunload delay if we're tracking a browser initiated
774 // navigation and it happened later than the navigation request.
775 if (navigation_data_ &&
776 renderer_before_unload_start_time > navigation_data_->start_time_) {
777 navigation_data_->before_unload_delay_ =
778 renderer_before_unload_end_time - renderer_before_unload_start_time;
782 void NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL(
783 RenderFrameHostImpl* render_frame_host,
784 const GURL& url) {
785 int enabled_bindings =
786 render_frame_host->render_view_host()->GetEnabledBindings();
787 bool is_allowed_in_web_ui_renderer =
788 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
789 controller_->GetBrowserContext(), url);
790 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
791 !is_allowed_in_web_ui_renderer) {
792 // Log the URL to help us diagnose any future failures of this CHECK.
793 GetContentClient()->SetActiveURL(url);
794 CHECK(0);
798 // PlzNavigate
799 void NavigatorImpl::RequestNavigation(
800 FrameTreeNode* frame_tree_node,
801 const GURL& dest_url,
802 const Referrer& dest_referrer,
803 const FrameNavigationEntry& frame_entry,
804 const NavigationEntryImpl& entry,
805 NavigationController::ReloadType reload_type,
806 bool is_same_document_history_load,
807 base::TimeTicks navigation_start) {
808 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
809 switches::kEnableBrowserSideNavigation));
810 DCHECK(frame_tree_node);
812 // This value must be set here because creating a NavigationRequest might
813 // change the renderer live/non-live status and change this result.
814 bool should_dispatch_beforeunload =
815 frame_tree_node->current_frame_host()->ShouldDispatchBeforeUnload();
816 FrameMsg_Navigate_Type::Value navigation_type =
817 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
818 frame_tree_node->CreatedNavigationRequest(
819 NavigationRequest::CreateBrowserInitiated(
820 frame_tree_node, dest_url, dest_referrer, frame_entry, entry,
821 navigation_type, is_same_document_history_load, navigation_start,
822 controller_));
823 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
825 // Have the current renderer execute its beforeunload event if needed. If it
826 // is not needed (when beforeunload dispatch is not needed or this navigation
827 // is synchronous and same-site) then NavigationRequest::BeginNavigation
828 // should be directly called instead.
829 if (should_dispatch_beforeunload &&
830 ShouldMakeNetworkRequestForURL(
831 navigation_request->common_params().url)) {
832 navigation_request->SetWaitingForRendererResponse();
833 frame_tree_node->current_frame_host()->DispatchBeforeUnload(true);
834 } else {
835 navigation_request->BeginNavigation();
839 void NavigatorImpl::RecordNavigationMetrics(
840 const LoadCommittedDetails& details,
841 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
842 SiteInstance* site_instance) {
843 DCHECK(site_instance->HasProcess());
845 if (!details.is_in_page)
846 RecordAction(base::UserMetricsAction("FrameLoad"));
848 if (!details.is_main_frame || !navigation_data_ ||
849 navigation_data_->url_job_start_time_.is_null() ||
850 navigation_data_->url_ != params.original_request_url) {
851 return;
854 base::TimeDelta time_to_commit =
855 base::TimeTicks::Now() - navigation_data_->start_time_;
856 UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit);
858 time_to_commit -= navigation_data_->before_unload_delay_;
859 base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ -
860 navigation_data_->start_time_ -
861 navigation_data_->before_unload_delay_;
862 if (navigation_data_->is_restoring_from_last_session_) {
863 UMA_HISTOGRAM_TIMES(
864 "Navigation.TimeToCommit_SessionRestored_BeforeUnloadDiscounted",
865 time_to_commit);
866 UMA_HISTOGRAM_TIMES(
867 "Navigation.TimeToURLJobStart_SessionRestored_BeforeUnloadDiscounted",
868 time_to_network);
869 navigation_data_.reset();
870 return;
872 bool navigation_created_new_renderer_process =
873 site_instance->GetProcess()->GetInitTimeForNavigationMetrics() >
874 navigation_data_->start_time_;
875 if (navigation_created_new_renderer_process) {
876 UMA_HISTOGRAM_TIMES(
877 "Navigation.TimeToCommit_NewRenderer_BeforeUnloadDiscounted",
878 time_to_commit);
879 UMA_HISTOGRAM_TIMES(
880 "Navigation.TimeToURLJobStart_NewRenderer_BeforeUnloadDiscounted",
881 time_to_network);
882 } else {
883 UMA_HISTOGRAM_TIMES(
884 "Navigation.TimeToCommit_ExistingRenderer_BeforeUnloadDiscounted",
885 time_to_commit);
886 UMA_HISTOGRAM_TIMES(
887 "Navigation.TimeToURLJobStart_ExistingRenderer_BeforeUnloadDiscounted",
888 time_to_network);
890 navigation_data_.reset();
893 void NavigatorImpl::DidStartMainFrameNavigation(
894 const GURL& url,
895 SiteInstanceImpl* site_instance) {
896 // If there is no browser-initiated pending entry for this navigation and it
897 // is not for the error URL, create a pending entry using the current
898 // SiteInstance, and ensure the address bar updates accordingly. We don't
899 // know the referrer or extra headers at this point, but the referrer will
900 // be set properly upon commit.
901 NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
902 bool has_browser_initiated_pending_entry =
903 pending_entry && !pending_entry->is_renderer_initiated();
904 if (!has_browser_initiated_pending_entry) {
905 scoped_ptr<NavigationEntryImpl> entry =
906 NavigationEntryImpl::FromNavigationEntry(
907 controller_->CreateNavigationEntry(
908 url, content::Referrer(), ui::PAGE_TRANSITION_LINK,
909 true /* is_renderer_initiated */, std::string(),
910 controller_->GetBrowserContext()));
911 entry->set_site_instance(site_instance);
912 // TODO(creis): If there's a pending entry already, find a safe way to
913 // update it instead of replacing it and copying over things like this.
914 if (pending_entry) {
915 entry->set_transferred_global_request_id(
916 pending_entry->transferred_global_request_id());
917 entry->set_should_replace_entry(pending_entry->should_replace_entry());
918 entry->SetRedirectChain(pending_entry->GetRedirectChain());
920 controller_->SetPendingEntry(entry.Pass());
921 if (delegate_)
922 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
926 } // namespace content