Add long running gmail memory benchmark for background tab.
[chromium-blink-merge.git] / content / browser / frame_host / navigator_impl.cc
blobb899825dee79f4a342a84df7548f64b5dbd38ccc
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_handle_impl.h"
15 #include "content/browser/frame_host/navigation_request.h"
16 #include "content/browser/frame_host/navigation_request_info.h"
17 #include "content/browser/frame_host/navigator_delegate.h"
18 #include "content/browser/frame_host/render_frame_host_impl.h"
19 #include "content/browser/renderer_host/render_view_host_impl.h"
20 #include "content/browser/site_instance_impl.h"
21 #include "content/browser/webui/web_ui_controller_factory_registry.h"
22 #include "content/browser/webui/web_ui_impl.h"
23 #include "content/common/frame_messages.h"
24 #include "content/common/navigation_params.h"
25 #include "content/common/site_isolation_policy.h"
26 #include "content/common/view_messages.h"
27 #include "content/public/browser/browser_context.h"
28 #include "content/public/browser/content_browser_client.h"
29 #include "content/public/browser/global_request_id.h"
30 #include "content/public/browser/invalidate_type.h"
31 #include "content/public/browser/navigation_controller.h"
32 #include "content/public/browser/navigation_details.h"
33 #include "content/public/browser/page_navigator.h"
34 #include "content/public/browser/render_view_host.h"
35 #include "content/public/browser/stream_handle.h"
36 #include "content/public/browser/user_metrics.h"
37 #include "content/public/common/bindings_policy.h"
38 #include "content/public/common/content_client.h"
39 #include "content/public/common/content_switches.h"
40 #include "content/public/common/resource_response.h"
41 #include "content/public/common/url_constants.h"
42 #include "content/public/common/url_utils.h"
43 #include "net/base/net_errors.h"
45 namespace content {
47 namespace {
49 FrameMsg_Navigate_Type::Value GetNavigationType(
50 BrowserContext* browser_context, const NavigationEntryImpl& entry,
51 NavigationController::ReloadType reload_type) {
52 switch (reload_type) {
53 case NavigationControllerImpl::RELOAD:
54 return FrameMsg_Navigate_Type::RELOAD;
55 case NavigationControllerImpl::RELOAD_IGNORING_CACHE:
56 return FrameMsg_Navigate_Type::RELOAD_IGNORING_CACHE;
57 case NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL:
58 return FrameMsg_Navigate_Type::RELOAD_ORIGINAL_REQUEST_URL;
59 case NavigationControllerImpl::NO_RELOAD:
60 break; // Fall through to rest of function.
63 // |RenderViewImpl::PopulateStateFromPendingNavigationParams| differentiates
64 // between |RESTORE_WITH_POST| and |RESTORE|.
65 if (entry.restore_type() ==
66 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY) {
67 if (entry.GetHasPostData())
68 return FrameMsg_Navigate_Type::RESTORE_WITH_POST;
69 return FrameMsg_Navigate_Type::RESTORE;
72 return FrameMsg_Navigate_Type::NORMAL;
75 RenderFrameHostManager* GetRenderManager(RenderFrameHostImpl* rfh) {
76 if (SiteIsolationPolicy::AreCrossProcessFramesPossible())
77 return rfh->frame_tree_node()->render_manager();
79 return rfh->frame_tree_node()->frame_tree()->root()->render_manager();
82 } // namespace
84 struct NavigatorImpl::NavigationMetricsData {
85 NavigationMetricsData(base::TimeTicks start_time,
86 GURL url,
87 NavigationEntryImpl::RestoreType restore_type)
88 : start_time_(start_time), url_(url) {
89 is_restoring_from_last_session_ =
90 (restore_type ==
91 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY ||
92 restore_type == NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED);
95 base::TimeTicks start_time_;
96 GURL url_;
97 bool is_restoring_from_last_session_;
98 base::TimeTicks url_job_start_time_;
99 base::TimeDelta before_unload_delay_;
102 NavigatorImpl::NavigatorImpl(
103 NavigationControllerImpl* navigation_controller,
104 NavigatorDelegate* delegate)
105 : controller_(navigation_controller),
106 delegate_(delegate) {
109 NavigatorImpl::~NavigatorImpl() {}
111 NavigatorDelegate* NavigatorImpl::GetDelegate() {
112 return delegate_;
115 NavigationController* NavigatorImpl::GetController() {
116 return controller_;
119 void NavigatorImpl::DidStartProvisionalLoad(
120 RenderFrameHostImpl* render_frame_host,
121 const GURL& url) {
122 bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame();
123 bool is_error_page = (url.spec() == kUnreachableWebDataURL);
124 bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL);
125 GURL validated_url(url);
126 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
127 render_process_host->FilterURL(false, &validated_url);
129 if (is_main_frame && !is_error_page) {
130 DidStartMainFrameNavigation(validated_url,
131 render_frame_host->GetSiteInstance());
134 if (delegate_) {
135 // Notify the observer about the start of the provisional load.
136 delegate_->DidStartProvisionalLoad(render_frame_host, validated_url,
137 is_error_page, is_iframe_srcdoc);
140 if (is_error_page ||
141 base::CommandLine::ForCurrentProcess()->HasSwitch(
142 switches::kEnableBrowserSideNavigation)) {
143 return;
146 if (render_frame_host->navigation_handle()) {
147 if (render_frame_host->navigation_handle()->is_transferring()) {
148 // If the navigation is completing a transfer, this
149 // DidStartProvisionalLoad should not correspond to a new navigation.
150 DCHECK_EQ(url, render_frame_host->navigation_handle()->GetURL());
151 render_frame_host->navigation_handle()->set_is_transferring(false);
152 return;
155 // This ensures that notifications about the end of the previous
156 // navigation are sent before notifications about the start of the
157 // new navigation.
158 render_frame_host->SetNavigationHandle(scoped_ptr<NavigationHandleImpl>());
161 render_frame_host->SetNavigationHandle(
162 NavigationHandleImpl::Create(url, is_main_frame, delegate_));
165 void NavigatorImpl::DidFailProvisionalLoadWithError(
166 RenderFrameHostImpl* render_frame_host,
167 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
168 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
169 << ", error_code: " << params.error_code
170 << ", error_description: " << params.error_description
171 << ", showing_repost_interstitial: " <<
172 params.showing_repost_interstitial
173 << ", frame_id: " << render_frame_host->GetRoutingID();
174 GURL validated_url(params.url);
175 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
176 render_process_host->FilterURL(false, &validated_url);
178 if (net::ERR_ABORTED == params.error_code) {
179 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
180 // This means that the interstitial won't be torn down properly, which is
181 // bad. But if we have an interstitial, go back to another tab type, and
182 // then load the same interstitial again, we could end up getting the first
183 // interstitial's "failed" message (as a result of the cancel) when we're on
184 // the second one. We can't tell this apart, so we think we're tearing down
185 // the current page which will cause a crash later on.
187 // http://code.google.com/p/chromium/issues/detail?id=2855
188 // Because this will not tear down the interstitial properly, if "back" is
189 // back to another tab type, the interstitial will still be somewhat alive
190 // in the previous tab type. If you navigate somewhere that activates the
191 // tab with the interstitial again, you'll see a flash before the new load
192 // commits of the interstitial page.
193 FrameTreeNode* root =
194 render_frame_host->frame_tree_node()->frame_tree()->root();
195 if (root->render_manager()->interstitial_page() != NULL) {
196 LOG(WARNING) << "Discarding message during interstitial.";
197 return;
200 // We used to cancel the pending renderer here for cross-site downloads.
201 // However, it's not safe to do that because the download logic repeatedly
202 // looks for this WebContents based on a render ID. Instead, we just
203 // leave the pending renderer around until the next navigation event
204 // (Navigate, DidNavigate, etc), which will clean it up properly.
206 // TODO(creis): Find a way to cancel any pending RFH here.
209 // We usually clear the pending entry when it fails, so that an arbitrary URL
210 // isn't left visible above a committed page. This must be enforced when
211 // the pending entry isn't visible (e.g., renderer-initiated navigations) to
212 // prevent URL spoofs for in-page navigations that don't go through
213 // DidStartProvisionalLoadForFrame.
215 // However, we do preserve the pending entry in some cases, such as on the
216 // initial navigation of an unmodified blank tab. We also allow the delegate
217 // to say when it's safe to leave aborted URLs in the omnibox, to let the user
218 // edit the URL and try again. This may be useful in cases that the committed
219 // page cannot be attacker-controlled. In these cases, we still allow the
220 // view to clear the pending entry and typed URL if the user requests
221 // (e.g., hitting Escape with focus in the address bar).
223 // Note: don't touch the transient entry, since an interstitial may exist.
224 bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() ||
225 delegate_->ShouldPreserveAbortedURLs();
226 if (controller_->GetPendingEntry() != controller_->GetVisibleEntry() ||
227 !should_preserve_entry) {
228 controller_->DiscardPendingEntry(true);
230 // Also force the UI to refresh.
231 controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
234 if (delegate_)
235 delegate_->DidFailProvisionalLoadWithError(render_frame_host, params);
238 void NavigatorImpl::DidFailLoadWithError(
239 RenderFrameHostImpl* render_frame_host,
240 const GURL& url,
241 int error_code,
242 const base::string16& error_description,
243 bool was_ignored_by_handler) {
244 if (delegate_) {
245 delegate_->DidFailLoadWithError(
246 render_frame_host, url, error_code,
247 error_description, was_ignored_by_handler);
251 bool NavigatorImpl::NavigateToEntry(
252 FrameTreeNode* frame_tree_node,
253 const FrameNavigationEntry& frame_entry,
254 const NavigationEntryImpl& entry,
255 NavigationController::ReloadType reload_type,
256 bool is_same_document_history_load) {
257 TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
259 GURL dest_url = frame_entry.url();
260 Referrer dest_referrer = frame_entry.referrer();
261 if (reload_type ==
262 NavigationController::ReloadType::RELOAD_ORIGINAL_REQUEST_URL &&
263 entry.GetOriginalRequestURL().is_valid() && !entry.GetHasPostData()) {
264 // We may have been redirected when navigating to the current URL.
265 // Use the URL the user originally intended to visit, if it's valid and if a
266 // POST wasn't involved; the latter case avoids issues with sending data to
267 // the wrong page.
268 dest_url = entry.GetOriginalRequestURL();
269 dest_referrer = Referrer();
272 // The renderer will reject IPC messages with URLs longer than
273 // this limit, so don't attempt to navigate with a longer URL.
274 if (dest_url.spec().size() > GetMaxURLChars()) {
275 LOG(WARNING) << "Refusing to load URL as it exceeds " << GetMaxURLChars()
276 << " characters.";
277 return false;
280 // This will be used to set the Navigation Timing API navigationStart
281 // parameter for browser navigations in new tabs (intents, tabs opened through
282 // "Open link in new tab"). We need to keep it above RFHM::Navigate() call to
283 // capture the time needed for the RenderFrameHost initialization.
284 base::TimeTicks navigation_start = base::TimeTicks::Now();
286 RenderFrameHostManager* manager = frame_tree_node->render_manager();
288 // PlzNavigate: the RenderFrameHosts are no longer asked to navigate.
289 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
290 switches::kEnableBrowserSideNavigation)) {
291 navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
292 entry.restore_type()));
293 RequestNavigation(frame_tree_node, dest_url, dest_referrer, frame_entry,
294 entry, reload_type, is_same_document_history_load,
295 navigation_start);
297 // Notify observers about navigation.
298 if (delegate_)
299 delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);
301 return true;
304 RenderFrameHostImpl* dest_render_frame_host =
305 manager->Navigate(dest_url, frame_entry, entry);
306 if (!dest_render_frame_host)
307 return false; // Unable to create the desired RenderFrameHost.
309 // Make sure no code called via RFHM::Navigate clears the pending entry.
310 CHECK_EQ(controller_->GetPendingEntry(), &entry);
312 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
313 // Double check that here.
314 CheckWebUIRendererDoesNotDisplayNormalURL(dest_render_frame_host, dest_url);
316 // Notify observers that we will navigate in this RenderFrame.
317 if (delegate_) {
318 delegate_->AboutToNavigateRenderFrame(frame_tree_node->current_frame_host(),
319 dest_render_frame_host);
322 // Navigate in the desired RenderFrameHost.
323 // We can skip this step in the rare case that this is a transfer navigation
324 // which began in the chosen RenderFrameHost, since the request has already
325 // been issued. In that case, simply resume the response.
326 bool is_transfer_to_same =
327 entry.transferred_global_request_id().child_id != -1 &&
328 entry.transferred_global_request_id().child_id ==
329 dest_render_frame_host->GetProcess()->GetID();
330 if (!is_transfer_to_same) {
331 navigation_data_.reset(new NavigationMetricsData(navigation_start, dest_url,
332 entry.restore_type()));
333 // Create the navigation parameters.
334 FrameMsg_Navigate_Type::Value navigation_type =
335 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
336 dest_render_frame_host->Navigate(
337 entry.ConstructCommonNavigationParams(dest_url, dest_referrer,
338 frame_entry, navigation_type),
339 entry.ConstructStartNavigationParams(),
340 entry.ConstructRequestNavigationParams(
341 frame_entry, navigation_start, is_same_document_history_load,
342 frame_tree_node->has_committed_real_load(),
343 controller_->GetPendingEntryIndex() == -1,
344 controller_->GetIndexOfEntry(&entry),
345 controller_->GetLastCommittedEntryIndex(),
346 controller_->GetEntryCount()));
347 } else {
348 // No need to navigate again. Just resume the deferred request.
349 dest_render_frame_host->GetProcess()->ResumeDeferredNavigation(
350 entry.transferred_global_request_id());
353 // Make sure no code called via RFH::Navigate clears the pending entry.
354 CHECK_EQ(controller_->GetPendingEntry(), &entry);
356 if (controller_->GetPendingEntryIndex() == -1 &&
357 dest_url.SchemeIs(url::kJavaScriptScheme)) {
358 // If the pending entry index is -1 (which means a new navigation rather
359 // than a history one), and the user typed in a javascript: URL, don't add
360 // it to the session history.
362 // This is a hack. What we really want is to avoid adding to the history any
363 // URL that doesn't generate content, and what would be great would be if we
364 // had a message from the renderer telling us that a new page was not
365 // created. The same message could be used for mailto: URLs and the like.
366 return false;
369 // Notify observers about navigation.
370 if (delegate_) {
371 delegate_->DidStartNavigationToPendingEntry(dest_url, reload_type);
374 return true;
377 bool NavigatorImpl::NavigateToPendingEntry(
378 FrameTreeNode* frame_tree_node,
379 const FrameNavigationEntry& frame_entry,
380 NavigationController::ReloadType reload_type,
381 bool is_same_document_history_load) {
382 return NavigateToEntry(frame_tree_node, frame_entry,
383 *controller_->GetPendingEntry(), reload_type,
384 is_same_document_history_load);
387 void NavigatorImpl::DidNavigate(
388 RenderFrameHostImpl* render_frame_host,
389 const FrameHostMsg_DidCommitProvisionalLoad_Params& input_params) {
390 FrameHostMsg_DidCommitProvisionalLoad_Params params(input_params);
391 FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
392 bool oopifs_possible = SiteIsolationPolicy::AreCrossProcessFramesPossible();
394 if (ui::PageTransitionIsMainFrame(params.transition)) {
395 if (delegate_) {
396 // When overscroll navigation gesture is enabled, a screenshot of the page
397 // in its current state is taken so that it can be used during the
398 // nav-gesture. It is necessary to take the screenshot here, before
399 // calling RenderFrameHostManager::DidNavigateMainFrame, because that can
400 // change WebContents::GetRenderViewHost to return the new host, instead
401 // of the one that may have just been swapped out.
402 if (delegate_->CanOverscrollContent()) {
403 // Don't take screenshots if we are staying on the same page. We want
404 // in-page navigations to be super fast, and taking a screenshot
405 // currently blocks GPU for a longer time than we are willing to
406 // tolerate in this use case.
407 if (!params.was_within_same_page)
408 controller_->TakeScreenshot();
411 // Run tasks that must execute just before the commit.
412 bool is_navigation_within_page = controller_->IsURLInPageNavigation(
413 params.url, params.was_within_same_page, render_frame_host);
414 delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
417 if (!oopifs_possible)
418 frame_tree->root()->render_manager()->DidNavigateFrame(
419 render_frame_host, params.gesture == NavigationGestureUser);
422 // Save the origin of the new page. Do this before calling
423 // DidNavigateFrame(), because the origin needs to be included in the SwapOut
424 // message, which is sent inside DidNavigateFrame(). SwapOut needs the
425 // origin because it creates a RenderFrameProxy that needs this to initialize
426 // its security context. This origin will also be sent to RenderFrameProxies
427 // created via ViewMsg_New and FrameMsg_NewFrameProxy.
428 render_frame_host->frame_tree_node()->SetCurrentOrigin(params.origin);
430 // When using --site-per-process, we notify the RFHM for all navigations,
431 // not just main frame navigations.
432 if (oopifs_possible) {
433 FrameTreeNode* frame = render_frame_host->frame_tree_node();
434 frame->render_manager()->DidNavigateFrame(
435 render_frame_host, params.gesture == NavigationGestureUser);
438 // Update the site of the SiteInstance if it doesn't have one yet, unless
439 // assigning a site is not necessary for this URL. In that case, the
440 // SiteInstance can still be considered unused until a navigation to a real
441 // page.
442 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
443 if (!site_instance->HasSite() &&
444 ShouldAssignSiteForURL(params.url)) {
445 site_instance->SetSite(params.url);
448 // Need to update MIME type here because it's referred to in
449 // UpdateNavigationCommands() called by RendererDidNavigate() to
450 // determine whether or not to enable the encoding menu.
451 // It's updated only for the main frame. For a subframe,
452 // RenderView::UpdateURL does not set params.contents_mime_type.
453 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
454 // TODO(jungshik): Add a test for the encoding menu to avoid
455 // regressing it again.
456 // TODO(nasko): Verify the correctness of the above comment, since some of the
457 // code doesn't exist anymore. Also, move this code in the
458 // PageTransitionIsMainFrame code block above.
459 if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
460 delegate_->SetMainFrameMimeType(params.contents_mime_type);
462 LoadCommittedDetails details;
463 bool did_navigate = controller_->RendererDidNavigate(render_frame_host,
464 params, &details);
466 // Keep track of each frame's URL in its FrameTreeNode.
467 render_frame_host->frame_tree_node()->SetCurrentURL(params.url);
469 // Send notification about committed provisional loads. This notification is
470 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
471 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
472 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
473 DCHECK_EQ(!render_frame_host->GetParent(),
474 did_navigate ? details.is_main_frame : false);
475 ui::PageTransition transition_type = params.transition;
476 // Whether or not a page transition was triggered by going backward or
477 // forward in the history is only stored in the navigation controller's
478 // entry list.
479 if (did_navigate &&
480 (controller_->GetLastCommittedEntry()->GetTransitionType() &
481 ui::PAGE_TRANSITION_FORWARD_BACK)) {
482 transition_type = ui::PageTransitionFromInt(
483 params.transition | ui::PAGE_TRANSITION_FORWARD_BACK);
486 delegate_->DidCommitProvisionalLoad(render_frame_host,
487 params.url,
488 transition_type);
489 render_frame_host->navigation_handle()->DidCommitNavigation();
492 if (!did_navigate)
493 return; // No navigation happened.
495 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
496 // for the appropriate notification (best) or you can add it to
497 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
498 // necessary, please).
500 // TODO(carlosk): Move this out when PlzNavigate implementation properly calls
501 // the observer methods.
502 RecordNavigationMetrics(details, params, site_instance);
504 // Run post-commit tasks.
505 if (delegate_) {
506 if (details.is_main_frame) {
507 delegate_->DidNavigateMainFramePostCommit(render_frame_host,
508 details, params);
511 delegate_->DidNavigateAnyFramePostCommit(
512 render_frame_host, details, params);
516 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
517 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
518 // still be used for a normal web site.
519 if (url == GURL(url::kAboutBlankURL))
520 return false;
522 // The embedder will then have the opportunity to determine if the URL
523 // should "use up" the SiteInstance.
524 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
527 void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
528 const GURL& url,
529 SiteInstance* source_site_instance,
530 const Referrer& referrer,
531 WindowOpenDisposition disposition,
532 bool should_replace_current_entry,
533 bool user_gesture) {
534 SiteInstance* current_site_instance =
535 GetRenderManager(render_frame_host)->current_frame_host()->
536 GetSiteInstance();
537 // If this came from a swapped out RenderFrameHost, we only allow the request
538 // if we are still in the same BrowsingInstance.
539 // TODO(creis): Move this to RenderFrameProxyHost::OpenURL.
540 if (render_frame_host->is_swapped_out() &&
541 !render_frame_host->GetSiteInstance()->IsRelatedSiteInstance(
542 current_site_instance)) {
543 return;
546 // Delegate to RequestTransferURL because this is just the generic
547 // case where |old_request_id| is empty.
548 // TODO(creis): Pass the redirect_chain into this method to support client
549 // redirects. http://crbug.com/311721.
550 std::vector<GURL> redirect_chain;
551 RequestTransferURL(render_frame_host, url, source_site_instance,
552 redirect_chain, referrer, ui::PAGE_TRANSITION_LINK,
553 disposition, GlobalRequestID(),
554 should_replace_current_entry, user_gesture);
557 void NavigatorImpl::RequestTransferURL(
558 RenderFrameHostImpl* render_frame_host,
559 const GURL& url,
560 SiteInstance* source_site_instance,
561 const std::vector<GURL>& redirect_chain,
562 const Referrer& referrer,
563 ui::PageTransition page_transition,
564 WindowOpenDisposition disposition,
565 const GlobalRequestID& transferred_global_request_id,
566 bool should_replace_current_entry,
567 bool user_gesture) {
568 GURL dest_url(url);
569 SiteInstance* current_site_instance =
570 GetRenderManager(render_frame_host)->current_frame_host()->
571 GetSiteInstance();
572 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
573 current_site_instance, url)) {
574 dest_url = GURL(url::kAboutBlankURL);
577 int frame_tree_node_id = -1;
579 // Send the navigation to the current FrameTreeNode if it's destined for a
580 // subframe in the current tab. We'll assume it's for the main frame
581 // (possibly of a new or different WebContents) otherwise.
582 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() &&
583 disposition == CURRENT_TAB && render_frame_host->GetParent()) {
584 frame_tree_node_id =
585 render_frame_host->frame_tree_node()->frame_tree_node_id();
588 OpenURLParams params(
589 dest_url, referrer, frame_tree_node_id, disposition, page_transition,
590 true /* is_renderer_initiated */);
591 params.source_site_instance = source_site_instance;
592 if (redirect_chain.size() > 0)
593 params.redirect_chain = redirect_chain;
594 params.transferred_global_request_id = transferred_global_request_id;
595 params.should_replace_current_entry = should_replace_current_entry;
596 params.user_gesture = user_gesture;
598 if (GetRenderManager(render_frame_host)->web_ui()) {
599 // Web UI pages sometimes want to override the page transition type for
600 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
601 // automatically generated suggestions). We don't override other types
602 // like TYPED because they have different implications (e.g., autocomplete).
603 if (ui::PageTransitionCoreTypeIs(
604 params.transition, ui::PAGE_TRANSITION_LINK))
605 params.transition =
606 GetRenderManager(render_frame_host)->web_ui()->
607 GetLinkTransitionType();
609 // Note also that we hide the referrer for Web UI pages. We don't really
610 // want web sites to see a referrer of "chrome://blah" (and some
611 // chrome: URLs might have search terms or other stuff we don't want to
612 // send to the site), so we send no referrer.
613 params.referrer = Referrer();
615 // Navigations in Web UI pages count as browser-initiated navigations.
616 params.is_renderer_initiated = false;
619 if (delegate_)
620 delegate_->RequestOpenURL(render_frame_host, params);
623 // PlzNavigate
624 void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
625 bool proceed) {
626 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
627 switches::kEnableBrowserSideNavigation));
628 DCHECK(frame_tree_node);
630 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
632 // The NavigationRequest may have been canceled while the renderer was
633 // executing the BeforeUnload event.
634 if (!navigation_request)
635 return;
637 DCHECK_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
638 navigation_request->state());
640 // If the navigation is allowed to proceed, send the request to the IO thread.
641 if (proceed)
642 navigation_request->BeginNavigation();
643 else
644 CancelNavigation(frame_tree_node);
647 // PlzNavigate
648 void NavigatorImpl::OnBeginNavigation(
649 FrameTreeNode* frame_tree_node,
650 const CommonNavigationParams& common_params,
651 const BeginNavigationParams& begin_params,
652 scoped_refptr<ResourceRequestBody> body) {
653 // TODO(clamy): the url sent by the renderer should be validated with
654 // FilterURL.
655 // This is a renderer-initiated navigation.
656 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
657 switches::kEnableBrowserSideNavigation));
658 DCHECK(frame_tree_node);
660 NavigationRequest* ongoing_navigation_request =
661 frame_tree_node->navigation_request();
663 // The renderer-initiated navigation request is ignored iff a) there is an
664 // ongoing request b) which is browser or user-initiated and c) the renderer
665 // request is not user-initiated.
666 if (ongoing_navigation_request &&
667 (ongoing_navigation_request->browser_initiated() ||
668 ongoing_navigation_request->begin_params().has_user_gesture) &&
669 !begin_params.has_user_gesture) {
670 return;
673 // In all other cases the current navigation, if any, is canceled and a new
674 // NavigationRequest is created for the node.
675 frame_tree_node->CreatedNavigationRequest(
676 NavigationRequest::CreateRendererInitiated(
677 frame_tree_node, common_params, begin_params, body,
678 controller_->GetLastCommittedEntryIndex(),
679 controller_->GetEntryCount()));
680 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
681 navigation_request->CreateNavigationHandle(delegate_);
683 if (frame_tree_node->IsMainFrame()) {
684 // Renderer-initiated main-frame navigations that need to swap processes
685 // will go to the browser via a OpenURL call, and then be handled by the
686 // same code path as browser-initiated navigations. For renderer-initiated
687 // main frame navigation that start via a BeginNavigation IPC, the
688 // RenderFrameHost will not be swapped. Therefore it is safe to call
689 // DidStartMainFrameNavigation with the SiteInstance from the current
690 // RenderFrameHost.
691 DidStartMainFrameNavigation(
692 common_params.url,
693 frame_tree_node->current_frame_host()->GetSiteInstance());
694 navigation_data_.reset();
697 navigation_request->BeginNavigation();
700 // PlzNavigate
701 void NavigatorImpl::CommitNavigation(FrameTreeNode* frame_tree_node,
702 ResourceResponse* response,
703 scoped_ptr<StreamHandle> body) {
704 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
705 switches::kEnableBrowserSideNavigation));
707 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
708 DCHECK(navigation_request);
709 DCHECK(response ||
710 !ShouldMakeNetworkRequestForURL(
711 navigation_request->common_params().url));
713 // HTTP 204 (No Content) and HTTP 205 (Reset Content) responses should not
714 // commit; they leave the frame showing the previous page.
715 if (response && response->head.headers.get() &&
716 (response->head.headers->response_code() == 204 ||
717 response->head.headers->response_code() == 205)) {
718 CancelNavigation(frame_tree_node);
719 return;
722 // Select an appropriate renderer to commit the navigation.
723 RenderFrameHostImpl* render_frame_host =
724 frame_tree_node->render_manager()->GetFrameHostForNavigation(
725 *navigation_request);
727 // The renderer can exit view source mode when any error or cancellation
728 // happen. When reusing the same renderer, overwrite to recover the mode.
729 if (navigation_request->is_view_source() &&
730 render_frame_host ==
731 frame_tree_node->render_manager()->current_frame_host()) {
732 DCHECK(!render_frame_host->GetParent());
733 render_frame_host->render_view_host()->Send(
734 new ViewMsg_EnableViewSourceMode(
735 render_frame_host->render_view_host()->GetRoutingID()));
738 CheckWebUIRendererDoesNotDisplayNormalURL(
739 render_frame_host, navigation_request->common_params().url);
741 navigation_request->TransferNavigationHandleOwnership(render_frame_host);
742 render_frame_host->CommitNavigation(response, body.Pass(),
743 navigation_request->common_params(),
744 navigation_request->request_params());
748 // PlzNavigate
749 void NavigatorImpl::FailedNavigation(FrameTreeNode* frame_tree_node,
750 bool has_stale_copy_in_cache,
751 int error_code) {
752 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
753 switches::kEnableBrowserSideNavigation));
755 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
756 DCHECK(navigation_request);
758 // If the request was canceled by the user do not show an error page.
759 if (error_code == net::ERR_ABORTED) {
760 frame_tree_node->ResetNavigationRequest(false);
761 return;
764 // Select an appropriate renderer to show the error page.
765 RenderFrameHostImpl* render_frame_host =
766 frame_tree_node->render_manager()->GetFrameHostForNavigation(
767 *navigation_request);
768 CheckWebUIRendererDoesNotDisplayNormalURL(
769 render_frame_host, navigation_request->common_params().url);
771 navigation_request->TransferNavigationHandleOwnership(render_frame_host);
772 render_frame_host->FailedNavigation(navigation_request->common_params(),
773 navigation_request->request_params(),
774 has_stale_copy_in_cache, error_code);
777 // PlzNavigate
778 void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) {
779 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
780 switches::kEnableBrowserSideNavigation));
781 frame_tree_node->ResetNavigationRequest(false);
782 if (frame_tree_node->IsMainFrame())
783 navigation_data_.reset();
786 void NavigatorImpl::LogResourceRequestTime(
787 base::TimeTicks timestamp, const GURL& url) {
788 if (navigation_data_ && navigation_data_->url_ == url) {
789 navigation_data_->url_job_start_time_ = timestamp;
790 UMA_HISTOGRAM_TIMES(
791 "Navigation.TimeToURLJobStart",
792 navigation_data_->url_job_start_time_ - navigation_data_->start_time_);
796 void NavigatorImpl::LogBeforeUnloadTime(
797 const base::TimeTicks& renderer_before_unload_start_time,
798 const base::TimeTicks& renderer_before_unload_end_time) {
799 // Only stores the beforeunload delay if we're tracking a browser initiated
800 // navigation and it happened later than the navigation request.
801 if (navigation_data_ &&
802 renderer_before_unload_start_time > navigation_data_->start_time_) {
803 navigation_data_->before_unload_delay_ =
804 renderer_before_unload_end_time - renderer_before_unload_start_time;
808 void NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL(
809 RenderFrameHostImpl* render_frame_host,
810 const GURL& url) {
811 int enabled_bindings =
812 render_frame_host->render_view_host()->GetEnabledBindings();
813 bool is_allowed_in_web_ui_renderer =
814 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
815 controller_->GetBrowserContext(), url);
816 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
817 !is_allowed_in_web_ui_renderer) {
818 // Log the URL to help us diagnose any future failures of this CHECK.
819 GetContentClient()->SetActiveURL(url);
820 CHECK(0);
824 // PlzNavigate
825 void NavigatorImpl::RequestNavigation(
826 FrameTreeNode* frame_tree_node,
827 const GURL& dest_url,
828 const Referrer& dest_referrer,
829 const FrameNavigationEntry& frame_entry,
830 const NavigationEntryImpl& entry,
831 NavigationController::ReloadType reload_type,
832 bool is_same_document_history_load,
833 base::TimeTicks navigation_start) {
834 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
835 switches::kEnableBrowserSideNavigation));
836 DCHECK(frame_tree_node);
838 // This value must be set here because creating a NavigationRequest might
839 // change the renderer live/non-live status and change this result.
840 bool should_dispatch_beforeunload =
841 frame_tree_node->current_frame_host()->ShouldDispatchBeforeUnload();
842 FrameMsg_Navigate_Type::Value navigation_type =
843 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
844 frame_tree_node->CreatedNavigationRequest(
845 NavigationRequest::CreateBrowserInitiated(
846 frame_tree_node, dest_url, dest_referrer, frame_entry, entry,
847 navigation_type, is_same_document_history_load, navigation_start,
848 controller_));
849 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
850 navigation_request->CreateNavigationHandle(delegate_);
852 // Have the current renderer execute its beforeunload event if needed. If it
853 // is not needed (when beforeunload dispatch is not needed or this navigation
854 // is synchronous and same-site) then NavigationRequest::BeginNavigation
855 // should be directly called instead.
856 if (should_dispatch_beforeunload &&
857 ShouldMakeNetworkRequestForURL(
858 navigation_request->common_params().url)) {
859 navigation_request->SetWaitingForRendererResponse();
860 frame_tree_node->current_frame_host()->DispatchBeforeUnload(true);
861 } else {
862 navigation_request->BeginNavigation();
866 void NavigatorImpl::RecordNavigationMetrics(
867 const LoadCommittedDetails& details,
868 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
869 SiteInstance* site_instance) {
870 DCHECK(site_instance->HasProcess());
872 if (!details.is_in_page)
873 RecordAction(base::UserMetricsAction("FrameLoad"));
875 if (!details.is_main_frame || !navigation_data_ ||
876 navigation_data_->url_job_start_time_.is_null() ||
877 navigation_data_->url_ != params.original_request_url) {
878 return;
881 base::TimeDelta time_to_commit =
882 base::TimeTicks::Now() - navigation_data_->start_time_;
883 UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit);
885 time_to_commit -= navigation_data_->before_unload_delay_;
886 base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ -
887 navigation_data_->start_time_ -
888 navigation_data_->before_unload_delay_;
889 if (navigation_data_->is_restoring_from_last_session_) {
890 UMA_HISTOGRAM_TIMES(
891 "Navigation.TimeToCommit_SessionRestored_BeforeUnloadDiscounted",
892 time_to_commit);
893 UMA_HISTOGRAM_TIMES(
894 "Navigation.TimeToURLJobStart_SessionRestored_BeforeUnloadDiscounted",
895 time_to_network);
896 navigation_data_.reset();
897 return;
899 bool navigation_created_new_renderer_process =
900 site_instance->GetProcess()->GetInitTimeForNavigationMetrics() >
901 navigation_data_->start_time_;
902 if (navigation_created_new_renderer_process) {
903 UMA_HISTOGRAM_TIMES(
904 "Navigation.TimeToCommit_NewRenderer_BeforeUnloadDiscounted",
905 time_to_commit);
906 UMA_HISTOGRAM_TIMES(
907 "Navigation.TimeToURLJobStart_NewRenderer_BeforeUnloadDiscounted",
908 time_to_network);
909 } else {
910 UMA_HISTOGRAM_TIMES(
911 "Navigation.TimeToCommit_ExistingRenderer_BeforeUnloadDiscounted",
912 time_to_commit);
913 UMA_HISTOGRAM_TIMES(
914 "Navigation.TimeToURLJobStart_ExistingRenderer_BeforeUnloadDiscounted",
915 time_to_network);
917 navigation_data_.reset();
920 void NavigatorImpl::DidStartMainFrameNavigation(
921 const GURL& url,
922 SiteInstanceImpl* site_instance) {
923 // If there is no browser-initiated pending entry for this navigation and it
924 // is not for the error URL, create a pending entry using the current
925 // SiteInstance, and ensure the address bar updates accordingly. We don't
926 // know the referrer or extra headers at this point, but the referrer will
927 // be set properly upon commit.
928 NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
929 bool has_browser_initiated_pending_entry =
930 pending_entry && !pending_entry->is_renderer_initiated();
931 if (!has_browser_initiated_pending_entry) {
932 scoped_ptr<NavigationEntryImpl> entry =
933 NavigationEntryImpl::FromNavigationEntry(
934 controller_->CreateNavigationEntry(
935 url, content::Referrer(), ui::PAGE_TRANSITION_LINK,
936 true /* is_renderer_initiated */, std::string(),
937 controller_->GetBrowserContext()));
938 entry->set_site_instance(site_instance);
939 // TODO(creis): If there's a pending entry already, find a safe way to
940 // update it instead of replacing it and copying over things like this.
941 if (pending_entry) {
942 entry->set_transferred_global_request_id(
943 pending_entry->transferred_global_request_id());
944 entry->set_should_replace_entry(pending_entry->should_replace_entry());
945 entry->SetRedirectChain(pending_entry->GetRedirectChain());
947 controller_->SetPendingEntry(entry.Pass());
948 if (delegate_)
949 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
953 } // namespace content