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/navigation_controller_impl.h"
8 #include "base/command_line.h"
9 #include "base/logging.h"
10 #include "base/metrics/histogram.h"
11 #include "base/strings/string_number_conversions.h" // Temporary
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/time/time.h"
15 #include "base/trace_event/trace_event.h"
16 #include "cc/base/switches.h"
17 #include "content/browser/browser_url_handler_impl.h"
18 #include "content/browser/dom_storage/dom_storage_context_wrapper.h"
19 #include "content/browser/dom_storage/session_storage_namespace_impl.h"
20 #include "content/browser/frame_host/debug_urls.h"
21 #include "content/browser/frame_host/interstitial_page_impl.h"
22 #include "content/browser/frame_host/navigation_entry_impl.h"
23 #include "content/browser/frame_host/navigation_entry_screenshot_manager.h"
24 #include "content/browser/renderer_host/render_view_host_impl.h" // Temporary
25 #include "content/browser/site_instance_impl.h"
26 #include "content/common/frame_messages.h"
27 #include "content/common/view_messages.h"
28 #include "content/public/browser/browser_context.h"
29 #include "content/public/browser/content_browser_client.h"
30 #include "content/public/browser/invalidate_type.h"
31 #include "content/public/browser/navigation_details.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_types.h"
34 #include "content/public/browser/render_widget_host.h"
35 #include "content/public/browser/render_widget_host_view.h"
36 #include "content/public/browser/storage_partition.h"
37 #include "content/public/browser/user_metrics.h"
38 #include "content/public/common/content_client.h"
39 #include "content/public/common/content_constants.h"
40 #include "content/public/common/content_switches.h"
41 #include "net/base/escape.h"
42 #include "net/base/mime_util.h"
43 #include "net/base/net_util.h"
44 #include "skia/ext/platform_canvas.h"
45 #include "url/url_constants.h"
50 // Invoked when entries have been pruned, or removed. For example, if the
51 // current entries are [google, digg, yahoo], with the current entry google,
52 // and the user types in cnet, then digg and yahoo are pruned.
53 void NotifyPrunedEntries(NavigationControllerImpl
* nav_controller
,
56 PrunedDetails details
;
57 details
.from_front
= from_front
;
58 details
.count
= count
;
59 NotificationService::current()->Notify(
60 NOTIFICATION_NAV_LIST_PRUNED
,
61 Source
<NavigationController
>(nav_controller
),
62 Details
<PrunedDetails
>(&details
));
65 // Ensure the given NavigationEntry has a valid state, so that WebKit does not
66 // get confused if we navigate back to it.
68 // An empty state is treated as a new navigation by WebKit, which would mean
69 // losing the navigation entries and generating a new navigation entry after
70 // this one. We don't want that. To avoid this we create a valid state which
71 // WebKit will not treat as a new navigation.
72 void SetPageStateIfEmpty(NavigationEntryImpl
* entry
) {
73 if (!entry
->GetPageState().IsValid())
74 entry
->SetPageState(PageState::CreateFromURL(entry
->GetURL()));
77 NavigationEntryImpl::RestoreType
ControllerRestoreTypeToEntryType(
78 NavigationController::RestoreType type
) {
80 case NavigationController::RESTORE_CURRENT_SESSION
:
81 return NavigationEntryImpl::RESTORE_CURRENT_SESSION
;
82 case NavigationController::RESTORE_LAST_SESSION_EXITED_CLEANLY
:
83 return NavigationEntryImpl::RESTORE_LAST_SESSION_EXITED_CLEANLY
;
84 case NavigationController::RESTORE_LAST_SESSION_CRASHED
:
85 return NavigationEntryImpl::RESTORE_LAST_SESSION_CRASHED
;
88 return NavigationEntryImpl::RESTORE_CURRENT_SESSION
;
91 // Configure all the NavigationEntries in entries for restore. This resets
92 // the transition type to reload and makes sure the content state isn't empty.
93 void ConfigureEntriesForRestore(
94 std::vector
<linked_ptr
<NavigationEntryImpl
> >* entries
,
95 NavigationController::RestoreType type
) {
96 for (size_t i
= 0; i
< entries
->size(); ++i
) {
97 // Use a transition type of reload so that we don't incorrectly increase
99 (*entries
)[i
]->SetTransitionType(ui::PAGE_TRANSITION_RELOAD
);
100 (*entries
)[i
]->set_restore_type(ControllerRestoreTypeToEntryType(type
));
101 // NOTE(darin): This code is only needed for backwards compat.
102 SetPageStateIfEmpty((*entries
)[i
].get());
106 // There are two general cases where a navigation is in page:
107 // 1. A fragment navigation, in which the url is kept the same except for the
108 // reference fragment.
109 // 2. A history API navigation (pushState and replaceState). This case is
110 // always in-page, but the urls are not guaranteed to match excluding the
111 // fragment. The relevant spec allows pushState/replaceState to any URL on
113 // However, due to reloads, even identical urls are *not* guaranteed to be
114 // in-page navigations, we have to trust the renderer almost entirely.
115 // The one thing we do know is that cross-origin navigations will *never* be
116 // in-page. Therefore, trust the renderer if the URLs are on the same origin,
117 // and assume the renderer is malicious if a cross-origin navigation claims to
119 bool AreURLsInPageNavigation(const GURL
& existing_url
,
121 bool renderer_says_in_page
,
122 RenderFrameHost
* rfh
) {
123 WebPreferences prefs
= rfh
->GetRenderViewHost()->GetWebkitPreferences();
124 bool is_same_origin
= existing_url
.is_empty() ||
125 // TODO(japhet): We should only permit navigations
126 // originating from about:blank to be in-page if the
127 // about:blank is the first document that frame loaded.
128 // We don't have sufficient information to identify
129 // that case at the moment, so always allow about:blank
131 existing_url
== GURL(url::kAboutBlankURL
) ||
132 existing_url
.GetOrigin() == new_url
.GetOrigin() ||
133 !prefs
.web_security_enabled
||
134 (prefs
.allow_universal_access_from_file_urls
&&
135 existing_url
.SchemeIs(url::kFileScheme
));
136 if (!is_same_origin
&& renderer_says_in_page
)
137 rfh
->GetProcess()->ReceivedBadMessage();
138 return is_same_origin
&& renderer_says_in_page
;
141 // Determines whether or not we should be carrying over a user agent override
142 // between two NavigationEntries.
143 bool ShouldKeepOverride(const NavigationEntry
* last_entry
) {
144 return last_entry
&& last_entry
->GetIsOverridingUserAgent();
149 // NavigationControllerImpl ----------------------------------------------------
151 const size_t kMaxEntryCountForTestingNotSet
= static_cast<size_t>(-1);
154 size_t NavigationControllerImpl::max_entry_count_for_testing_
=
155 kMaxEntryCountForTestingNotSet
;
157 // Should Reload check for post data? The default is true, but is set to false
159 static bool g_check_for_repost
= true;
162 NavigationEntry
* NavigationController::CreateNavigationEntry(
164 const Referrer
& referrer
,
165 ui::PageTransition transition
,
166 bool is_renderer_initiated
,
167 const std::string
& extra_headers
,
168 BrowserContext
* browser_context
) {
169 // Fix up the given URL before letting it be rewritten, so that any minor
170 // cleanup (e.g., removing leading dots) will not lead to a virtual URL.
172 BrowserURLHandlerImpl::GetInstance()->FixupURLBeforeRewrite(&dest_url
,
175 // Allow the browser URL handler to rewrite the URL. This will, for example,
176 // remove "view-source:" from the beginning of the URL to get the URL that
177 // will actually be loaded. This real URL won't be shown to the user, just
179 GURL
loaded_url(dest_url
);
180 bool reverse_on_redirect
= false;
181 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
182 &loaded_url
, browser_context
, &reverse_on_redirect
);
184 NavigationEntryImpl
* entry
= new NavigationEntryImpl(
185 NULL
, // The site instance for tabs is sent on navigation
186 // (WebContents::GetSiteInstance).
192 is_renderer_initiated
);
193 entry
->SetVirtualURL(dest_url
);
194 entry
->set_user_typed_url(dest_url
);
195 entry
->set_update_virtual_url_with_url(reverse_on_redirect
);
196 entry
->set_extra_headers(extra_headers
);
201 void NavigationController::DisablePromptOnRepost() {
202 g_check_for_repost
= false;
205 base::Time
NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
207 // If |t| is between the water marks, we're in a run of duplicates
208 // or just getting out of it, so increase the high-water mark to get
209 // a time that probably hasn't been used before and return it.
210 if (low_water_mark_
<= t
&& t
<= high_water_mark_
) {
211 high_water_mark_
+= base::TimeDelta::FromMicroseconds(1);
212 return high_water_mark_
;
215 // Otherwise, we're clear of the last duplicate run, so reset the
217 low_water_mark_
= high_water_mark_
= t
;
221 NavigationControllerImpl::NavigationControllerImpl(
222 NavigationControllerDelegate
* delegate
,
223 BrowserContext
* browser_context
)
224 : browser_context_(browser_context
),
225 pending_entry_(NULL
),
226 last_committed_entry_index_(-1),
227 pending_entry_index_(-1),
228 transient_entry_index_(-1),
230 max_restored_page_id_(-1),
232 needs_reload_(false),
233 is_initial_navigation_(true),
234 in_navigate_to_pending_entry_(false),
235 pending_reload_(NO_RELOAD
),
236 get_timestamp_callback_(base::Bind(&base::Time::Now
)),
237 screenshot_manager_(new NavigationEntryScreenshotManager(this)) {
238 DCHECK(browser_context_
);
241 NavigationControllerImpl::~NavigationControllerImpl() {
242 DiscardNonCommittedEntriesInternal();
245 WebContents
* NavigationControllerImpl::GetWebContents() const {
246 return delegate_
->GetWebContents();
249 BrowserContext
* NavigationControllerImpl::GetBrowserContext() const {
250 return browser_context_
;
253 void NavigationControllerImpl::SetBrowserContext(
254 BrowserContext
* browser_context
) {
255 browser_context_
= browser_context
;
258 void NavigationControllerImpl::Restore(
259 int selected_navigation
,
261 std::vector
<NavigationEntry
*>* entries
) {
262 // Verify that this controller is unused and that the input is valid.
263 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
264 DCHECK(selected_navigation
>= 0 &&
265 selected_navigation
< static_cast<int>(entries
->size()));
267 needs_reload_
= true;
268 for (size_t i
= 0; i
< entries
->size(); ++i
) {
269 NavigationEntryImpl
* entry
=
270 NavigationEntryImpl::FromNavigationEntry((*entries
)[i
]);
271 entries_
.push_back(linked_ptr
<NavigationEntryImpl
>(entry
));
275 // And finish the restore.
276 FinishRestore(selected_navigation
, type
);
279 void NavigationControllerImpl::Reload(bool check_for_repost
) {
280 ReloadInternal(check_for_repost
, RELOAD
);
282 void NavigationControllerImpl::ReloadIgnoringCache(bool check_for_repost
) {
283 ReloadInternal(check_for_repost
, RELOAD_IGNORING_CACHE
);
285 void NavigationControllerImpl::ReloadOriginalRequestURL(bool check_for_repost
) {
286 ReloadInternal(check_for_repost
, RELOAD_ORIGINAL_REQUEST_URL
);
289 void NavigationControllerImpl::ReloadInternal(bool check_for_repost
,
290 ReloadType reload_type
) {
291 if (transient_entry_index_
!= -1) {
292 // If an interstitial is showing, treat a reload as a navigation to the
293 // transient entry's URL.
294 NavigationEntryImpl
* transient_entry
=
295 NavigationEntryImpl::FromNavigationEntry(GetTransientEntry());
296 if (!transient_entry
)
298 LoadURL(transient_entry
->GetURL(),
300 ui::PAGE_TRANSITION_RELOAD
,
301 transient_entry
->extra_headers());
305 NavigationEntryImpl
* entry
= NULL
;
306 int current_index
= -1;
308 // If we are reloading the initial navigation, just use the current
309 // pending entry. Otherwise look up the current entry.
310 if (IsInitialNavigation() && pending_entry_
) {
311 entry
= pending_entry_
;
312 // The pending entry might be in entries_ (e.g., after a Clone), so we
313 // should also update the current_index.
314 current_index
= pending_entry_index_
;
316 DiscardNonCommittedEntriesInternal();
317 current_index
= GetCurrentEntryIndex();
318 if (current_index
!= -1) {
319 entry
= NavigationEntryImpl::FromNavigationEntry(
320 GetEntryAtIndex(current_index
));
324 // If we are no where, then we can't reload. TODO(darin): We should add a
329 if (reload_type
== NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL
&&
330 entry
->GetOriginalRequestURL().is_valid() && !entry
->GetHasPostData()) {
331 // We may have been redirected when navigating to the current URL.
332 // Use the URL the user originally intended to visit, if it's valid and if a
333 // POST wasn't involved; the latter case avoids issues with sending data to
335 entry
->SetURL(entry
->GetOriginalRequestURL());
336 entry
->SetReferrer(Referrer());
339 if (g_check_for_repost
&& check_for_repost
&&
340 entry
->GetHasPostData()) {
341 // The user is asking to reload a page with POST data. Prompt to make sure
342 // they really want to do this. If they do, the dialog will call us back
343 // with check_for_repost = false.
344 delegate_
->NotifyBeforeFormRepostWarningShow();
346 pending_reload_
= reload_type
;
347 delegate_
->ActivateAndShowRepostFormWarningDialog();
349 if (!IsInitialNavigation())
350 DiscardNonCommittedEntriesInternal();
352 // If we are reloading an entry that no longer belongs to the current
353 // site instance (for example, refreshing a page for just installed app),
354 // the reload must happen in a new process.
355 // The new entry must have a new page_id and site instance, so it behaves
356 // as new navigation (which happens to clear forward history).
357 // Tabs that are discarded due to low memory conditions may not have a site
358 // instance, and should not be treated as a cross-site reload.
359 SiteInstanceImpl
* site_instance
= entry
->site_instance();
360 // Permit reloading guests without further checks.
361 bool is_isolated_guest
= site_instance
&& site_instance
->HasProcess() &&
362 site_instance
->GetProcess()->IsIsolatedGuest();
363 if (!is_isolated_guest
&& site_instance
&&
364 site_instance
->HasWrongProcessForURL(entry
->GetURL())) {
365 // Create a navigation entry that resembles the current one, but do not
366 // copy page id, site instance, content state, or timestamp.
367 NavigationEntryImpl
* nav_entry
= NavigationEntryImpl::FromNavigationEntry(
368 CreateNavigationEntry(
369 entry
->GetURL(), entry
->GetReferrer(), entry
->GetTransitionType(),
370 false, entry
->extra_headers(), browser_context_
));
372 // Mark the reload type as NO_RELOAD, so navigation will not be considered
373 // a reload in the renderer.
374 reload_type
= NavigationController::NO_RELOAD
;
376 nav_entry
->set_should_replace_entry(true);
377 pending_entry_
= nav_entry
;
379 pending_entry_
= entry
;
380 pending_entry_index_
= current_index
;
382 // The title of the page being reloaded might have been removed in the
383 // meanwhile, so we need to revert to the default title upon reload and
384 // invalidate the previously cached title (SetTitle will do both).
385 // See Chromium issue 96041.
386 pending_entry_
->SetTitle(base::string16());
388 pending_entry_
->SetTransitionType(ui::PAGE_TRANSITION_RELOAD
);
391 NavigateToPendingEntry(reload_type
);
395 void NavigationControllerImpl::CancelPendingReload() {
396 DCHECK(pending_reload_
!= NO_RELOAD
);
397 pending_reload_
= NO_RELOAD
;
400 void NavigationControllerImpl::ContinuePendingReload() {
401 if (pending_reload_
== NO_RELOAD
) {
404 ReloadInternal(false, pending_reload_
);
405 pending_reload_
= NO_RELOAD
;
409 bool NavigationControllerImpl::IsInitialNavigation() const {
410 return is_initial_navigation_
;
413 NavigationEntryImpl
* NavigationControllerImpl::GetEntryWithPageID(
414 SiteInstance
* instance
, int32 page_id
) const {
415 int index
= GetEntryIndexWithPageID(instance
, page_id
);
416 return (index
!= -1) ? entries_
[index
].get() : NULL
;
419 void NavigationControllerImpl::LoadEntry(NavigationEntryImpl
* entry
) {
420 // When navigating to a new page, we don't know for sure if we will actually
421 // end up leaving the current page. The new page load could for example
422 // result in a download or a 'no content' response (e.g., a mailto: URL).
423 SetPendingEntry(entry
);
424 NavigateToPendingEntry(NO_RELOAD
);
427 void NavigationControllerImpl::SetPendingEntry(NavigationEntryImpl
* entry
) {
428 DiscardNonCommittedEntriesInternal();
429 pending_entry_
= entry
;
430 NotificationService::current()->Notify(
431 NOTIFICATION_NAV_ENTRY_PENDING
,
432 Source
<NavigationController
>(this),
433 Details
<NavigationEntry
>(entry
));
436 NavigationEntry
* NavigationControllerImpl::GetActiveEntry() const {
437 if (transient_entry_index_
!= -1)
438 return entries_
[transient_entry_index_
].get();
440 return pending_entry_
;
441 return GetLastCommittedEntry();
444 NavigationEntry
* NavigationControllerImpl::GetVisibleEntry() const {
445 if (transient_entry_index_
!= -1)
446 return entries_
[transient_entry_index_
].get();
447 // The pending entry is safe to return for new (non-history), browser-
448 // initiated navigations. Most renderer-initiated navigations should not
449 // show the pending entry, to prevent URL spoof attacks.
451 // We make an exception for renderer-initiated navigations in new tabs, as
452 // long as no other page has tried to access the initial empty document in
453 // the new tab. If another page modifies this blank page, a URL spoof is
454 // possible, so we must stop showing the pending entry.
455 bool safe_to_show_pending
=
457 // Require a new navigation.
458 pending_entry_index_
== -1 &&
459 // Require either browser-initiated or an unmodified new tab.
460 (!pending_entry_
->is_renderer_initiated() || IsUnmodifiedBlankTab());
462 // Also allow showing the pending entry for history navigations in a new tab,
463 // such as Ctrl+Back. In this case, no existing page is visible and no one
464 // can script the new tab before it commits.
465 if (!safe_to_show_pending
&&
467 pending_entry_index_
!= -1 &&
468 IsInitialNavigation() &&
469 !pending_entry_
->is_renderer_initiated())
470 safe_to_show_pending
= true;
472 if (safe_to_show_pending
)
473 return pending_entry_
;
474 return GetLastCommittedEntry();
477 int NavigationControllerImpl::GetCurrentEntryIndex() const {
478 if (transient_entry_index_
!= -1)
479 return transient_entry_index_
;
480 if (pending_entry_index_
!= -1)
481 return pending_entry_index_
;
482 return last_committed_entry_index_
;
485 NavigationEntry
* NavigationControllerImpl::GetLastCommittedEntry() const {
486 if (last_committed_entry_index_
== -1)
488 return entries_
[last_committed_entry_index_
].get();
491 bool NavigationControllerImpl::CanViewSource() const {
492 const std::string
& mime_type
= delegate_
->GetContentsMimeType();
493 bool is_viewable_mime_type
= net::IsSupportedNonImageMimeType(mime_type
) &&
494 !net::IsSupportedMediaMimeType(mime_type
);
495 NavigationEntry
* visible_entry
= GetVisibleEntry();
496 return visible_entry
&& !visible_entry
->IsViewSourceMode() &&
497 is_viewable_mime_type
&& !delegate_
->GetInterstitialPage();
500 int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
501 return last_committed_entry_index_
;
504 int NavigationControllerImpl::GetEntryCount() const {
505 DCHECK(entries_
.size() <= max_entry_count());
506 return static_cast<int>(entries_
.size());
509 NavigationEntry
* NavigationControllerImpl::GetEntryAtIndex(
511 return entries_
.at(index
).get();
514 NavigationEntry
* NavigationControllerImpl::GetEntryAtOffset(
516 int index
= GetIndexForOffset(offset
);
517 if (index
< 0 || index
>= GetEntryCount())
520 return entries_
[index
].get();
523 int NavigationControllerImpl::GetIndexForOffset(int offset
) const {
524 return GetCurrentEntryIndex() + offset
;
527 void NavigationControllerImpl::TakeScreenshot() {
528 screenshot_manager_
->TakeScreenshot();
531 void NavigationControllerImpl::SetScreenshotManager(
532 NavigationEntryScreenshotManager
* manager
) {
533 screenshot_manager_
.reset(manager
? manager
:
534 new NavigationEntryScreenshotManager(this));
537 bool NavigationControllerImpl::CanGoBack() const {
538 return entries_
.size() > 1 && GetCurrentEntryIndex() > 0;
541 bool NavigationControllerImpl::CanGoForward() const {
542 int index
= GetCurrentEntryIndex();
543 return index
>= 0 && index
< (static_cast<int>(entries_
.size()) - 1);
546 bool NavigationControllerImpl::CanGoToOffset(int offset
) const {
547 int index
= GetIndexForOffset(offset
);
548 return index
>= 0 && index
< GetEntryCount();
551 void NavigationControllerImpl::GoBack() {
557 // Base the navigation on where we are now...
558 int current_index
= GetCurrentEntryIndex();
560 DiscardNonCommittedEntries();
562 pending_entry_index_
= current_index
- 1;
563 entries_
[pending_entry_index_
]->SetTransitionType(
564 ui::PageTransitionFromInt(
565 entries_
[pending_entry_index_
]->GetTransitionType() |
566 ui::PAGE_TRANSITION_FORWARD_BACK
));
567 NavigateToPendingEntry(NO_RELOAD
);
570 void NavigationControllerImpl::GoForward() {
571 if (!CanGoForward()) {
576 bool transient
= (transient_entry_index_
!= -1);
578 // Base the navigation on where we are now...
579 int current_index
= GetCurrentEntryIndex();
581 DiscardNonCommittedEntries();
583 pending_entry_index_
= current_index
;
584 // If there was a transient entry, we removed it making the current index
587 pending_entry_index_
++;
589 entries_
[pending_entry_index_
]->SetTransitionType(
590 ui::PageTransitionFromInt(
591 entries_
[pending_entry_index_
]->GetTransitionType() |
592 ui::PAGE_TRANSITION_FORWARD_BACK
));
593 NavigateToPendingEntry(NO_RELOAD
);
596 void NavigationControllerImpl::GoToIndex(int index
) {
597 if (index
< 0 || index
>= static_cast<int>(entries_
.size())) {
602 if (transient_entry_index_
!= -1) {
603 if (index
== transient_entry_index_
) {
604 // Nothing to do when navigating to the transient.
607 if (index
> transient_entry_index_
) {
608 // Removing the transient is goint to shift all entries by 1.
613 DiscardNonCommittedEntries();
615 pending_entry_index_
= index
;
616 entries_
[pending_entry_index_
]->SetTransitionType(
617 ui::PageTransitionFromInt(
618 entries_
[pending_entry_index_
]->GetTransitionType() |
619 ui::PAGE_TRANSITION_FORWARD_BACK
));
620 NavigateToPendingEntry(NO_RELOAD
);
623 void NavigationControllerImpl::GoToOffset(int offset
) {
624 if (!CanGoToOffset(offset
))
627 GoToIndex(GetIndexForOffset(offset
));
630 bool NavigationControllerImpl::RemoveEntryAtIndex(int index
) {
631 if (index
== last_committed_entry_index_
||
632 index
== pending_entry_index_
)
635 RemoveEntryAtIndexInternal(index
);
639 void NavigationControllerImpl::UpdateVirtualURLToURL(
640 NavigationEntryImpl
* entry
, const GURL
& new_url
) {
641 GURL
new_virtual_url(new_url
);
642 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
643 &new_virtual_url
, entry
->GetVirtualURL(), browser_context_
)) {
644 entry
->SetVirtualURL(new_virtual_url
);
648 void NavigationControllerImpl::LoadURL(
650 const Referrer
& referrer
,
651 ui::PageTransition transition
,
652 const std::string
& extra_headers
) {
653 LoadURLParams
params(url
);
654 params
.referrer
= referrer
;
655 params
.transition_type
= transition
;
656 params
.extra_headers
= extra_headers
;
657 LoadURLWithParams(params
);
660 void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams
& params
) {
661 TRACE_EVENT1("browser,navigation",
662 "NavigationControllerImpl::LoadURLWithParams",
663 "url", params
.url
.possibly_invalid_spec());
664 if (HandleDebugURL(params
.url
, params
.transition_type
)) {
665 // If Telemetry is running, allow the URL load to proceed as if it's
666 // unhandled, otherwise Telemetry can't tell if Navigation completed.
667 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
668 cc::switches::kEnableGpuBenchmarking
))
672 // Any renderer-side debug URLs or javascript: URLs should be ignored if the
673 // renderer process is not live, unless it is the initial navigation of the
675 if (IsRendererDebugURL(params
.url
)) {
676 // TODO(creis): Find the RVH for the correct frame.
677 if (!delegate_
->GetRenderViewHost()->IsRenderViewLive() &&
678 !IsInitialNavigation())
682 // Checks based on params.load_type.
683 switch (params
.load_type
) {
684 case LOAD_TYPE_DEFAULT
:
686 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST
:
687 if (!params
.url
.SchemeIs(url::kHttpScheme
) &&
688 !params
.url
.SchemeIs(url::kHttpsScheme
)) {
689 NOTREACHED() << "Http post load must use http(s) scheme.";
694 if (!params
.url
.SchemeIs(url::kDataScheme
)) {
695 NOTREACHED() << "Data load must use data scheme.";
704 // The user initiated a load, we don't need to reload anymore.
705 needs_reload_
= false;
707 bool override
= false;
708 switch (params
.override_user_agent
) {
709 case UA_OVERRIDE_INHERIT
:
710 override
= ShouldKeepOverride(GetLastCommittedEntry());
712 case UA_OVERRIDE_TRUE
:
715 case UA_OVERRIDE_FALSE
:
723 NavigationEntryImpl
* entry
= NavigationEntryImpl::FromNavigationEntry(
724 CreateNavigationEntry(
727 params
.transition_type
,
728 params
.is_renderer_initiated
,
729 params
.extra_headers
,
731 if (params
.frame_tree_node_id
!= -1)
732 entry
->set_frame_tree_node_id(params
.frame_tree_node_id
);
733 entry
->set_source_site_instance(
734 static_cast<SiteInstanceImpl
*>(params
.source_site_instance
.get()));
735 if (params
.redirect_chain
.size() > 0)
736 entry
->SetRedirectChain(params
.redirect_chain
);
737 // Don't allow an entry replacement if there is no entry to replace.
738 // http://crbug.com/457149
739 if (params
.should_replace_current_entry
&& entries_
.size() > 0)
740 entry
->set_should_replace_entry(true);
741 entry
->set_should_clear_history_list(params
.should_clear_history_list
);
742 entry
->SetIsOverridingUserAgent(override
);
743 entry
->set_transferred_global_request_id(
744 params
.transferred_global_request_id
);
745 entry
->SetFrameToNavigate(params
.frame_name
);
747 #if defined(OS_ANDROID)
748 if (params
.intent_received_timestamp
> 0) {
749 entry
->set_intent_received_timestamp(
751 base::TimeDelta::FromMilliseconds(params
.intent_received_timestamp
));
755 switch (params
.load_type
) {
756 case LOAD_TYPE_DEFAULT
:
758 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST
:
759 entry
->SetHasPostData(true);
760 entry
->SetBrowserInitiatedPostData(
761 params
.browser_initiated_post_data
.get());
764 entry
->SetBaseURLForDataURL(params
.base_url_for_data_url
);
765 entry
->SetVirtualURL(params
.virtual_url_for_data_url
);
766 entry
->SetCanLoadLocalResources(params
.can_load_local_resources
);
776 bool NavigationControllerImpl::RendererDidNavigate(
777 RenderFrameHost
* rfh
,
778 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
,
779 LoadCommittedDetails
* details
) {
780 is_initial_navigation_
= false;
782 // Save the previous state before we clobber it.
783 if (GetLastCommittedEntry()) {
784 details
->previous_url
= GetLastCommittedEntry()->GetURL();
785 details
->previous_entry_index
= GetLastCommittedEntryIndex();
787 details
->previous_url
= GURL();
788 details
->previous_entry_index
= -1;
791 // If we have a pending entry at this point, it should have a SiteInstance.
792 // Restored entries start out with a null SiteInstance, but we should have
793 // assigned one in NavigateToPendingEntry.
794 DCHECK(pending_entry_index_
== -1 || pending_entry_
->site_instance());
796 // If we are doing a cross-site reload, we need to replace the existing
797 // navigation entry, not add another entry to the history. This has the side
798 // effect of removing forward browsing history, if such existed.
799 // Or if we are doing a cross-site redirect navigation,
800 // we will do a similar thing.
801 details
->did_replace_entry
=
802 pending_entry_
&& pending_entry_
->should_replace_entry();
804 // Do navigation-type specific actions. These will make and commit an entry.
805 details
->type
= ClassifyNavigation(rfh
, params
);
807 // is_in_page must be computed before the entry gets committed.
808 details
->is_in_page
= AreURLsInPageNavigation(rfh
->GetLastCommittedURL(),
809 params
.url
, params
.was_within_same_page
, rfh
);
811 switch (details
->type
) {
812 case NAVIGATION_TYPE_NEW_PAGE
:
813 RendererDidNavigateToNewPage(rfh
, params
, details
->did_replace_entry
);
815 case NAVIGATION_TYPE_EXISTING_PAGE
:
816 RendererDidNavigateToExistingPage(rfh
, params
);
818 case NAVIGATION_TYPE_SAME_PAGE
:
819 RendererDidNavigateToSamePage(rfh
, params
);
821 case NAVIGATION_TYPE_IN_PAGE
:
822 RendererDidNavigateInPage(rfh
, params
, &details
->did_replace_entry
);
824 case NAVIGATION_TYPE_NEW_SUBFRAME
:
825 RendererDidNavigateNewSubframe(rfh
, params
);
827 case NAVIGATION_TYPE_AUTO_SUBFRAME
:
828 if (!RendererDidNavigateAutoSubframe(rfh
, params
))
831 case NAVIGATION_TYPE_NAV_IGNORE
:
832 // If a pending navigation was in progress, this canceled it. We should
833 // discard it and make sure it is removed from the URL bar. After that,
834 // there is nothing we can do with this navigation, so we just return to
835 // the caller that nothing has happened.
836 if (pending_entry_
) {
837 DiscardNonCommittedEntries();
838 delegate_
->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
845 // At this point, we know that the navigation has just completed, so
848 // TODO(akalin): Use "sane time" as described in
849 // http://www.chromium.org/developers/design-documents/sane-time .
850 base::Time timestamp
=
851 time_smoother_
.GetSmoothedTime(get_timestamp_callback_
.Run());
852 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
853 << timestamp
.ToInternalValue();
855 // We should not have a pending entry anymore. Clear it again in case any
856 // error cases above forgot to do so.
857 DiscardNonCommittedEntriesInternal();
859 // All committed entries should have nonempty content state so WebKit doesn't
860 // get confused when we go back to them (see the function for details).
861 DCHECK(params
.page_state
.IsValid());
862 NavigationEntryImpl
* active_entry
=
863 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
864 active_entry
->SetTimestamp(timestamp
);
865 active_entry
->SetHttpStatusCode(params
.http_status_code
);
866 active_entry
->SetPageState(params
.page_state
);
867 active_entry
->SetRedirectChain(params
.redirects
);
869 // Use histogram to track memory impact of redirect chain because it's now
870 // not cleared for committed entries.
871 size_t redirect_chain_size
= 0;
872 for (size_t i
= 0; i
< params
.redirects
.size(); ++i
) {
873 redirect_chain_size
+= params
.redirects
[i
].spec().length();
875 UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size
);
877 // Once it is committed, we no longer need to track several pieces of state on
879 active_entry
->ResetForCommit();
881 // The active entry's SiteInstance should match our SiteInstance.
882 // TODO(creis): This check won't pass for subframes until we create entries
883 // for subframe navigations.
884 if (ui::PageTransitionIsMainFrame(params
.transition
))
885 CHECK(active_entry
->site_instance() == rfh
->GetSiteInstance());
887 // Remember the bindings the renderer process has at this point, so that
888 // we do not grant this entry additional bindings if we come back to it.
889 active_entry
->SetBindings(
890 static_cast<RenderFrameHostImpl
*>(rfh
)->GetEnabledBindings());
892 // Now prep the rest of the details for the notification and broadcast.
893 details
->entry
= active_entry
;
894 details
->is_main_frame
=
895 ui::PageTransitionIsMainFrame(params
.transition
);
896 details
->serialized_security_info
= params
.security_info
;
897 details
->http_status_code
= params
.http_status_code
;
898 NotifyNavigationEntryCommitted(details
);
903 NavigationType
NavigationControllerImpl::ClassifyNavigation(
904 RenderFrameHost
* rfh
,
905 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) const {
906 if (params
.page_id
== -1) {
907 // TODO(nasko, creis): An out-of-process child frame has no way of
908 // knowing the page_id of its parent, so it is passing back -1. The
909 // semantics here should be re-evaluated during session history refactor
910 // (see http://crbug.com/236848). For now, we assume this means the
911 // child frame loaded and proceed. Note that this may do the wrong thing
912 // for cross-process AUTO_SUBFRAME navigations.
913 if (rfh
->IsCrossProcessSubframe())
914 return NAVIGATION_TYPE_NEW_SUBFRAME
;
916 // The renderer generates the page IDs, and so if it gives us the invalid
917 // page ID (-1) we know it didn't actually navigate. This happens in a few
920 // - If a page makes a popup navigated to about blank, and then writes
921 // stuff like a subframe navigated to a real page. We'll get the commit
922 // for the subframe, but there won't be any commit for the outer page.
924 // - We were also getting these for failed loads (for example, bug 21849).
925 // The guess is that we get a "load commit" for the alternate error page,
926 // but that doesn't affect the page ID, so we get the "old" one, which
927 // could be invalid. This can also happen for a cross-site transition
928 // that causes us to swap processes. Then the error page load will be in
929 // a new process with no page IDs ever assigned (and hence a -1 value),
930 // yet the navigation controller still might have previous pages in its
933 // In these cases, there's nothing we can do with them, so ignore.
934 return NAVIGATION_TYPE_NAV_IGNORE
;
937 if (params
.page_id
> delegate_
->GetMaxPageIDForSiteInstance(
938 rfh
->GetSiteInstance())) {
939 // Greater page IDs than we've ever seen before are new pages. We may or may
940 // not have a pending entry for the page, and this may or may not be the
942 if (ui::PageTransitionIsMainFrame(params
.transition
))
943 return NAVIGATION_TYPE_NEW_PAGE
;
945 // When this is a new subframe navigation, we should have a committed page
946 // for which it's a suframe in. This may not be the case when an iframe is
947 // navigated on a popup navigated to about:blank (the iframe would be
948 // written into the popup by script on the main page). For these cases,
949 // there isn't any navigation stuff we can do, so just ignore it.
950 if (!GetLastCommittedEntry())
951 return NAVIGATION_TYPE_NAV_IGNORE
;
953 // Valid subframe navigation.
954 return NAVIGATION_TYPE_NEW_SUBFRAME
;
957 // We only clear the session history when navigating to a new page.
958 DCHECK(!params
.history_list_was_cleared
);
960 // Now we know that the notification is for an existing page. Find that entry.
961 int existing_entry_index
= GetEntryIndexWithPageID(
962 rfh
->GetSiteInstance(),
964 if (existing_entry_index
== -1) {
965 // The page was not found. It could have been pruned because of the limit on
966 // back/forward entries (not likely since we'll usually tell it to navigate
967 // to such entries). It could also mean that the renderer is smoking crack.
970 // Because the unknown entry has committed, we risk showing the wrong URL in
971 // release builds. Instead, we'll kill the renderer process to be safe.
972 LOG(ERROR
) << "terminating renderer for bad navigation: " << params
.url
;
973 RecordAction(base::UserMetricsAction("BadMessageTerminate_NC"));
975 // Temporary code so we can get more information. Format:
976 // http://url/foo.html#page1#max3#frame1#ids:2_Nx,1_1x,3_2
977 std::string temp
= params
.url
.spec();
978 temp
.append("#page");
979 temp
.append(base::IntToString(params
.page_id
));
981 temp
.append(base::IntToString(delegate_
->GetMaxPageID()));
982 temp
.append("#frame");
983 temp
.append(base::IntToString(rfh
->GetRoutingID()));
985 for (int i
= 0; i
< static_cast<int>(entries_
.size()); ++i
) {
986 // Append entry metadata (e.g., 3_7x):
988 // 7: SiteInstance ID, or N for null
989 // x: appended if not from the current SiteInstance
990 temp
.append(base::IntToString(entries_
[i
]->GetPageID()));
992 if (entries_
[i
]->site_instance())
993 temp
.append(base::IntToString(entries_
[i
]->site_instance()->GetId()));
996 if (entries_
[i
]->site_instance() != rfh
->GetSiteInstance())
1001 static_cast<RenderFrameHostImpl
*>(rfh
)->render_view_host()->Send(
1002 new ViewMsg_TempCrashWithData(url
));
1003 return NAVIGATION_TYPE_NAV_IGNORE
;
1005 NavigationEntryImpl
* existing_entry
= entries_
[existing_entry_index
].get();
1007 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
1008 // All manual subframes would get new IDs and were handled above, so we
1009 // know this is auto. Since the current page was found in the navigation
1010 // entry list, we're guaranteed to have a last committed entry.
1011 DCHECK(GetLastCommittedEntry());
1012 return NAVIGATION_TYPE_AUTO_SUBFRAME
;
1015 // Anything below here we know is a main frame navigation.
1016 if (pending_entry_
&&
1017 !pending_entry_
->is_renderer_initiated() &&
1018 existing_entry
!= pending_entry_
&&
1019 pending_entry_
->GetPageID() == -1 &&
1020 existing_entry
== GetLastCommittedEntry()) {
1021 // In this case, we have a pending entry for a URL but WebCore didn't do a
1022 // new navigation. This happens when you press enter in the URL bar to
1023 // reload. We will create a pending entry, but WebKit will convert it to
1024 // a reload since it's the same page and not create a new entry for it
1025 // (the user doesn't want to have a new back/forward entry when they do
1026 // this). If this matches the last committed entry, we want to just ignore
1027 // the pending entry and go back to where we were (the "existing entry").
1028 return NAVIGATION_TYPE_SAME_PAGE
;
1031 // Any toplevel navigations with the same base (minus the reference fragment)
1032 // are in-page navigations. We weeded out subframe navigations above. Most of
1033 // the time this doesn't matter since WebKit doesn't tell us about subframe
1034 // navigations that don't actually navigate, but it can happen when there is
1035 // an encoding override (it always sends a navigation request).
1036 if (AreURLsInPageNavigation(existing_entry
->GetURL(), params
.url
,
1037 params
.was_within_same_page
, rfh
)) {
1038 return NAVIGATION_TYPE_IN_PAGE
;
1041 // Since we weeded out "new" navigations above, we know this is an existing
1042 // (back/forward) navigation.
1043 return NAVIGATION_TYPE_EXISTING_PAGE
;
1046 void NavigationControllerImpl::RendererDidNavigateToNewPage(
1047 RenderFrameHost
* rfh
,
1048 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
,
1049 bool replace_entry
) {
1050 NavigationEntryImpl
* new_entry
;
1051 bool update_virtual_url
;
1052 // Only make a copy of the pending entry if it is appropriate for the new page
1053 // that was just loaded. We verify this at a coarse grain by checking that
1054 // the SiteInstance hasn't been assigned to something else.
1055 if (pending_entry_
&&
1056 (!pending_entry_
->site_instance() ||
1057 pending_entry_
->site_instance() == rfh
->GetSiteInstance())) {
1058 new_entry
= new NavigationEntryImpl(*pending_entry_
);
1060 update_virtual_url
= new_entry
->update_virtual_url_with_url();
1062 new_entry
= new NavigationEntryImpl
;
1064 // Find out whether the new entry needs to update its virtual URL on URL
1065 // change and set up the entry accordingly. This is needed to correctly
1066 // update the virtual URL when replaceState is called after a pushState.
1067 GURL url
= params
.url
;
1068 bool needs_update
= false;
1069 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1070 &url
, browser_context_
, &needs_update
);
1071 new_entry
->set_update_virtual_url_with_url(needs_update
);
1073 // When navigating to a new page, give the browser URL handler a chance to
1074 // update the virtual URL based on the new URL. For example, this is needed
1075 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1077 update_virtual_url
= needs_update
;
1080 // Don't use the page type from the pending entry. Some interstitial page
1081 // may have set the type to interstitial. Once we commit, however, the page
1082 // type must always be normal or error.
1083 new_entry
->set_page_type(params
.url_is_unreachable
? PAGE_TYPE_ERROR
1084 : PAGE_TYPE_NORMAL
);
1085 new_entry
->SetURL(params
.url
);
1086 if (update_virtual_url
)
1087 UpdateVirtualURLToURL(new_entry
, params
.url
);
1088 new_entry
->SetReferrer(params
.referrer
);
1089 new_entry
->SetPageID(params
.page_id
);
1090 new_entry
->SetTransitionType(params
.transition
);
1091 new_entry
->set_site_instance(
1092 static_cast<SiteInstanceImpl
*>(rfh
->GetSiteInstance()));
1093 new_entry
->SetHasPostData(params
.is_post
);
1094 new_entry
->SetPostID(params
.post_id
);
1095 new_entry
->SetOriginalRequestURL(params
.original_request_url
);
1096 new_entry
->SetIsOverridingUserAgent(params
.is_overriding_user_agent
);
1098 // history.pushState() is classified as a navigation to a new page, but
1099 // sets was_within_same_page to true. In this case, we already have the
1100 // title and favicon available, so set them immediately.
1101 if (params
.was_within_same_page
&& GetLastCommittedEntry()) {
1102 new_entry
->SetTitle(GetLastCommittedEntry()->GetTitle());
1103 new_entry
->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
1106 DCHECK(!params
.history_list_was_cleared
|| !replace_entry
);
1107 // The browser requested to clear the session history when it initiated the
1108 // navigation. Now we know that the renderer has updated its state accordingly
1109 // and it is safe to also clear the browser side history.
1110 if (params
.history_list_was_cleared
) {
1111 DiscardNonCommittedEntriesInternal();
1113 last_committed_entry_index_
= -1;
1116 InsertOrReplaceEntry(new_entry
, replace_entry
);
1119 void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1120 RenderFrameHost
* rfh
,
1121 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
1122 // We should only get here for main frame navigations.
1123 DCHECK(ui::PageTransitionIsMainFrame(params
.transition
));
1125 // This is a back/forward navigation. The existing page for the ID is
1126 // guaranteed to exist by ClassifyNavigation, and we just need to update it
1127 // with new information from the renderer.
1128 int entry_index
= GetEntryIndexWithPageID(rfh
->GetSiteInstance(),
1130 DCHECK(entry_index
>= 0 &&
1131 entry_index
< static_cast<int>(entries_
.size()));
1132 NavigationEntryImpl
* entry
= entries_
[entry_index
].get();
1134 // The URL may have changed due to redirects.
1135 entry
->set_page_type(params
.url_is_unreachable
? PAGE_TYPE_ERROR
1136 : PAGE_TYPE_NORMAL
);
1137 entry
->SetURL(params
.url
);
1138 entry
->SetReferrer(params
.referrer
);
1139 if (entry
->update_virtual_url_with_url())
1140 UpdateVirtualURLToURL(entry
, params
.url
);
1142 // The redirected to page should not inherit the favicon from the previous
1144 if (ui::PageTransitionIsRedirect(params
.transition
))
1145 entry
->GetFavicon() = FaviconStatus();
1147 // The site instance will normally be the same except during session restore,
1148 // when no site instance will be assigned.
1149 DCHECK(entry
->site_instance() == NULL
||
1150 entry
->site_instance() == rfh
->GetSiteInstance());
1151 entry
->set_site_instance(
1152 static_cast<SiteInstanceImpl
*>(rfh
->GetSiteInstance()));
1154 entry
->SetHasPostData(params
.is_post
);
1155 entry
->SetPostID(params
.post_id
);
1157 // The entry we found in the list might be pending if the user hit
1158 // back/forward/reload. This load should commit it (since it's already in the
1159 // list, we can just discard the pending pointer). We should also discard the
1160 // pending entry if it corresponds to a different navigation, since that one
1161 // is now likely canceled. If it is not canceled, we will treat it as a new
1162 // navigation when it arrives, which is also ok.
1164 // Note that we need to use the "internal" version since we don't want to
1165 // actually change any other state, just kill the pointer.
1166 DiscardNonCommittedEntriesInternal();
1168 // If a transient entry was removed, the indices might have changed, so we
1169 // have to query the entry index again.
1170 last_committed_entry_index_
=
1171 GetEntryIndexWithPageID(rfh
->GetSiteInstance(), params
.page_id
);
1174 void NavigationControllerImpl::RendererDidNavigateToSamePage(
1175 RenderFrameHost
* rfh
,
1176 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
1177 // This mode implies we have a pending entry that's the same as an existing
1178 // entry for this page ID. This entry is guaranteed to exist by
1179 // ClassifyNavigation. All we need to do is update the existing entry.
1180 NavigationEntryImpl
* existing_entry
= GetEntryWithPageID(
1181 rfh
->GetSiteInstance(), params
.page_id
);
1183 // We assign the entry's unique ID to be that of the new one. Since this is
1184 // always the result of a user action, we want to dismiss infobars, etc. like
1185 // a regular user-initiated navigation.
1186 existing_entry
->set_unique_id(pending_entry_
->GetUniqueID());
1188 // The URL may have changed due to redirects.
1189 existing_entry
->set_page_type(params
.url_is_unreachable
? PAGE_TYPE_ERROR
1190 : PAGE_TYPE_NORMAL
);
1191 if (existing_entry
->update_virtual_url_with_url())
1192 UpdateVirtualURLToURL(existing_entry
, params
.url
);
1193 existing_entry
->SetURL(params
.url
);
1194 existing_entry
->SetReferrer(params
.referrer
);
1196 // The page may have been requested with a different HTTP method.
1197 existing_entry
->SetHasPostData(params
.is_post
);
1198 existing_entry
->SetPostID(params
.post_id
);
1200 DiscardNonCommittedEntries();
1203 void NavigationControllerImpl::RendererDidNavigateInPage(
1204 RenderFrameHost
* rfh
,
1205 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
,
1206 bool* did_replace_entry
) {
1207 DCHECK(ui::PageTransitionIsMainFrame(params
.transition
)) <<
1208 "WebKit should only tell us about in-page navs for the main frame.";
1209 // We're guaranteed to have an entry for this one.
1210 NavigationEntryImpl
* existing_entry
= GetEntryWithPageID(
1211 rfh
->GetSiteInstance(), params
.page_id
);
1213 // Reference fragment navigation. We're guaranteed to have the last_committed
1214 // entry and it will be the same page as the new navigation (minus the
1215 // reference fragments, of course). We'll update the URL of the existing
1216 // entry without pruning the forward history.
1217 existing_entry
->set_page_type(params
.url_is_unreachable
? PAGE_TYPE_ERROR
1218 : PAGE_TYPE_NORMAL
);
1219 existing_entry
->SetURL(params
.url
);
1220 if (existing_entry
->update_virtual_url_with_url())
1221 UpdateVirtualURLToURL(existing_entry
, params
.url
);
1223 existing_entry
->SetHasPostData(params
.is_post
);
1224 existing_entry
->SetPostID(params
.post_id
);
1226 // This replaces the existing entry since the page ID didn't change.
1227 *did_replace_entry
= true;
1229 DiscardNonCommittedEntriesInternal();
1231 // If a transient entry was removed, the indices might have changed, so we
1232 // have to query the entry index again.
1233 last_committed_entry_index_
=
1234 GetEntryIndexWithPageID(rfh
->GetSiteInstance(), params
.page_id
);
1237 void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1238 RenderFrameHost
* rfh
,
1239 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
1240 if (!ui::PageTransitionCoreTypeIs(params
.transition
,
1241 ui::PAGE_TRANSITION_MANUAL_SUBFRAME
)) {
1242 // There was a comment here that said, "This is not user-initiated. Ignore."
1243 // But this makes no sense; non-user-initiated navigations should be
1244 // determined to be of type NAVIGATION_TYPE_AUTO_SUBFRAME and sent to
1245 // RendererDidNavigateAutoSubframe below.
1247 // This if clause dates back to https://codereview.chromium.org/115919 and
1248 // the handling of immediate redirects. TODO(avi): Is this still valid? I'm
1249 // pretty sure that's there's nothing left of that code and that we should
1252 // Except for cross-process iframes; this doesn't work yet for them.
1253 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1254 switches::kSitePerProcess
)) {
1258 DiscardNonCommittedEntriesInternal();
1262 // Manual subframe navigations just get the current entry cloned so the user
1263 // can go back or forward to it. The actual subframe information will be
1264 // stored in the page state for each of those entries. This happens out of
1265 // band with the actual navigations.
1266 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1267 << "that a last committed entry exists.";
1268 NavigationEntryImpl
* new_entry
= new NavigationEntryImpl(
1269 *NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry()));
1270 new_entry
->SetPageID(params
.page_id
);
1271 InsertOrReplaceEntry(new_entry
, false);
1274 bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1275 RenderFrameHost
* rfh
,
1276 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
1277 DCHECK(ui::PageTransitionCoreTypeIs(params
.transition
,
1278 ui::PAGE_TRANSITION_AUTO_SUBFRAME
));
1280 // We're guaranteed to have a previously committed entry, and we now need to
1281 // handle navigation inside of a subframe in it without creating a new entry.
1282 DCHECK(GetLastCommittedEntry());
1284 // Handle the case where we're navigating back/forward to a previous subframe
1285 // navigation entry. This is case "2." in NAV_AUTO_SUBFRAME comment in the
1286 // header file. In case "1." this will be a NOP.
1287 int entry_index
= GetEntryIndexWithPageID(
1288 rfh
->GetSiteInstance(),
1290 if (entry_index
< 0 ||
1291 entry_index
>= static_cast<int>(entries_
.size())) {
1296 // Update the current navigation entry in case we're going back/forward.
1297 if (entry_index
!= last_committed_entry_index_
) {
1298 last_committed_entry_index_
= entry_index
;
1299 DiscardNonCommittedEntriesInternal();
1303 // We do not need to discard the pending entry in this case, since we will
1304 // not generate commit notifications for this auto-subframe navigation.
1308 int NavigationControllerImpl::GetIndexOfEntry(
1309 const NavigationEntryImpl
* entry
) const {
1310 const NavigationEntries::const_iterator
i(std::find(
1314 return (i
== entries_
.end()) ? -1 : static_cast<int>(i
- entries_
.begin());
1317 bool NavigationControllerImpl::IsURLInPageNavigation(
1319 bool renderer_says_in_page
,
1320 RenderFrameHost
* rfh
) const {
1321 NavigationEntry
* last_committed
= GetLastCommittedEntry();
1322 return last_committed
&& AreURLsInPageNavigation(
1323 last_committed
->GetURL(), url
, renderer_says_in_page
, rfh
);
1326 void NavigationControllerImpl::CopyStateFrom(
1327 const NavigationController
& temp
) {
1328 const NavigationControllerImpl
& source
=
1329 static_cast<const NavigationControllerImpl
&>(temp
);
1330 // Verify that we look new.
1331 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1333 if (source
.GetEntryCount() == 0)
1334 return; // Nothing new to do.
1336 needs_reload_
= true;
1337 InsertEntriesFrom(source
, source
.GetEntryCount());
1339 for (SessionStorageNamespaceMap::const_iterator it
=
1340 source
.session_storage_namespace_map_
.begin();
1341 it
!= source
.session_storage_namespace_map_
.end();
1343 SessionStorageNamespaceImpl
* source_namespace
=
1344 static_cast<SessionStorageNamespaceImpl
*>(it
->second
.get());
1345 session_storage_namespace_map_
[it
->first
] = source_namespace
->Clone();
1348 FinishRestore(source
.last_committed_entry_index_
, RESTORE_CURRENT_SESSION
);
1350 // Copy the max page id map from the old tab to the new tab. This ensures
1351 // that new and existing navigations in the tab's current SiteInstances
1352 // are identified properly.
1353 delegate_
->CopyMaxPageIDsFrom(source
.delegate()->GetWebContents());
1356 void NavigationControllerImpl::CopyStateFromAndPrune(
1357 NavigationController
* temp
,
1358 bool replace_entry
) {
1359 // It is up to callers to check the invariants before calling this.
1360 CHECK(CanPruneAllButLastCommitted());
1362 NavigationControllerImpl
* source
=
1363 static_cast<NavigationControllerImpl
*>(temp
);
1365 // Remove all the entries leaving the last committed entry.
1366 PruneAllButLastCommittedInternal();
1368 // We now have one entry, possibly with a new pending entry. Ensure that
1369 // adding the entries from source won't put us over the limit.
1370 DCHECK_EQ(1, GetEntryCount());
1372 source
->PruneOldestEntryIfFull();
1374 // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1375 // we don't want to copy over the transient entry. Ignore any pending entry,
1376 // since it has not committed in source.
1377 int max_source_index
= source
->last_committed_entry_index_
;
1378 if (max_source_index
== -1)
1379 max_source_index
= source
->GetEntryCount();
1383 // Ignore the source's current entry if merging with replacement.
1384 // TODO(davidben): This should preserve entries forward of the current
1385 // too. http://crbug.com/317872
1386 if (replace_entry
&& max_source_index
> 0)
1389 InsertEntriesFrom(*source
, max_source_index
);
1391 // Adjust indices such that the last entry and pending are at the end now.
1392 last_committed_entry_index_
= GetEntryCount() - 1;
1394 delegate_
->SetHistoryOffsetAndLength(last_committed_entry_index_
,
1397 // Copy the max page id map from the old tab to the new tab. This ensures that
1398 // new and existing navigations in the tab's current SiteInstances are
1399 // identified properly.
1400 NavigationEntryImpl
* last_committed
=
1401 NavigationEntryImpl::FromNavigationEntry(GetLastCommittedEntry());
1402 int32 site_max_page_id
=
1403 delegate_
->GetMaxPageIDForSiteInstance(last_committed
->site_instance());
1404 delegate_
->CopyMaxPageIDsFrom(source
->delegate()->GetWebContents());
1405 delegate_
->UpdateMaxPageIDForSiteInstance(last_committed
->site_instance(),
1407 max_restored_page_id_
= source
->max_restored_page_id_
;
1410 bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
1411 // If there is no last committed entry, we cannot prune. Even if there is a
1412 // pending entry, it may not commit, leaving this WebContents blank, despite
1413 // possibly giving it new entries via CopyStateFromAndPrune.
1414 if (last_committed_entry_index_
== -1)
1417 // We cannot prune if there is a pending entry at an existing entry index.
1418 // It may not commit, so we have to keep the last committed entry, and thus
1419 // there is no sensible place to keep the pending entry. It is ok to have
1420 // a new pending entry, which can optionally commit as a new navigation.
1421 if (pending_entry_index_
!= -1)
1424 // We should not prune if we are currently showing a transient entry.
1425 if (transient_entry_index_
!= -1)
1431 void NavigationControllerImpl::PruneAllButLastCommitted() {
1432 PruneAllButLastCommittedInternal();
1434 DCHECK_EQ(0, last_committed_entry_index_
);
1435 DCHECK_EQ(1, GetEntryCount());
1437 delegate_
->SetHistoryOffsetAndLength(last_committed_entry_index_
,
1441 void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
1442 // It is up to callers to check the invariants before calling this.
1443 CHECK(CanPruneAllButLastCommitted());
1445 // Erase all entries but the last committed entry. There may still be a
1446 // new pending entry after this.
1447 entries_
.erase(entries_
.begin(),
1448 entries_
.begin() + last_committed_entry_index_
);
1449 entries_
.erase(entries_
.begin() + 1, entries_
.end());
1450 last_committed_entry_index_
= 0;
1453 void NavigationControllerImpl::ClearAllScreenshots() {
1454 screenshot_manager_
->ClearAllScreenshots();
1457 void NavigationControllerImpl::SetSessionStorageNamespace(
1458 const std::string
& partition_id
,
1459 SessionStorageNamespace
* session_storage_namespace
) {
1460 if (!session_storage_namespace
)
1463 // We can't overwrite an existing SessionStorage without violating spec.
1464 // Attempts to do so may give a tab access to another tab's session storage
1465 // so die hard on an error.
1466 bool successful_insert
= session_storage_namespace_map_
.insert(
1467 make_pair(partition_id
,
1468 static_cast<SessionStorageNamespaceImpl
*>(
1469 session_storage_namespace
)))
1471 CHECK(successful_insert
) << "Cannot replace existing SessionStorageNamespace";
1474 void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id
) {
1475 max_restored_page_id_
= max_id
;
1478 int32
NavigationControllerImpl::GetMaxRestoredPageID() const {
1479 return max_restored_page_id_
;
1482 bool NavigationControllerImpl::IsUnmodifiedBlankTab() const {
1483 return IsInitialNavigation() &&
1484 !GetLastCommittedEntry() &&
1485 !delegate_
->HasAccessedInitialDocument();
1488 SessionStorageNamespace
*
1489 NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance
* instance
) {
1490 std::string partition_id
;
1492 // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1493 // this if statement so |instance| must not be NULL.
1495 GetContentClient()->browser()->GetStoragePartitionIdForSite(
1496 browser_context_
, instance
->GetSiteURL());
1499 SessionStorageNamespaceMap::const_iterator it
=
1500 session_storage_namespace_map_
.find(partition_id
);
1501 if (it
!= session_storage_namespace_map_
.end())
1502 return it
->second
.get();
1504 // Create one if no one has accessed session storage for this partition yet.
1506 // TODO(ajwong): Should this use the |partition_id| directly rather than
1507 // re-lookup via |instance|? http://crbug.com/142685
1508 StoragePartition
* partition
=
1509 BrowserContext::GetStoragePartition(browser_context_
, instance
);
1510 SessionStorageNamespaceImpl
* session_storage_namespace
=
1511 new SessionStorageNamespaceImpl(
1512 static_cast<DOMStorageContextWrapper
*>(
1513 partition
->GetDOMStorageContext()));
1514 session_storage_namespace_map_
[partition_id
] = session_storage_namespace
;
1516 return session_storage_namespace
;
1519 SessionStorageNamespace
*
1520 NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1521 // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1522 return GetSessionStorageNamespace(NULL
);
1525 const SessionStorageNamespaceMap
&
1526 NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1527 return session_storage_namespace_map_
;
1530 bool NavigationControllerImpl::NeedsReload() const {
1531 return needs_reload_
;
1534 void NavigationControllerImpl::SetNeedsReload() {
1535 needs_reload_
= true;
1537 if (last_committed_entry_index_
!= -1) {
1538 entries_
[last_committed_entry_index_
]->SetTransitionType(
1539 ui::PAGE_TRANSITION_RELOAD
);
1543 void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index
) {
1544 DCHECK(index
< GetEntryCount());
1545 DCHECK(index
!= last_committed_entry_index_
);
1547 DiscardNonCommittedEntries();
1549 entries_
.erase(entries_
.begin() + index
);
1550 if (last_committed_entry_index_
> index
)
1551 last_committed_entry_index_
--;
1554 void NavigationControllerImpl::DiscardNonCommittedEntries() {
1555 bool transient
= transient_entry_index_
!= -1;
1556 DiscardNonCommittedEntriesInternal();
1558 // If there was a transient entry, invalidate everything so the new active
1559 // entry state is shown.
1561 delegate_
->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL
);
1565 NavigationEntry
* NavigationControllerImpl::GetPendingEntry() const {
1566 return pending_entry_
;
1569 int NavigationControllerImpl::GetPendingEntryIndex() const {
1570 return pending_entry_index_
;
1573 void NavigationControllerImpl::InsertOrReplaceEntry(NavigationEntryImpl
* entry
,
1575 DCHECK(entry
->GetTransitionType() != ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
1577 // Copy the pending entry's unique ID to the committed entry.
1578 // I don't know if pending_entry_index_ can be other than -1 here.
1579 const NavigationEntryImpl
* const pending_entry
=
1580 (pending_entry_index_
== -1) ?
1581 pending_entry_
: entries_
[pending_entry_index_
].get();
1583 entry
->set_unique_id(pending_entry
->GetUniqueID());
1585 DiscardNonCommittedEntriesInternal();
1587 int current_size
= static_cast<int>(entries_
.size());
1588 DCHECK(current_size
> 0 || !replace
);
1590 if (current_size
> 0) {
1591 // Prune any entries which are in front of the current entry.
1592 // Also prune the current entry if we are to replace the current entry.
1593 // last_committed_entry_index_ must be updated here since calls to
1594 // NotifyPrunedEntries() below may re-enter and we must make sure
1595 // last_committed_entry_index_ is not left in an invalid state.
1597 --last_committed_entry_index_
;
1600 while (last_committed_entry_index_
< (current_size
- 1)) {
1602 entries_
.pop_back();
1605 if (num_pruned
> 0) // Only notify if we did prune something.
1606 NotifyPrunedEntries(this, false, num_pruned
);
1609 PruneOldestEntryIfFull();
1611 entries_
.push_back(linked_ptr
<NavigationEntryImpl
>(entry
));
1612 last_committed_entry_index_
= static_cast<int>(entries_
.size()) - 1;
1614 // This is a new page ID, so we need everybody to know about it.
1615 delegate_
->UpdateMaxPageID(entry
->GetPageID());
1618 void NavigationControllerImpl::PruneOldestEntryIfFull() {
1619 if (entries_
.size() >= max_entry_count()) {
1620 DCHECK_EQ(max_entry_count(), entries_
.size());
1621 DCHECK_GT(last_committed_entry_index_
, 0);
1622 RemoveEntryAtIndex(0);
1623 NotifyPrunedEntries(this, true, 1);
1627 void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type
) {
1628 needs_reload_
= false;
1630 // If we were navigating to a slow-to-commit page, and the user performs
1631 // a session history navigation to the last committed page, RenderViewHost
1632 // will force the throbber to start, but WebKit will essentially ignore the
1633 // navigation, and won't send a message to stop the throbber. To prevent this
1634 // from happening, we drop the navigation here and stop the slow-to-commit
1635 // page from loading (which would normally happen during the navigation).
1636 if (pending_entry_index_
!= -1 &&
1637 pending_entry_index_
== last_committed_entry_index_
&&
1638 (entries_
[pending_entry_index_
]->restore_type() ==
1639 NavigationEntryImpl::RESTORE_NONE
) &&
1640 (entries_
[pending_entry_index_
]->GetTransitionType() &
1641 ui::PAGE_TRANSITION_FORWARD_BACK
)) {
1644 // If an interstitial page is showing, we want to close it to get back
1645 // to what was showing before.
1646 if (delegate_
->GetInterstitialPage())
1647 delegate_
->GetInterstitialPage()->DontProceed();
1649 DiscardNonCommittedEntries();
1653 // If an interstitial page is showing, the previous renderer is blocked and
1654 // cannot make new requests. Unblock (and disable) it to allow this
1655 // navigation to succeed. The interstitial will stay visible until the
1656 // resulting DidNavigate.
1657 if (delegate_
->GetInterstitialPage()) {
1658 static_cast<InterstitialPageImpl
*>(delegate_
->GetInterstitialPage())->
1659 CancelForNavigation();
1662 // For session history navigations only the pending_entry_index_ is set.
1663 if (!pending_entry_
) {
1664 DCHECK_NE(pending_entry_index_
, -1);
1665 pending_entry_
= entries_
[pending_entry_index_
].get();
1668 // This call does not support re-entrancy. See http://crbug.com/347742.
1669 CHECK(!in_navigate_to_pending_entry_
);
1670 in_navigate_to_pending_entry_
= true;
1671 bool success
= delegate_
->NavigateToPendingEntry(reload_type
);
1672 in_navigate_to_pending_entry_
= false;
1675 DiscardNonCommittedEntries();
1677 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1678 // it in now that we know. This allows us to find the entry when it commits.
1679 if (pending_entry_
&& !pending_entry_
->site_instance() &&
1680 pending_entry_
->restore_type() != NavigationEntryImpl::RESTORE_NONE
) {
1681 pending_entry_
->set_site_instance(static_cast<SiteInstanceImpl
*>(
1682 delegate_
->GetPendingSiteInstance()));
1683 pending_entry_
->set_restore_type(NavigationEntryImpl::RESTORE_NONE
);
1687 void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1688 LoadCommittedDetails
* details
) {
1689 details
->entry
= GetLastCommittedEntry();
1691 // We need to notify the ssl_manager_ before the web_contents_ so the
1692 // location bar will have up-to-date information about the security style
1693 // when it wants to draw. See http://crbug.com/11157
1694 ssl_manager_
.DidCommitProvisionalLoad(*details
);
1696 delegate_
->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL
);
1697 delegate_
->NotifyNavigationEntryCommitted(*details
);
1699 // TODO(avi): Remove. http://crbug.com/170921
1700 NotificationDetails notification_details
=
1701 Details
<LoadCommittedDetails
>(details
);
1702 NotificationService::current()->Notify(
1703 NOTIFICATION_NAV_ENTRY_COMMITTED
,
1704 Source
<NavigationController
>(this),
1705 notification_details
);
1709 size_t NavigationControllerImpl::max_entry_count() {
1710 if (max_entry_count_for_testing_
!= kMaxEntryCountForTestingNotSet
)
1711 return max_entry_count_for_testing_
;
1712 return kMaxSessionHistoryEntries
;
1715 void NavigationControllerImpl::SetActive(bool is_active
) {
1716 if (is_active
&& needs_reload_
)
1720 void NavigationControllerImpl::LoadIfNecessary() {
1724 // Calling Reload() results in ignoring state, and not loading.
1725 // Explicitly use NavigateToPendingEntry so that the renderer uses the
1727 pending_entry_index_
= last_committed_entry_index_
;
1728 NavigateToPendingEntry(NO_RELOAD
);
1731 void NavigationControllerImpl::NotifyEntryChanged(const NavigationEntry
* entry
,
1733 EntryChangedDetails det
;
1734 det
.changed_entry
= entry
;
1736 NotificationService::current()->Notify(
1737 NOTIFICATION_NAV_ENTRY_CHANGED
,
1738 Source
<NavigationController
>(this),
1739 Details
<EntryChangedDetails
>(&det
));
1742 void NavigationControllerImpl::FinishRestore(int selected_index
,
1744 DCHECK(selected_index
>= 0 && selected_index
< GetEntryCount());
1745 ConfigureEntriesForRestore(&entries_
, type
);
1747 SetMaxRestoredPageID(static_cast<int32
>(GetEntryCount()));
1749 last_committed_entry_index_
= selected_index
;
1752 void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1753 DiscardPendingEntry();
1754 DiscardTransientEntry();
1757 void NavigationControllerImpl::DiscardPendingEntry() {
1758 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
1759 // progress, since this will cause a use-after-free. (We only allow this
1760 // when the tab is being destroyed for shutdown, since it won't return to
1761 // NavigateToEntry in that case.) http://crbug.com/347742.
1762 CHECK(!in_navigate_to_pending_entry_
|| delegate_
->IsBeingDestroyed());
1764 if (pending_entry_index_
== -1)
1765 delete pending_entry_
;
1766 pending_entry_
= NULL
;
1767 pending_entry_index_
= -1;
1770 void NavigationControllerImpl::DiscardTransientEntry() {
1771 if (transient_entry_index_
== -1)
1773 entries_
.erase(entries_
.begin() + transient_entry_index_
);
1774 if (last_committed_entry_index_
> transient_entry_index_
)
1775 last_committed_entry_index_
--;
1776 transient_entry_index_
= -1;
1779 int NavigationControllerImpl::GetEntryIndexWithPageID(
1780 SiteInstance
* instance
, int32 page_id
) const {
1781 for (int i
= static_cast<int>(entries_
.size()) - 1; i
>= 0; --i
) {
1782 if ((entries_
[i
]->site_instance() == instance
) &&
1783 (entries_
[i
]->GetPageID() == page_id
))
1789 NavigationEntry
* NavigationControllerImpl::GetTransientEntry() const {
1790 if (transient_entry_index_
== -1)
1792 return entries_
[transient_entry_index_
].get();
1795 void NavigationControllerImpl::SetTransientEntry(NavigationEntry
* entry
) {
1796 // Discard any current transient entry, we can only have one at a time.
1798 if (last_committed_entry_index_
!= -1)
1799 index
= last_committed_entry_index_
+ 1;
1800 DiscardTransientEntry();
1802 entries_
.begin() + index
, linked_ptr
<NavigationEntryImpl
>(
1803 NavigationEntryImpl::FromNavigationEntry(entry
)));
1804 transient_entry_index_
= index
;
1805 delegate_
->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL
);
1808 void NavigationControllerImpl::InsertEntriesFrom(
1809 const NavigationControllerImpl
& source
,
1811 DCHECK_LE(max_index
, source
.GetEntryCount());
1812 size_t insert_index
= 0;
1813 for (int i
= 0; i
< max_index
; i
++) {
1814 // When cloning a tab, copy all entries except interstitial pages
1815 if (source
.entries_
[i
].get()->GetPageType() !=
1816 PAGE_TYPE_INTERSTITIAL
) {
1817 entries_
.insert(entries_
.begin() + insert_index
++,
1818 linked_ptr
<NavigationEntryImpl
>(
1819 new NavigationEntryImpl(*source
.entries_
[i
])));
1824 void NavigationControllerImpl::SetGetTimestampCallbackForTest(
1825 const base::Callback
<base::Time()>& get_timestamp_callback
) {
1826 get_timestamp_callback_
= get_timestamp_callback
;
1829 } // namespace content