Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / content / browser / frame_host / navigator_impl.cc
blobb2be362dfb61d9b6904098078d4c62f5f2c1cbc6
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& params) {
390 FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
391 bool oopifs_possible = SiteIsolationPolicy::AreCrossProcessFramesPossible();
393 if (ui::PageTransitionIsMainFrame(params.transition)) {
394 if (delegate_) {
395 // When overscroll navigation gesture is enabled, a screenshot of the page
396 // in its current state is taken so that it can be used during the
397 // nav-gesture. It is necessary to take the screenshot here, before
398 // calling RenderFrameHostManager::DidNavigateMainFrame, because that can
399 // change WebContents::GetRenderViewHost to return the new host, instead
400 // of the one that may have just been swapped out.
401 if (delegate_->CanOverscrollContent()) {
402 // Don't take screenshots if we are staying on the same page. We want
403 // in-page navigations to be super fast, and taking a screenshot
404 // currently blocks GPU for a longer time than we are willing to
405 // tolerate in this use case.
406 if (!params.was_within_same_page)
407 controller_->TakeScreenshot();
410 // Run tasks that must execute just before the commit.
411 bool is_navigation_within_page = controller_->IsURLInPageNavigation(
412 params.url, params.was_within_same_page, render_frame_host);
413 delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
416 if (!oopifs_possible)
417 frame_tree->root()->render_manager()->DidNavigateFrame(
418 render_frame_host, params.gesture == NavigationGestureUser);
421 // Save the origin of the new page. Do this before calling
422 // DidNavigateFrame(), because the origin needs to be included in the SwapOut
423 // message, which is sent inside DidNavigateFrame(). SwapOut needs the
424 // origin because it creates a RenderFrameProxy that needs this to initialize
425 // its security context. This origin will also be sent to RenderFrameProxies
426 // created via ViewMsg_New and FrameMsg_NewFrameProxy.
427 render_frame_host->frame_tree_node()->SetCurrentOrigin(params.origin);
429 // When using --site-per-process, we notify the RFHM for all navigations,
430 // not just main frame navigations.
431 if (oopifs_possible) {
432 FrameTreeNode* frame = render_frame_host->frame_tree_node();
433 frame->render_manager()->DidNavigateFrame(
434 render_frame_host, params.gesture == NavigationGestureUser);
437 // Update the site of the SiteInstance if it doesn't have one yet, unless
438 // assigning a site is not necessary for this URL. In that case, the
439 // SiteInstance can still be considered unused until a navigation to a real
440 // page.
441 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
442 if (!site_instance->HasSite() &&
443 ShouldAssignSiteForURL(params.url)) {
444 site_instance->SetSite(params.url);
447 // Need to update MIME type here because it's referred to in
448 // UpdateNavigationCommands() called by RendererDidNavigate() to
449 // determine whether or not to enable the encoding menu.
450 // It's updated only for the main frame. For a subframe,
451 // RenderView::UpdateURL does not set params.contents_mime_type.
452 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
453 // TODO(jungshik): Add a test for the encoding menu to avoid
454 // regressing it again.
455 // TODO(nasko): Verify the correctness of the above comment, since some of the
456 // code doesn't exist anymore. Also, move this code in the
457 // PageTransitionIsMainFrame code block above.
458 if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
459 delegate_->SetMainFrameMimeType(params.contents_mime_type);
461 LoadCommittedDetails details;
462 bool did_navigate = controller_->RendererDidNavigate(render_frame_host,
463 params, &details);
465 // Keep track of each frame's URL in its FrameTreeNode.
466 render_frame_host->frame_tree_node()->SetCurrentURL(params.url);
468 // Send notification about committed provisional loads. This notification is
469 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
470 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
471 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
472 DCHECK_EQ(!render_frame_host->GetParent(),
473 did_navigate ? details.is_main_frame : false);
474 ui::PageTransition transition_type = params.transition;
475 // Whether or not a page transition was triggered by going backward or
476 // forward in the history is only stored in the navigation controller's
477 // entry list.
478 if (did_navigate &&
479 (controller_->GetLastCommittedEntry()->GetTransitionType() &
480 ui::PAGE_TRANSITION_FORWARD_BACK)) {
481 transition_type = ui::PageTransitionFromInt(
482 params.transition | ui::PAGE_TRANSITION_FORWARD_BACK);
485 delegate_->DidCommitProvisionalLoad(render_frame_host,
486 params.url,
487 transition_type);
488 render_frame_host->navigation_handle()->DidCommitNavigation();
491 if (!did_navigate)
492 return; // No navigation happened.
494 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
495 // for the appropriate notification (best) or you can add it to
496 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
497 // necessary, please).
499 // TODO(carlosk): Move this out when PlzNavigate implementation properly calls
500 // the observer methods.
501 RecordNavigationMetrics(details, params, site_instance);
503 // Run post-commit tasks.
504 if (delegate_) {
505 if (details.is_main_frame) {
506 delegate_->DidNavigateMainFramePostCommit(render_frame_host,
507 details, params);
510 delegate_->DidNavigateAnyFramePostCommit(
511 render_frame_host, details, params);
515 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
516 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
517 // still be used for a normal web site.
518 if (url == GURL(url::kAboutBlankURL))
519 return false;
521 // The embedder will then have the opportunity to determine if the URL
522 // should "use up" the SiteInstance.
523 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
526 void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
527 const GURL& url,
528 SiteInstance* source_site_instance,
529 const Referrer& referrer,
530 WindowOpenDisposition disposition,
531 bool should_replace_current_entry,
532 bool user_gesture) {
533 SiteInstance* current_site_instance =
534 GetRenderManager(render_frame_host)->current_frame_host()->
535 GetSiteInstance();
536 // If this came from a swapped out RenderFrameHost, we only allow the request
537 // if we are still in the same BrowsingInstance.
538 // TODO(creis): Move this to RenderFrameProxyHost::OpenURL.
539 if (render_frame_host->is_swapped_out() &&
540 !render_frame_host->GetSiteInstance()->IsRelatedSiteInstance(
541 current_site_instance)) {
542 return;
545 // Delegate to RequestTransferURL because this is just the generic
546 // case where |old_request_id| is empty.
547 // TODO(creis): Pass the redirect_chain into this method to support client
548 // redirects. http://crbug.com/311721.
549 std::vector<GURL> redirect_chain;
550 RequestTransferURL(render_frame_host, url, source_site_instance,
551 redirect_chain, referrer, ui::PAGE_TRANSITION_LINK,
552 disposition, GlobalRequestID(),
553 should_replace_current_entry, user_gesture);
556 void NavigatorImpl::RequestTransferURL(
557 RenderFrameHostImpl* render_frame_host,
558 const GURL& url,
559 SiteInstance* source_site_instance,
560 const std::vector<GURL>& redirect_chain,
561 const Referrer& referrer,
562 ui::PageTransition page_transition,
563 WindowOpenDisposition disposition,
564 const GlobalRequestID& transferred_global_request_id,
565 bool should_replace_current_entry,
566 bool user_gesture) {
567 GURL dest_url(url);
568 SiteInstance* current_site_instance =
569 GetRenderManager(render_frame_host)->current_frame_host()->
570 GetSiteInstance();
571 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
572 current_site_instance, url)) {
573 dest_url = GURL(url::kAboutBlankURL);
576 int frame_tree_node_id = -1;
578 // Send the navigation to the current FrameTreeNode if it's destined for a
579 // subframe in the current tab. We'll assume it's for the main frame
580 // (possibly of a new or different WebContents) otherwise.
581 if (SiteIsolationPolicy::AreCrossProcessFramesPossible() &&
582 disposition == CURRENT_TAB && render_frame_host->GetParent()) {
583 frame_tree_node_id =
584 render_frame_host->frame_tree_node()->frame_tree_node_id();
587 OpenURLParams params(
588 dest_url, referrer, frame_tree_node_id, disposition, page_transition,
589 true /* is_renderer_initiated */);
590 params.source_site_instance = source_site_instance;
591 if (redirect_chain.size() > 0)
592 params.redirect_chain = redirect_chain;
593 params.transferred_global_request_id = transferred_global_request_id;
594 params.should_replace_current_entry = should_replace_current_entry;
595 params.user_gesture = user_gesture;
597 if (GetRenderManager(render_frame_host)->web_ui()) {
598 // Web UI pages sometimes want to override the page transition type for
599 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
600 // automatically generated suggestions). We don't override other types
601 // like TYPED because they have different implications (e.g., autocomplete).
602 if (ui::PageTransitionCoreTypeIs(
603 params.transition, ui::PAGE_TRANSITION_LINK))
604 params.transition =
605 GetRenderManager(render_frame_host)->web_ui()->
606 GetLinkTransitionType();
608 // Note also that we hide the referrer for Web UI pages. We don't really
609 // want web sites to see a referrer of "chrome://blah" (and some
610 // chrome: URLs might have search terms or other stuff we don't want to
611 // send to the site), so we send no referrer.
612 params.referrer = Referrer();
614 // Navigations in Web UI pages count as browser-initiated navigations.
615 params.is_renderer_initiated = false;
618 if (delegate_)
619 delegate_->RequestOpenURL(render_frame_host, params);
622 // PlzNavigate
623 void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
624 bool proceed) {
625 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
626 switches::kEnableBrowserSideNavigation));
627 DCHECK(frame_tree_node);
629 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
631 // The NavigationRequest may have been canceled while the renderer was
632 // executing the BeforeUnload event.
633 if (!navigation_request)
634 return;
636 DCHECK_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
637 navigation_request->state());
639 // If the navigation is allowed to proceed, send the request to the IO thread.
640 if (proceed)
641 navigation_request->BeginNavigation();
642 else
643 CancelNavigation(frame_tree_node);
646 // PlzNavigate
647 void NavigatorImpl::OnBeginNavigation(
648 FrameTreeNode* frame_tree_node,
649 const CommonNavigationParams& common_params,
650 const BeginNavigationParams& begin_params,
651 scoped_refptr<ResourceRequestBody> body) {
652 // TODO(clamy): the url sent by the renderer should be validated with
653 // FilterURL.
654 // This is a renderer-initiated navigation.
655 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
656 switches::kEnableBrowserSideNavigation));
657 DCHECK(frame_tree_node);
659 NavigationRequest* ongoing_navigation_request =
660 frame_tree_node->navigation_request();
662 // The renderer-initiated navigation request is ignored iff a) there is an
663 // ongoing request b) which is browser or user-initiated and c) the renderer
664 // request is not user-initiated.
665 if (ongoing_navigation_request &&
666 (ongoing_navigation_request->browser_initiated() ||
667 ongoing_navigation_request->begin_params().has_user_gesture) &&
668 !begin_params.has_user_gesture) {
669 return;
672 // In all other cases the current navigation, if any, is canceled and a new
673 // NavigationRequest is created for the node.
674 frame_tree_node->CreatedNavigationRequest(
675 NavigationRequest::CreateRendererInitiated(
676 frame_tree_node, common_params, begin_params, body,
677 controller_->GetLastCommittedEntryIndex(),
678 controller_->GetEntryCount()));
679 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
680 navigation_request->CreateNavigationHandle(delegate_);
682 if (frame_tree_node->IsMainFrame()) {
683 // Renderer-initiated main-frame navigations that need to swap processes
684 // will go to the browser via a OpenURL call, and then be handled by the
685 // same code path as browser-initiated navigations. For renderer-initiated
686 // main frame navigation that start via a BeginNavigation IPC, the
687 // RenderFrameHost will not be swapped. Therefore it is safe to call
688 // DidStartMainFrameNavigation with the SiteInstance from the current
689 // RenderFrameHost.
690 DidStartMainFrameNavigation(
691 common_params.url,
692 frame_tree_node->current_frame_host()->GetSiteInstance());
693 navigation_data_.reset();
696 navigation_request->BeginNavigation();
699 // PlzNavigate
700 void NavigatorImpl::CommitNavigation(FrameTreeNode* frame_tree_node,
701 ResourceResponse* response,
702 scoped_ptr<StreamHandle> body) {
703 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
704 switches::kEnableBrowserSideNavigation));
706 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
707 DCHECK(navigation_request);
708 DCHECK(response ||
709 !ShouldMakeNetworkRequestForURL(
710 navigation_request->common_params().url));
712 // HTTP 204 (No Content) and HTTP 205 (Reset Content) responses should not
713 // commit; they leave the frame showing the previous page.
714 if (response && response->head.headers.get() &&
715 (response->head.headers->response_code() == 204 ||
716 response->head.headers->response_code() == 205)) {
717 CancelNavigation(frame_tree_node);
718 return;
721 // Select an appropriate renderer to commit the navigation.
722 RenderFrameHostImpl* render_frame_host =
723 frame_tree_node->render_manager()->GetFrameHostForNavigation(
724 *navigation_request);
726 // The renderer can exit view source mode when any error or cancellation
727 // happen. When reusing the same renderer, overwrite to recover the mode.
728 if (navigation_request->is_view_source() &&
729 render_frame_host ==
730 frame_tree_node->render_manager()->current_frame_host()) {
731 DCHECK(!render_frame_host->GetParent());
732 render_frame_host->render_view_host()->Send(
733 new ViewMsg_EnableViewSourceMode(
734 render_frame_host->render_view_host()->GetRoutingID()));
737 CheckWebUIRendererDoesNotDisplayNormalURL(
738 render_frame_host, navigation_request->common_params().url);
740 navigation_request->TransferNavigationHandleOwnership(render_frame_host);
741 render_frame_host->CommitNavigation(response, body.Pass(),
742 navigation_request->common_params(),
743 navigation_request->request_params());
747 // PlzNavigate
748 void NavigatorImpl::FailedNavigation(FrameTreeNode* frame_tree_node,
749 bool has_stale_copy_in_cache,
750 int error_code) {
751 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
752 switches::kEnableBrowserSideNavigation));
754 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
755 DCHECK(navigation_request);
757 // If the request was canceled by the user do not show an error page.
758 if (error_code == net::ERR_ABORTED) {
759 frame_tree_node->ResetNavigationRequest(false);
760 return;
763 // Select an appropriate renderer to show the error page.
764 RenderFrameHostImpl* render_frame_host =
765 frame_tree_node->render_manager()->GetFrameHostForNavigation(
766 *navigation_request);
767 CheckWebUIRendererDoesNotDisplayNormalURL(
768 render_frame_host, navigation_request->common_params().url);
770 navigation_request->TransferNavigationHandleOwnership(render_frame_host);
771 render_frame_host->FailedNavigation(navigation_request->common_params(),
772 navigation_request->request_params(),
773 has_stale_copy_in_cache, error_code);
776 // PlzNavigate
777 void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) {
778 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
779 switches::kEnableBrowserSideNavigation));
780 frame_tree_node->ResetNavigationRequest(false);
781 if (frame_tree_node->IsMainFrame())
782 navigation_data_.reset();
785 void NavigatorImpl::LogResourceRequestTime(
786 base::TimeTicks timestamp, const GURL& url) {
787 if (navigation_data_ && navigation_data_->url_ == url) {
788 navigation_data_->url_job_start_time_ = timestamp;
789 UMA_HISTOGRAM_TIMES(
790 "Navigation.TimeToURLJobStart",
791 navigation_data_->url_job_start_time_ - navigation_data_->start_time_);
795 void NavigatorImpl::LogBeforeUnloadTime(
796 const base::TimeTicks& renderer_before_unload_start_time,
797 const base::TimeTicks& renderer_before_unload_end_time) {
798 // Only stores the beforeunload delay if we're tracking a browser initiated
799 // navigation and it happened later than the navigation request.
800 if (navigation_data_ &&
801 renderer_before_unload_start_time > navigation_data_->start_time_) {
802 navigation_data_->before_unload_delay_ =
803 renderer_before_unload_end_time - renderer_before_unload_start_time;
807 void NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL(
808 RenderFrameHostImpl* render_frame_host,
809 const GURL& url) {
810 int enabled_bindings =
811 render_frame_host->render_view_host()->GetEnabledBindings();
812 bool is_allowed_in_web_ui_renderer =
813 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
814 controller_->GetBrowserContext(), url);
815 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
816 !is_allowed_in_web_ui_renderer) {
817 // Log the URL to help us diagnose any future failures of this CHECK.
818 GetContentClient()->SetActiveURL(url);
819 CHECK(0);
823 // PlzNavigate
824 void NavigatorImpl::RequestNavigation(
825 FrameTreeNode* frame_tree_node,
826 const GURL& dest_url,
827 const Referrer& dest_referrer,
828 const FrameNavigationEntry& frame_entry,
829 const NavigationEntryImpl& entry,
830 NavigationController::ReloadType reload_type,
831 bool is_same_document_history_load,
832 base::TimeTicks navigation_start) {
833 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
834 switches::kEnableBrowserSideNavigation));
835 DCHECK(frame_tree_node);
837 // This value must be set here because creating a NavigationRequest might
838 // change the renderer live/non-live status and change this result.
839 bool should_dispatch_beforeunload =
840 frame_tree_node->current_frame_host()->ShouldDispatchBeforeUnload();
841 FrameMsg_Navigate_Type::Value navigation_type =
842 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
843 frame_tree_node->CreatedNavigationRequest(
844 NavigationRequest::CreateBrowserInitiated(
845 frame_tree_node, dest_url, dest_referrer, frame_entry, entry,
846 navigation_type, is_same_document_history_load, navigation_start,
847 controller_));
848 NavigationRequest* navigation_request = frame_tree_node->navigation_request();
849 navigation_request->CreateNavigationHandle(delegate_);
851 // Have the current renderer execute its beforeunload event if needed. If it
852 // is not needed (when beforeunload dispatch is not needed or this navigation
853 // is synchronous and same-site) then NavigationRequest::BeginNavigation
854 // should be directly called instead.
855 if (should_dispatch_beforeunload &&
856 ShouldMakeNetworkRequestForURL(
857 navigation_request->common_params().url)) {
858 navigation_request->SetWaitingForRendererResponse();
859 frame_tree_node->current_frame_host()->DispatchBeforeUnload(true);
860 } else {
861 navigation_request->BeginNavigation();
865 void NavigatorImpl::RecordNavigationMetrics(
866 const LoadCommittedDetails& details,
867 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
868 SiteInstance* site_instance) {
869 DCHECK(site_instance->HasProcess());
871 if (!details.is_in_page)
872 RecordAction(base::UserMetricsAction("FrameLoad"));
874 if (!details.is_main_frame || !navigation_data_ ||
875 navigation_data_->url_job_start_time_.is_null() ||
876 navigation_data_->url_ != params.original_request_url) {
877 return;
880 base::TimeDelta time_to_commit =
881 base::TimeTicks::Now() - navigation_data_->start_time_;
882 UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit);
884 time_to_commit -= navigation_data_->before_unload_delay_;
885 base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ -
886 navigation_data_->start_time_ -
887 navigation_data_->before_unload_delay_;
888 if (navigation_data_->is_restoring_from_last_session_) {
889 UMA_HISTOGRAM_TIMES(
890 "Navigation.TimeToCommit_SessionRestored_BeforeUnloadDiscounted",
891 time_to_commit);
892 UMA_HISTOGRAM_TIMES(
893 "Navigation.TimeToURLJobStart_SessionRestored_BeforeUnloadDiscounted",
894 time_to_network);
895 navigation_data_.reset();
896 return;
898 bool navigation_created_new_renderer_process =
899 site_instance->GetProcess()->GetInitTimeForNavigationMetrics() >
900 navigation_data_->start_time_;
901 if (navigation_created_new_renderer_process) {
902 UMA_HISTOGRAM_TIMES(
903 "Navigation.TimeToCommit_NewRenderer_BeforeUnloadDiscounted",
904 time_to_commit);
905 UMA_HISTOGRAM_TIMES(
906 "Navigation.TimeToURLJobStart_NewRenderer_BeforeUnloadDiscounted",
907 time_to_network);
908 } else {
909 UMA_HISTOGRAM_TIMES(
910 "Navigation.TimeToCommit_ExistingRenderer_BeforeUnloadDiscounted",
911 time_to_commit);
912 UMA_HISTOGRAM_TIMES(
913 "Navigation.TimeToURLJobStart_ExistingRenderer_BeforeUnloadDiscounted",
914 time_to_network);
916 navigation_data_.reset();
919 void NavigatorImpl::DidStartMainFrameNavigation(
920 const GURL& url,
921 SiteInstanceImpl* site_instance) {
922 // If there is no browser-initiated pending entry for this navigation and it
923 // is not for the error URL, create a pending entry using the current
924 // SiteInstance, and ensure the address bar updates accordingly. We don't
925 // know the referrer or extra headers at this point, but the referrer will
926 // be set properly upon commit.
927 NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
928 bool has_browser_initiated_pending_entry =
929 pending_entry && !pending_entry->is_renderer_initiated();
930 if (!has_browser_initiated_pending_entry) {
931 scoped_ptr<NavigationEntryImpl> entry =
932 NavigationEntryImpl::FromNavigationEntry(
933 controller_->CreateNavigationEntry(
934 url, content::Referrer(), ui::PAGE_TRANSITION_LINK,
935 true /* is_renderer_initiated */, std::string(),
936 controller_->GetBrowserContext()));
937 entry->set_site_instance(site_instance);
938 // TODO(creis): If there's a pending entry already, find a safe way to
939 // update it instead of replacing it and copying over things like this.
940 if (pending_entry) {
941 entry->set_transferred_global_request_id(
942 pending_entry->transferred_global_request_id());
943 entry->set_should_replace_entry(pending_entry->should_replace_entry());
944 entry->SetRedirectChain(pending_entry->GetRedirectChain());
946 controller_->SetPendingEntry(entry.Pass());
947 if (delegate_)
948 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
952 } // namespace content