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