Use multiline attribute to check for IA2_STATE_MULTILINE.
[chromium-blink-merge.git] / content / browser / frame_host / navigator_impl.cc
blob527eda7d6c833688a45331a6b1d1c5ee40d9771b
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 } // namespace
82 struct NavigatorImpl::NavigationMetricsData {
83 NavigationMetricsData(base::TimeTicks start_time,
84 GURL url,
85 NavigationEntryImpl::RestoreType restore_type)
86 : start_time_(start_time), url_(url) {
87 is_restoring_from_last_session_ =
88 (restore_type ==
89 NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY ||
90 restore_type == NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED);
93 base::TimeTicks start_time_;
94 GURL url_;
95 bool is_restoring_from_last_session_;
96 base::TimeTicks url_job_start_time_;
97 base::TimeDelta before_unload_delay_;
100 NavigatorImpl::NavigatorImpl(
101 NavigationControllerImpl* navigation_controller,
102 NavigatorDelegate* delegate)
103 : controller_(navigation_controller),
104 delegate_(delegate) {
107 NavigatorImpl::~NavigatorImpl() {}
109 NavigationController* NavigatorImpl::GetController() {
110 return controller_;
113 void NavigatorImpl::DidStartProvisionalLoad(
114 RenderFrameHostImpl* render_frame_host,
115 const GURL& url,
116 bool is_transition_navigation) {
117 bool is_error_page = (url.spec() == kUnreachableWebDataURL);
118 bool is_iframe_srcdoc = (url.spec() == kAboutSrcDocURL);
119 GURL validated_url(url);
120 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
121 render_process_host->FilterURL(false, &validated_url);
123 bool is_main_frame = render_frame_host->frame_tree_node()->IsMainFrame();
124 NavigationEntryImpl* pending_entry = controller_->GetPendingEntry();
125 if (is_main_frame) {
126 // If there is no browser-initiated pending entry for this navigation and it
127 // is not for the error URL, create a pending entry using the current
128 // SiteInstance, and ensure the address bar updates accordingly. We don't
129 // know the referrer or extra headers at this point, but the referrer will
130 // be set properly upon commit.
131 bool has_browser_initiated_pending_entry = pending_entry &&
132 !pending_entry->is_renderer_initiated();
133 if (!has_browser_initiated_pending_entry && !is_error_page) {
134 NavigationEntryImpl* entry = NavigationEntryImpl::FromNavigationEntry(
135 controller_->CreateNavigationEntry(validated_url,
136 content::Referrer(),
137 ui::PAGE_TRANSITION_LINK,
138 true /* is_renderer_initiated */,
139 std::string(),
140 controller_->GetBrowserContext()));
141 entry->set_site_instance(render_frame_host->GetSiteInstance());
142 // TODO(creis): If there's a pending entry already, find a safe way to
143 // update it instead of replacing it and copying over things like this.
144 if (pending_entry) {
145 entry->set_transferred_global_request_id(
146 pending_entry->transferred_global_request_id());
147 entry->set_should_replace_entry(pending_entry->should_replace_entry());
148 entry->SetRedirectChain(pending_entry->GetRedirectChain());
150 controller_->SetPendingEntry(entry);
151 if (delegate_)
152 delegate_->NotifyChangedNavigationState(content::INVALIDATE_TYPE_URL);
155 if (delegate_ && is_transition_navigation)
156 delegate_->DidStartNavigationTransition(render_frame_host);
159 if (delegate_) {
160 // Notify the observer about the start of the provisional load.
161 delegate_->DidStartProvisionalLoad(
162 render_frame_host, validated_url, is_error_page, is_iframe_srcdoc);
167 void NavigatorImpl::DidFailProvisionalLoadWithError(
168 RenderFrameHostImpl* render_frame_host,
169 const FrameHostMsg_DidFailProvisionalLoadWithError_Params& params) {
170 VLOG(1) << "Failed Provisional Load: " << params.url.possibly_invalid_spec()
171 << ", error_code: " << params.error_code
172 << ", error_description: " << params.error_description
173 << ", showing_repost_interstitial: " <<
174 params.showing_repost_interstitial
175 << ", frame_id: " << render_frame_host->GetRoutingID();
176 GURL validated_url(params.url);
177 RenderProcessHost* render_process_host = render_frame_host->GetProcess();
178 render_process_host->FilterURL(false, &validated_url);
180 if (net::ERR_ABORTED == params.error_code) {
181 // EVIL HACK ALERT! Ignore failed loads when we're showing interstitials.
182 // This means that the interstitial won't be torn down properly, which is
183 // bad. But if we have an interstitial, go back to another tab type, and
184 // then load the same interstitial again, we could end up getting the first
185 // interstitial's "failed" message (as a result of the cancel) when we're on
186 // the second one. We can't tell this apart, so we think we're tearing down
187 // the current page which will cause a crash later on.
189 // http://code.google.com/p/chromium/issues/detail?id=2855
190 // Because this will not tear down the interstitial properly, if "back" is
191 // back to another tab type, the interstitial will still be somewhat alive
192 // in the previous tab type. If you navigate somewhere that activates the
193 // tab with the interstitial again, you'll see a flash before the new load
194 // commits of the interstitial page.
195 FrameTreeNode* root =
196 render_frame_host->frame_tree_node()->frame_tree()->root();
197 if (root->render_manager()->interstitial_page() != NULL) {
198 LOG(WARNING) << "Discarding message during interstitial.";
199 return;
202 // We used to cancel the pending renderer here for cross-site downloads.
203 // However, it's not safe to do that because the download logic repeatedly
204 // looks for this WebContents based on a render ID. Instead, we just
205 // leave the pending renderer around until the next navigation event
206 // (Navigate, DidNavigate, etc), which will clean it up properly.
208 // TODO(creis): Find a way to cancel any pending RFH here.
211 // We usually clear the pending entry when it fails, so that an arbitrary URL
212 // isn't left visible above a committed page. This must be enforced when
213 // the pending entry isn't visible (e.g., renderer-initiated navigations) to
214 // prevent URL spoofs for in-page navigations that don't go through
215 // DidStartProvisionalLoadForFrame.
217 // However, we do preserve the pending entry in some cases, such as on the
218 // initial navigation of an unmodified blank tab. We also allow the delegate
219 // to say when it's safe to leave aborted URLs in the omnibox, to let the user
220 // edit the URL and try again. This may be useful in cases that the committed
221 // page cannot be attacker-controlled. In these cases, we still allow the
222 // view to clear the pending entry and typed URL if the user requests
223 // (e.g., hitting Escape with focus in the address bar).
225 // Note: don't touch the transient entry, since an interstitial may exist.
226 bool should_preserve_entry = controller_->IsUnmodifiedBlankTab() ||
227 delegate_->ShouldPreserveAbortedURLs();
228 if (controller_->GetPendingEntry() != controller_->GetVisibleEntry() ||
229 !should_preserve_entry) {
230 controller_->DiscardPendingEntry(true);
232 // Also force the UI to refresh.
233 controller_->delegate()->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
236 if (delegate_)
237 delegate_->DidFailProvisionalLoadWithError(render_frame_host, params);
240 void NavigatorImpl::DidFailLoadWithError(
241 RenderFrameHostImpl* render_frame_host,
242 const GURL& url,
243 int error_code,
244 const base::string16& error_description) {
245 if (delegate_) {
246 delegate_->DidFailLoadWithError(
247 render_frame_host, url, error_code,
248 error_description);
252 bool NavigatorImpl::NavigateToEntry(
253 FrameTreeNode* frame_tree_node,
254 const NavigationEntryImpl& entry,
255 NavigationController::ReloadType reload_type) {
256 TRACE_EVENT0("browser,navigation", "NavigatorImpl::NavigateToEntry");
258 // The renderer will reject IPC messages with URLs longer than
259 // this limit, so don't attempt to navigate with a longer URL.
260 if (entry.GetURL().spec().size() > GetMaxURLChars()) {
261 LOG(WARNING) << "Refusing to load URL as it exceeds " << GetMaxURLChars()
262 << " characters.";
263 return false;
266 // This will be used to set the Navigation Timing API navigationStart
267 // parameter for browser navigations in new tabs (intents, tabs opened through
268 // "Open link in new tab"). We need to keep it above RFHM::Navigate() call to
269 // capture the time needed for the RenderFrameHost initialization.
270 base::TimeTicks navigation_start = base::TimeTicks::Now();
272 RenderFrameHostManager* manager = frame_tree_node->render_manager();
274 // PlzNavigate: the RenderFrameHosts are no longer asked to navigate.
275 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
276 switches::kEnableBrowserSideNavigation)) {
277 navigation_data_.reset(new NavigationMetricsData(
278 navigation_start, entry.GetURL(), entry.restore_type()));
279 RequestNavigation(frame_tree_node, entry, reload_type, navigation_start);
281 // Notify observers about navigation.
282 if (delegate_)
283 delegate_->DidStartNavigationToPendingEntry(entry.GetURL(), reload_type);
285 return true;
288 RenderFrameHostImpl* dest_render_frame_host = manager->Navigate(entry);
289 if (!dest_render_frame_host)
290 return false; // Unable to create the desired RenderFrameHost.
292 // Make sure no code called via RFHM::Navigate clears the pending entry.
293 CHECK_EQ(controller_->GetPendingEntry(), &entry);
295 // For security, we should never send non-Web-UI URLs to a Web UI renderer.
296 // Double check that here.
297 CheckWebUIRendererDoesNotDisplayNormalURL(
298 dest_render_frame_host, entry.GetURL());
300 // Notify observers that we will navigate in this RenderFrame.
301 if (delegate_) {
302 delegate_->AboutToNavigateRenderFrame(frame_tree_node->current_frame_host(),
303 dest_render_frame_host);
306 // Navigate in the desired RenderFrameHost.
307 // We can skip this step in the rare case that this is a transfer navigation
308 // which began in the chosen RenderFrameHost, since the request has already
309 // been issued. In that case, simply resume the response.
310 bool is_transfer_to_same =
311 entry.transferred_global_request_id().child_id != -1 &&
312 entry.transferred_global_request_id().child_id ==
313 dest_render_frame_host->GetProcess()->GetID();
314 if (!is_transfer_to_same) {
315 navigation_data_.reset(new NavigationMetricsData(
316 navigation_start, entry.GetURL(), entry.restore_type()));
317 // Create the navigation parameters.
318 // TODO(vitalybuka): Move this before AboutToNavigateRenderFrame once
319 // http://crbug.com/408684 is fixed.
320 FrameMsg_Navigate_Type::Value navigation_type =
321 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
322 dest_render_frame_host->Navigate(
323 entry.ConstructCommonNavigationParams(navigation_type),
324 entry.ConstructStartNavigationParams(),
325 entry.ConstructRequestNavigationParams(
326 navigation_start, controller_->GetIndexOfEntry(&entry),
327 controller_->GetLastCommittedEntryIndex(),
328 controller_->GetEntryCount()));
329 } else {
330 // No need to navigate again. Just resume the deferred request.
331 dest_render_frame_host->GetProcess()->ResumeDeferredNavigation(
332 entry.transferred_global_request_id());
335 // Make sure no code called via RFH::Navigate clears the pending entry.
336 CHECK_EQ(controller_->GetPendingEntry(), &entry);
338 if (entry.GetPageID() == -1) {
339 // HACK!! This code suppresses javascript: URLs from being added to
340 // session history, which is what we want to do for javascript: URLs that
341 // do not generate content. What we really need is a message from the
342 // renderer telling us that a new page was not created. The same message
343 // could be used for mailto: URLs and the like.
344 if (entry.GetURL().SchemeIs(url::kJavaScriptScheme))
345 return false;
348 // Notify observers about navigation.
349 if (delegate_)
350 delegate_->DidStartNavigationToPendingEntry(entry.GetURL(), reload_type);
352 return true;
355 bool NavigatorImpl::NavigateToPendingEntry(
356 FrameTreeNode* frame_tree_node,
357 NavigationController::ReloadType reload_type) {
358 return NavigateToEntry(frame_tree_node, *controller_->GetPendingEntry(),
359 reload_type);
362 void NavigatorImpl::DidNavigate(
363 RenderFrameHostImpl* render_frame_host,
364 const FrameHostMsg_DidCommitProvisionalLoad_Params& input_params) {
365 // PlzNavigate
366 // The navigation request has been committed so the browser process doesn't
367 // need to care about it anymore.
368 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
369 switches::kEnableBrowserSideNavigation)) {
370 navigation_request_map_.erase(
371 render_frame_host->frame_tree_node()->frame_tree_node_id());
374 FrameHostMsg_DidCommitProvisionalLoad_Params params(input_params);
375 FrameTree* frame_tree = render_frame_host->frame_tree_node()->frame_tree();
376 bool use_site_per_process = base::CommandLine::ForCurrentProcess()->HasSwitch(
377 switches::kSitePerProcess);
379 if (ui::PageTransitionIsMainFrame(params.transition)) {
380 if (delegate_) {
381 // When overscroll navigation gesture is enabled, a screenshot of the page
382 // in its current state is taken so that it can be used during the
383 // nav-gesture. It is necessary to take the screenshot here, before
384 // calling RenderFrameHostManager::DidNavigateMainFrame, because that can
385 // change WebContents::GetRenderViewHost to return the new host, instead
386 // of the one that may have just been swapped out.
387 if (delegate_->CanOverscrollContent()) {
388 // Don't take screenshots if we are staying on the same page. We want
389 // in-page navigations to be super fast, and taking a screenshot
390 // currently blocks GPU for a longer time than we are willing to
391 // tolerate in this use case.
392 if (!params.was_within_same_page)
393 controller_->TakeScreenshot();
396 // Run tasks that must execute just before the commit.
397 bool is_navigation_within_page = controller_->IsURLInPageNavigation(
398 params.url, params.was_within_same_page, render_frame_host);
399 delegate_->DidNavigateMainFramePreCommit(is_navigation_within_page);
402 if (!use_site_per_process)
403 frame_tree->root()->render_manager()->DidNavigateFrame(
404 render_frame_host, params.gesture == NavigationGestureUser);
407 // Save the origin of the new page. Do this before calling
408 // DidNavigateFrame(), because the origin needs to be included in the SwapOut
409 // message, which is sent inside DidNavigateFrame(). SwapOut needs the
410 // origin because it creates a RenderFrameProxy that needs this to initialize
411 // its security context. This origin will also be sent to RenderFrameProxies
412 // created via ViewMsg_New and FrameMsg_NewFrameProxy.
413 render_frame_host->frame_tree_node()->set_current_origin(params.origin);
415 // When using --site-per-process, we notify the RFHM for all navigations,
416 // not just main frame navigations.
417 if (use_site_per_process) {
418 FrameTreeNode* frame = render_frame_host->frame_tree_node();
419 frame->render_manager()->DidNavigateFrame(
420 render_frame_host, params.gesture == NavigationGestureUser);
423 // Update the site of the SiteInstance if it doesn't have one yet, unless
424 // assigning a site is not necessary for this URL. In that case, the
425 // SiteInstance can still be considered unused until a navigation to a real
426 // page.
427 SiteInstanceImpl* site_instance = render_frame_host->GetSiteInstance();
428 if (!site_instance->HasSite() &&
429 ShouldAssignSiteForURL(params.url)) {
430 site_instance->SetSite(params.url);
433 // Need to update MIME type here because it's referred to in
434 // UpdateNavigationCommands() called by RendererDidNavigate() to
435 // determine whether or not to enable the encoding menu.
436 // It's updated only for the main frame. For a subframe,
437 // RenderView::UpdateURL does not set params.contents_mime_type.
438 // (see http://code.google.com/p/chromium/issues/detail?id=2929 )
439 // TODO(jungshik): Add a test for the encoding menu to avoid
440 // regressing it again.
441 // TODO(nasko): Verify the correctness of the above comment, since some of the
442 // code doesn't exist anymore. Also, move this code in the
443 // PageTransitionIsMainFrame code block above.
444 if (ui::PageTransitionIsMainFrame(params.transition) && delegate_)
445 delegate_->SetMainFrameMimeType(params.contents_mime_type);
447 LoadCommittedDetails details;
448 bool did_navigate = controller_->RendererDidNavigate(render_frame_host,
449 params, &details);
451 // For now, keep track of each frame's URL in its FrameTreeNode. This lets
452 // us estimate our process count for implementing OOP iframes.
453 // TODO(creis): Remove this when we track which pages commit in each frame.
454 render_frame_host->frame_tree_node()->set_current_url(params.url);
456 // Send notification about committed provisional loads. This notification is
457 // different from the NAV_ENTRY_COMMITTED notification which doesn't include
458 // the actual URL navigated to and isn't sent for AUTO_SUBFRAME navigations.
459 if (details.type != NAVIGATION_TYPE_NAV_IGNORE && delegate_) {
460 DCHECK_EQ(!render_frame_host->GetParent(),
461 did_navigate ? details.is_main_frame : false);
462 ui::PageTransition transition_type = params.transition;
463 // Whether or not a page transition was triggered by going backward or
464 // forward in the history is only stored in the navigation controller's
465 // entry list.
466 if (did_navigate &&
467 (controller_->GetLastCommittedEntry()->GetTransitionType() &
468 ui::PAGE_TRANSITION_FORWARD_BACK)) {
469 transition_type = ui::PageTransitionFromInt(
470 params.transition | ui::PAGE_TRANSITION_FORWARD_BACK);
473 delegate_->DidCommitProvisionalLoad(render_frame_host,
474 params.url,
475 transition_type);
478 if (!did_navigate)
479 return; // No navigation happened.
481 // DO NOT ADD MORE STUFF TO THIS FUNCTION! Your component should either listen
482 // for the appropriate notification (best) or you can add it to
483 // DidNavigateMainFramePostCommit / DidNavigateAnyFramePostCommit (only if
484 // necessary, please).
486 // TODO(carlosk): Move this out when PlzNavigate implementation properly calls
487 // the observer methods.
488 RecordNavigationMetrics(details, params, site_instance);
490 // Run post-commit tasks.
491 if (delegate_) {
492 if (details.is_main_frame) {
493 delegate_->DidNavigateMainFramePostCommit(render_frame_host,
494 details, params);
497 delegate_->DidNavigateAnyFramePostCommit(
498 render_frame_host, details, params);
502 bool NavigatorImpl::ShouldAssignSiteForURL(const GURL& url) {
503 // about:blank should not "use up" a new SiteInstance. The SiteInstance can
504 // still be used for a normal web site.
505 if (url == GURL(url::kAboutBlankURL))
506 return false;
508 // The embedder will then have the opportunity to determine if the URL
509 // should "use up" the SiteInstance.
510 return GetContentClient()->browser()->ShouldAssignSiteForURL(url);
513 void NavigatorImpl::RequestOpenURL(RenderFrameHostImpl* render_frame_host,
514 const GURL& url,
515 SiteInstance* source_site_instance,
516 const Referrer& referrer,
517 WindowOpenDisposition disposition,
518 bool should_replace_current_entry,
519 bool user_gesture) {
520 SiteInstance* current_site_instance =
521 GetRenderManager(render_frame_host)->current_frame_host()->
522 GetSiteInstance();
523 // If this came from a swapped out RenderFrameHost, we only allow the request
524 // if we are still in the same BrowsingInstance.
525 // TODO(creis): Move this to RenderFrameProxyHost::OpenURL.
526 if (render_frame_host->is_swapped_out() &&
527 !render_frame_host->GetSiteInstance()->IsRelatedSiteInstance(
528 current_site_instance)) {
529 return;
532 // Delegate to RequestTransferURL because this is just the generic
533 // case where |old_request_id| is empty.
534 // TODO(creis): Pass the redirect_chain into this method to support client
535 // redirects. http://crbug.com/311721.
536 std::vector<GURL> redirect_chain;
537 RequestTransferURL(render_frame_host, url, source_site_instance,
538 redirect_chain, referrer, ui::PAGE_TRANSITION_LINK,
539 disposition, GlobalRequestID(),
540 should_replace_current_entry, user_gesture);
543 void NavigatorImpl::RequestTransferURL(
544 RenderFrameHostImpl* render_frame_host,
545 const GURL& url,
546 SiteInstance* source_site_instance,
547 const std::vector<GURL>& redirect_chain,
548 const Referrer& referrer,
549 ui::PageTransition page_transition,
550 WindowOpenDisposition disposition,
551 const GlobalRequestID& transferred_global_request_id,
552 bool should_replace_current_entry,
553 bool user_gesture) {
554 GURL dest_url(url);
555 SiteInstance* current_site_instance =
556 GetRenderManager(render_frame_host)->current_frame_host()->
557 GetSiteInstance();
558 if (!GetContentClient()->browser()->ShouldAllowOpenURL(
559 current_site_instance, url)) {
560 dest_url = GURL(url::kAboutBlankURL);
563 int64 frame_tree_node_id = -1;
565 // Send the navigation to the current FrameTreeNode if it's destined for a
566 // subframe in the current tab. We'll assume it's for the main frame
567 // (possibly of a new or different WebContents) otherwise.
568 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
569 switches::kSitePerProcess) &&
570 disposition == CURRENT_TAB &&
571 render_frame_host->GetParent()) {
572 frame_tree_node_id =
573 render_frame_host->frame_tree_node()->frame_tree_node_id();
576 OpenURLParams params(
577 dest_url, referrer, frame_tree_node_id, disposition, page_transition,
578 true /* is_renderer_initiated */);
579 params.source_site_instance = source_site_instance;
580 if (redirect_chain.size() > 0)
581 params.redirect_chain = redirect_chain;
582 params.transferred_global_request_id = transferred_global_request_id;
583 params.should_replace_current_entry = should_replace_current_entry;
584 params.user_gesture = user_gesture;
586 if (GetRenderManager(render_frame_host)->web_ui()) {
587 // Web UI pages sometimes want to override the page transition type for
588 // link clicks (e.g., so the new tab page can specify AUTO_BOOKMARK for
589 // automatically generated suggestions). We don't override other types
590 // like TYPED because they have different implications (e.g., autocomplete).
591 if (ui::PageTransitionCoreTypeIs(
592 params.transition, ui::PAGE_TRANSITION_LINK))
593 params.transition =
594 GetRenderManager(render_frame_host)->web_ui()->
595 GetLinkTransitionType();
597 // Note also that we hide the referrer for Web UI pages. We don't really
598 // want web sites to see a referrer of "chrome://blah" (and some
599 // chrome: URLs might have search terms or other stuff we don't want to
600 // send to the site), so we send no referrer.
601 params.referrer = Referrer();
603 // Navigations in Web UI pages count as browser-initiated navigations.
604 params.is_renderer_initiated = false;
607 if (delegate_)
608 delegate_->RequestOpenURL(render_frame_host, params);
611 // PlzNavigate
612 void NavigatorImpl::OnBeforeUnloadACK(FrameTreeNode* frame_tree_node,
613 bool proceed) {
614 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
615 switches::kEnableBrowserSideNavigation));
616 DCHECK(frame_tree_node);
618 NavigationRequest* navigation_request =
619 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
621 // The NavigationRequest may have been canceled while the renderer was
622 // executing the BeforeUnload event.
623 if (!navigation_request)
624 return;
626 DCHECK_EQ(NavigationRequest::WAITING_FOR_RENDERER_RESPONSE,
627 navigation_request->state());
629 if (proceed)
630 BeginNavigation(frame_tree_node);
631 else
632 CancelNavigation(frame_tree_node);
635 // PlzNavigate
636 void NavigatorImpl::OnBeginNavigation(
637 FrameTreeNode* frame_tree_node,
638 const CommonNavigationParams& common_params,
639 const BeginNavigationParams& begin_params,
640 scoped_refptr<ResourceRequestBody> body) {
641 // This is a renderer-initiated navigation.
642 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
643 switches::kEnableBrowserSideNavigation));
644 DCHECK(frame_tree_node);
646 NavigationRequest* ongoing_navigation_request =
647 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
649 // The renderer-initiated navigation request is ignored iff a) there is an
650 // ongoing request b) which is browser or user-initiated and c) the renderer
651 // request is not user-initiated.
652 if (ongoing_navigation_request &&
653 (ongoing_navigation_request->browser_initiated() ||
654 ongoing_navigation_request->begin_params().has_user_gesture) &&
655 !begin_params.has_user_gesture) {
656 return;
659 // In all other cases the current navigation, if any, is canceled and a new
660 // NavigationRequest is created and stored in the map.
661 if (ongoing_navigation_request)
662 CancelNavigation(frame_tree_node);
664 scoped_ptr<NavigationRequest> navigation_request =
665 NavigationRequest::CreateRendererInitiated(
666 frame_tree_node, common_params, begin_params, body,
667 controller_->GetLastCommittedEntryIndex(),
668 controller_->GetEntryCount());
669 navigation_request_map_.set(
670 frame_tree_node->frame_tree_node_id(), navigation_request.Pass());
672 if (frame_tree_node->IsMainFrame())
673 navigation_data_.reset();
675 BeginNavigation(frame_tree_node);
678 // PlzNavigate
679 void NavigatorImpl::CommitNavigation(FrameTreeNode* frame_tree_node,
680 ResourceResponse* response,
681 scoped_ptr<StreamHandle> body) {
682 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
683 switches::kEnableBrowserSideNavigation));
685 NavigationRequest* navigation_request =
686 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
687 DCHECK(navigation_request);
688 DCHECK(response ||
689 !NavigationRequest::ShouldMakeNetworkRequest(
690 navigation_request->common_params().url));
692 // HTTP 204 (No Content) and HTTP 205 (Reset Content) responses should not
693 // commit; they leave the frame showing the previous page.
694 if (response && response->head.headers.get() &&
695 (response->head.headers->response_code() == 204 ||
696 response->head.headers->response_code() == 205)) {
697 CancelNavigation(frame_tree_node);
698 return;
701 // Select an appropriate renderer to commit the navigation.
702 RenderFrameHostImpl* render_frame_host =
703 frame_tree_node->render_manager()->GetFrameHostForNavigation(
704 *navigation_request);
706 // The renderer can exit view source mode when any error or cancellation
707 // happen. When reusing the same renderer, overwrite to recover the mode.
708 if (navigation_request->is_view_source() &&
709 render_frame_host ==
710 frame_tree_node->render_manager()->current_frame_host()) {
711 DCHECK(!render_frame_host->GetParent());
712 render_frame_host->render_view_host()->Send(
713 new ViewMsg_EnableViewSourceMode(
714 render_frame_host->render_view_host()->GetRoutingID()));
717 CheckWebUIRendererDoesNotDisplayNormalURL(
718 render_frame_host, navigation_request->common_params().url);
720 render_frame_host->CommitNavigation(response, body.Pass(),
721 navigation_request->common_params(),
722 navigation_request->request_params());
725 // PlzNavigate
726 void NavigatorImpl::CancelNavigation(FrameTreeNode* frame_tree_node) {
727 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
728 switches::kEnableBrowserSideNavigation));
729 navigation_request_map_.erase(frame_tree_node->frame_tree_node_id());
730 if (frame_tree_node->IsMainFrame())
731 navigation_data_.reset();
732 // TODO(carlosk): move this cleanup into the NavigationRequest destructor once
733 // we properly cancel ongoing navigations.
734 frame_tree_node->render_manager()->CleanUpNavigation();
737 // PlzNavigate
738 NavigationRequest* NavigatorImpl::GetNavigationRequestForNodeForTesting(
739 FrameTreeNode* frame_tree_node) {
740 return navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
743 bool NavigatorImpl::IsWaitingForBeforeUnloadACK(
744 FrameTreeNode* frame_tree_node) {
745 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
746 switches::kEnableBrowserSideNavigation));
747 NavigationRequest* request =
748 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
749 if (!request)
750 return false;
751 return request->state() == NavigationRequest::WAITING_FOR_RENDERER_RESPONSE;
754 void NavigatorImpl::LogResourceRequestTime(
755 base::TimeTicks timestamp, const GURL& url) {
756 if (navigation_data_ && navigation_data_->url_ == url) {
757 navigation_data_->url_job_start_time_ = timestamp;
758 UMA_HISTOGRAM_TIMES(
759 "Navigation.TimeToURLJobStart",
760 navigation_data_->url_job_start_time_ - navigation_data_->start_time_);
764 void NavigatorImpl::LogBeforeUnloadTime(
765 const base::TimeTicks& renderer_before_unload_start_time,
766 const base::TimeTicks& renderer_before_unload_end_time) {
767 // Only stores the beforeunload delay if we're tracking a browser initiated
768 // navigation and it happened later than the navigation request.
769 if (navigation_data_ &&
770 renderer_before_unload_start_time > navigation_data_->start_time_) {
771 navigation_data_->before_unload_delay_ =
772 renderer_before_unload_end_time - renderer_before_unload_start_time;
776 void NavigatorImpl::CheckWebUIRendererDoesNotDisplayNormalURL(
777 RenderFrameHostImpl* render_frame_host,
778 const GURL& url) {
779 int enabled_bindings =
780 render_frame_host->render_view_host()->GetEnabledBindings();
781 bool is_allowed_in_web_ui_renderer =
782 WebUIControllerFactoryRegistry::GetInstance()->IsURLAcceptableForWebUI(
783 controller_->GetBrowserContext(), url);
784 if ((enabled_bindings & BINDINGS_POLICY_WEB_UI) &&
785 !is_allowed_in_web_ui_renderer) {
786 // Log the URL to help us diagnose any future failures of this CHECK.
787 GetContentClient()->SetActiveURL(url);
788 CHECK(0);
792 // PlzNavigate
793 void NavigatorImpl::RequestNavigation(
794 FrameTreeNode* frame_tree_node,
795 const NavigationEntryImpl& entry,
796 NavigationController::ReloadType reload_type,
797 base::TimeTicks navigation_start) {
798 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
799 switches::kEnableBrowserSideNavigation));
800 DCHECK(frame_tree_node);
801 int64 frame_tree_node_id = frame_tree_node->frame_tree_node_id();
802 FrameMsg_Navigate_Type::Value navigation_type =
803 GetNavigationType(controller_->GetBrowserContext(), entry, reload_type);
804 scoped_ptr<NavigationRequest> navigation_request =
805 NavigationRequest::CreateBrowserInitiated(frame_tree_node, entry,
806 navigation_type,
807 navigation_start, controller_);
808 // TODO(clamy): Check if navigations are blocked and if so store the
809 // parameters.
811 // If there is an ongoing request, cancel and replace it.
812 NavigationRequest* ongoing_request =
813 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
814 if (ongoing_request)
815 CancelNavigation(frame_tree_node);
817 navigation_request_map_.set(frame_tree_node_id, navigation_request.Pass());
819 // Have the current renderer execute its beforeUnload event if needed. If it
820 // is not needed (eg. the renderer is not live), BeginNavigation should get
821 // called.
822 NavigationRequest* request_to_send =
823 navigation_request_map_.get(frame_tree_node_id);
824 request_to_send->SetWaitingForRendererResponse();
825 frame_tree_node->current_frame_host()->DispatchBeforeUnload(true);
828 void NavigatorImpl::BeginNavigation(FrameTreeNode* frame_tree_node) {
829 NavigationRequest* navigation_request =
830 navigation_request_map_.get(frame_tree_node->frame_tree_node_id());
832 // A browser-initiated navigation could have been cancelled while it was
833 // waiting for the BeforeUnload event to execute.
834 if (!navigation_request)
835 return;
837 // Start the request.
838 if (navigation_request->BeginNavigation()) {
839 // If the request was sent to the IO thread, notify the
840 // RenderFrameHostManager so it can speculatively create a RenderFrameHost
841 // (and potentially a new renderer process) in parallel.
842 frame_tree_node->render_manager()->BeginNavigation(*navigation_request);
846 void NavigatorImpl::RecordNavigationMetrics(
847 const LoadCommittedDetails& details,
848 const FrameHostMsg_DidCommitProvisionalLoad_Params& params,
849 SiteInstance* site_instance) {
850 DCHECK(site_instance->HasProcess());
852 if (!details.is_in_page)
853 RecordAction(base::UserMetricsAction("FrameLoad"));
855 if (!details.is_main_frame || !navigation_data_ ||
856 navigation_data_->url_job_start_time_.is_null() ||
857 navigation_data_->url_ != params.original_request_url) {
858 return;
861 base::TimeDelta time_to_commit =
862 base::TimeTicks::Now() - navigation_data_->start_time_;
863 UMA_HISTOGRAM_TIMES("Navigation.TimeToCommit", time_to_commit);
865 time_to_commit -= navigation_data_->before_unload_delay_;
866 base::TimeDelta time_to_network = navigation_data_->url_job_start_time_ -
867 navigation_data_->start_time_ -
868 navigation_data_->before_unload_delay_;
869 if (navigation_data_->is_restoring_from_last_session_) {
870 UMA_HISTOGRAM_TIMES(
871 "Navigation.TimeToCommit_SessionRestored_BeforeUnloadDiscounted",
872 time_to_commit);
873 UMA_HISTOGRAM_TIMES(
874 "Navigation.TimeToURLJobStart_SessionRestored_BeforeUnloadDiscounted",
875 time_to_network);
876 navigation_data_.reset();
877 return;
879 bool navigation_created_new_renderer_process =
880 site_instance->GetProcess()->GetInitTimeForNavigationMetrics() >
881 navigation_data_->start_time_;
882 if (navigation_created_new_renderer_process) {
883 UMA_HISTOGRAM_TIMES(
884 "Navigation.TimeToCommit_NewRenderer_BeforeUnloadDiscounted",
885 time_to_commit);
886 UMA_HISTOGRAM_TIMES(
887 "Navigation.TimeToURLJobStart_NewRenderer_BeforeUnloadDiscounted",
888 time_to_network);
889 } else {
890 UMA_HISTOGRAM_TIMES(
891 "Navigation.TimeToCommit_ExistingRenderer_BeforeUnloadDiscounted",
892 time_to_commit);
893 UMA_HISTOGRAM_TIMES(
894 "Navigation.TimeToURLJobStart_ExistingRenderer_BeforeUnloadDiscounted",
895 time_to_network);
897 navigation_data_.reset();
900 } // namespace content