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
= GetTransientEntry();
295 if (!transient_entry
)
297 LoadURL(transient_entry
->GetURL(),
299 ui::PAGE_TRANSITION_RELOAD
,
300 transient_entry
->extra_headers());
304 NavigationEntryImpl
* entry
= NULL
;
305 int current_index
= -1;
307 // If we are reloading the initial navigation, just use the current
308 // pending entry. Otherwise look up the current entry.
309 if (IsInitialNavigation() && pending_entry_
) {
310 entry
= pending_entry_
;
311 // The pending entry might be in entries_ (e.g., after a Clone), so we
312 // should also update the current_index.
313 current_index
= pending_entry_index_
;
315 DiscardNonCommittedEntriesInternal();
316 current_index
= GetCurrentEntryIndex();
317 if (current_index
!= -1) {
318 entry
= GetEntryAtIndex(current_index
);
322 // If we are no where, then we can't reload. TODO(darin): We should add a
327 if (reload_type
== NavigationControllerImpl::RELOAD_ORIGINAL_REQUEST_URL
&&
328 entry
->GetOriginalRequestURL().is_valid() && !entry
->GetHasPostData()) {
329 // We may have been redirected when navigating to the current URL.
330 // Use the URL the user originally intended to visit, if it's valid and if a
331 // POST wasn't involved; the latter case avoids issues with sending data to
333 entry
->SetURL(entry
->GetOriginalRequestURL());
334 entry
->SetReferrer(Referrer());
337 if (g_check_for_repost
&& check_for_repost
&&
338 entry
->GetHasPostData()) {
339 // The user is asking to reload a page with POST data. Prompt to make sure
340 // they really want to do this. If they do, the dialog will call us back
341 // with check_for_repost = false.
342 delegate_
->NotifyBeforeFormRepostWarningShow();
344 pending_reload_
= reload_type
;
345 delegate_
->ActivateAndShowRepostFormWarningDialog();
347 if (!IsInitialNavigation())
348 DiscardNonCommittedEntriesInternal();
350 // If we are reloading an entry that no longer belongs to the current
351 // site instance (for example, refreshing a page for just installed app),
352 // the reload must happen in a new process.
353 // The new entry must have a new page_id and site instance, so it behaves
354 // as new navigation (which happens to clear forward history).
355 // Tabs that are discarded due to low memory conditions may not have a site
356 // instance, and should not be treated as a cross-site reload.
357 SiteInstanceImpl
* site_instance
= entry
->site_instance();
358 // Permit reloading guests without further checks.
359 bool is_isolated_guest
= site_instance
&& site_instance
->HasProcess() &&
360 site_instance
->GetProcess()->IsIsolatedGuest();
361 if (!is_isolated_guest
&& site_instance
&&
362 site_instance
->HasWrongProcessForURL(entry
->GetURL())) {
363 // Create a navigation entry that resembles the current one, but do not
364 // copy page id, site instance, content state, or timestamp.
365 NavigationEntryImpl
* nav_entry
= NavigationEntryImpl::FromNavigationEntry(
366 CreateNavigationEntry(
367 entry
->GetURL(), entry
->GetReferrer(), entry
->GetTransitionType(),
368 false, entry
->extra_headers(), browser_context_
));
370 // Mark the reload type as NO_RELOAD, so navigation will not be considered
371 // a reload in the renderer.
372 reload_type
= NavigationController::NO_RELOAD
;
374 nav_entry
->set_should_replace_entry(true);
375 pending_entry_
= nav_entry
;
377 pending_entry_
= entry
;
378 pending_entry_index_
= current_index
;
380 // The title of the page being reloaded might have been removed in the
381 // meanwhile, so we need to revert to the default title upon reload and
382 // invalidate the previously cached title (SetTitle will do both).
383 // See Chromium issue 96041.
384 pending_entry_
->SetTitle(base::string16());
386 pending_entry_
->SetTransitionType(ui::PAGE_TRANSITION_RELOAD
);
389 NavigateToPendingEntry(reload_type
);
393 void NavigationControllerImpl::CancelPendingReload() {
394 DCHECK(pending_reload_
!= NO_RELOAD
);
395 pending_reload_
= NO_RELOAD
;
398 void NavigationControllerImpl::ContinuePendingReload() {
399 if (pending_reload_
== NO_RELOAD
) {
402 ReloadInternal(false, pending_reload_
);
403 pending_reload_
= NO_RELOAD
;
407 bool NavigationControllerImpl::IsInitialNavigation() const {
408 return is_initial_navigation_
;
411 NavigationEntryImpl
* NavigationControllerImpl::GetEntryWithPageID(
412 SiteInstance
* instance
, int32 page_id
) const {
413 int index
= GetEntryIndexWithPageID(instance
, page_id
);
414 return (index
!= -1) ? entries_
[index
].get() : NULL
;
417 void NavigationControllerImpl::LoadEntry(NavigationEntryImpl
* entry
) {
418 // When navigating to a new page, we don't know for sure if we will actually
419 // end up leaving the current page. The new page load could for example
420 // result in a download or a 'no content' response (e.g., a mailto: URL).
421 SetPendingEntry(entry
);
422 NavigateToPendingEntry(NO_RELOAD
);
425 void NavigationControllerImpl::SetPendingEntry(NavigationEntryImpl
* entry
) {
426 DiscardNonCommittedEntriesInternal();
427 pending_entry_
= entry
;
428 NotificationService::current()->Notify(
429 NOTIFICATION_NAV_ENTRY_PENDING
,
430 Source
<NavigationController
>(this),
431 Details
<NavigationEntry
>(entry
));
434 NavigationEntryImpl
* NavigationControllerImpl::GetActiveEntry() const {
435 if (transient_entry_index_
!= -1)
436 return entries_
[transient_entry_index_
].get();
438 return pending_entry_
;
439 return GetLastCommittedEntry();
442 NavigationEntryImpl
* NavigationControllerImpl::GetVisibleEntry() const {
443 if (transient_entry_index_
!= -1)
444 return entries_
[transient_entry_index_
].get();
445 // The pending entry is safe to return for new (non-history), browser-
446 // initiated navigations. Most renderer-initiated navigations should not
447 // show the pending entry, to prevent URL spoof attacks.
449 // We make an exception for renderer-initiated navigations in new tabs, as
450 // long as no other page has tried to access the initial empty document in
451 // the new tab. If another page modifies this blank page, a URL spoof is
452 // possible, so we must stop showing the pending entry.
453 bool safe_to_show_pending
=
455 // Require a new navigation.
456 pending_entry_index_
== -1 &&
457 // Require either browser-initiated or an unmodified new tab.
458 (!pending_entry_
->is_renderer_initiated() || IsUnmodifiedBlankTab());
460 // Also allow showing the pending entry for history navigations in a new tab,
461 // such as Ctrl+Back. In this case, no existing page is visible and no one
462 // can script the new tab before it commits.
463 if (!safe_to_show_pending
&&
465 pending_entry_index_
!= -1 &&
466 IsInitialNavigation() &&
467 !pending_entry_
->is_renderer_initiated())
468 safe_to_show_pending
= true;
470 if (safe_to_show_pending
)
471 return pending_entry_
;
472 return GetLastCommittedEntry();
475 int NavigationControllerImpl::GetCurrentEntryIndex() const {
476 if (transient_entry_index_
!= -1)
477 return transient_entry_index_
;
478 if (pending_entry_index_
!= -1)
479 return pending_entry_index_
;
480 return last_committed_entry_index_
;
483 NavigationEntryImpl
* NavigationControllerImpl::GetLastCommittedEntry() const {
484 if (last_committed_entry_index_
== -1)
486 return entries_
[last_committed_entry_index_
].get();
489 bool NavigationControllerImpl::CanViewSource() const {
490 const std::string
& mime_type
= delegate_
->GetContentsMimeType();
491 bool is_viewable_mime_type
= net::IsSupportedNonImageMimeType(mime_type
) &&
492 !net::IsSupportedMediaMimeType(mime_type
);
493 NavigationEntry
* visible_entry
= GetVisibleEntry();
494 return visible_entry
&& !visible_entry
->IsViewSourceMode() &&
495 is_viewable_mime_type
&& !delegate_
->GetInterstitialPage();
498 int NavigationControllerImpl::GetLastCommittedEntryIndex() const {
499 return last_committed_entry_index_
;
502 int NavigationControllerImpl::GetEntryCount() const {
503 DCHECK(entries_
.size() <= max_entry_count());
504 return static_cast<int>(entries_
.size());
507 NavigationEntryImpl
* NavigationControllerImpl::GetEntryAtIndex(
509 return entries_
.at(index
).get();
512 NavigationEntryImpl
* NavigationControllerImpl::GetEntryAtOffset(
514 int index
= GetIndexForOffset(offset
);
515 if (index
< 0 || index
>= GetEntryCount())
518 return entries_
[index
].get();
521 int NavigationControllerImpl::GetIndexForOffset(int offset
) const {
522 return GetCurrentEntryIndex() + offset
;
525 void NavigationControllerImpl::TakeScreenshot() {
526 screenshot_manager_
->TakeScreenshot();
529 void NavigationControllerImpl::SetScreenshotManager(
530 NavigationEntryScreenshotManager
* manager
) {
531 screenshot_manager_
.reset(manager
? manager
:
532 new NavigationEntryScreenshotManager(this));
535 bool NavigationControllerImpl::CanGoBack() const {
536 return entries_
.size() > 1 && GetCurrentEntryIndex() > 0;
539 bool NavigationControllerImpl::CanGoForward() const {
540 int index
= GetCurrentEntryIndex();
541 return index
>= 0 && index
< (static_cast<int>(entries_
.size()) - 1);
544 bool NavigationControllerImpl::CanGoToOffset(int offset
) const {
545 int index
= GetIndexForOffset(offset
);
546 return index
>= 0 && index
< GetEntryCount();
549 void NavigationControllerImpl::GoBack() {
555 // Base the navigation on where we are now...
556 int current_index
= GetCurrentEntryIndex();
558 DiscardNonCommittedEntries();
560 pending_entry_index_
= current_index
- 1;
561 entries_
[pending_entry_index_
]->SetTransitionType(
562 ui::PageTransitionFromInt(
563 entries_
[pending_entry_index_
]->GetTransitionType() |
564 ui::PAGE_TRANSITION_FORWARD_BACK
));
565 NavigateToPendingEntry(NO_RELOAD
);
568 void NavigationControllerImpl::GoForward() {
569 if (!CanGoForward()) {
574 bool transient
= (transient_entry_index_
!= -1);
576 // Base the navigation on where we are now...
577 int current_index
= GetCurrentEntryIndex();
579 DiscardNonCommittedEntries();
581 pending_entry_index_
= current_index
;
582 // If there was a transient entry, we removed it making the current index
585 pending_entry_index_
++;
587 entries_
[pending_entry_index_
]->SetTransitionType(
588 ui::PageTransitionFromInt(
589 entries_
[pending_entry_index_
]->GetTransitionType() |
590 ui::PAGE_TRANSITION_FORWARD_BACK
));
591 NavigateToPendingEntry(NO_RELOAD
);
594 void NavigationControllerImpl::GoToIndex(int index
) {
595 if (index
< 0 || index
>= static_cast<int>(entries_
.size())) {
600 if (transient_entry_index_
!= -1) {
601 if (index
== transient_entry_index_
) {
602 // Nothing to do when navigating to the transient.
605 if (index
> transient_entry_index_
) {
606 // Removing the transient is goint to shift all entries by 1.
611 DiscardNonCommittedEntries();
613 pending_entry_index_
= index
;
614 entries_
[pending_entry_index_
]->SetTransitionType(
615 ui::PageTransitionFromInt(
616 entries_
[pending_entry_index_
]->GetTransitionType() |
617 ui::PAGE_TRANSITION_FORWARD_BACK
));
618 NavigateToPendingEntry(NO_RELOAD
);
621 void NavigationControllerImpl::GoToOffset(int offset
) {
622 if (!CanGoToOffset(offset
))
625 GoToIndex(GetIndexForOffset(offset
));
628 bool NavigationControllerImpl::RemoveEntryAtIndex(int index
) {
629 if (index
== last_committed_entry_index_
||
630 index
== pending_entry_index_
)
633 RemoveEntryAtIndexInternal(index
);
637 void NavigationControllerImpl::UpdateVirtualURLToURL(
638 NavigationEntryImpl
* entry
, const GURL
& new_url
) {
639 GURL
new_virtual_url(new_url
);
640 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
641 &new_virtual_url
, entry
->GetVirtualURL(), browser_context_
)) {
642 entry
->SetVirtualURL(new_virtual_url
);
646 void NavigationControllerImpl::LoadURL(
648 const Referrer
& referrer
,
649 ui::PageTransition transition
,
650 const std::string
& extra_headers
) {
651 LoadURLParams
params(url
);
652 params
.referrer
= referrer
;
653 params
.transition_type
= transition
;
654 params
.extra_headers
= extra_headers
;
655 LoadURLWithParams(params
);
658 void NavigationControllerImpl::LoadURLWithParams(const LoadURLParams
& params
) {
659 TRACE_EVENT1("browser,navigation",
660 "NavigationControllerImpl::LoadURLWithParams",
661 "url", params
.url
.possibly_invalid_spec());
662 if (HandleDebugURL(params
.url
, params
.transition_type
)) {
663 // If Telemetry is running, allow the URL load to proceed as if it's
664 // unhandled, otherwise Telemetry can't tell if Navigation completed.
665 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
666 cc::switches::kEnableGpuBenchmarking
))
670 // Any renderer-side debug URLs or javascript: URLs should be ignored if the
671 // renderer process is not live, unless it is the initial navigation of the
673 if (IsRendererDebugURL(params
.url
)) {
674 // TODO(creis): Find the RVH for the correct frame.
675 if (!delegate_
->GetRenderViewHost()->IsRenderViewLive() &&
676 !IsInitialNavigation())
680 // Checks based on params.load_type.
681 switch (params
.load_type
) {
682 case LOAD_TYPE_DEFAULT
:
684 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST
:
685 if (!params
.url
.SchemeIs(url::kHttpScheme
) &&
686 !params
.url
.SchemeIs(url::kHttpsScheme
)) {
687 NOTREACHED() << "Http post load must use http(s) scheme.";
692 if (!params
.url
.SchemeIs(url::kDataScheme
)) {
693 NOTREACHED() << "Data load must use data scheme.";
702 // The user initiated a load, we don't need to reload anymore.
703 needs_reload_
= false;
705 bool override
= false;
706 switch (params
.override_user_agent
) {
707 case UA_OVERRIDE_INHERIT
:
708 override
= ShouldKeepOverride(GetLastCommittedEntry());
710 case UA_OVERRIDE_TRUE
:
713 case UA_OVERRIDE_FALSE
:
721 NavigationEntryImpl
* entry
= NavigationEntryImpl::FromNavigationEntry(
722 CreateNavigationEntry(
725 params
.transition_type
,
726 params
.is_renderer_initiated
,
727 params
.extra_headers
,
729 if (params
.frame_tree_node_id
!= -1)
730 entry
->set_frame_tree_node_id(params
.frame_tree_node_id
);
731 entry
->set_source_site_instance(
732 static_cast<SiteInstanceImpl
*>(params
.source_site_instance
.get()));
733 if (params
.redirect_chain
.size() > 0)
734 entry
->SetRedirectChain(params
.redirect_chain
);
735 // Don't allow an entry replacement if there is no entry to replace.
736 // http://crbug.com/457149
737 if (params
.should_replace_current_entry
&& entries_
.size() > 0)
738 entry
->set_should_replace_entry(true);
739 entry
->set_should_clear_history_list(params
.should_clear_history_list
);
740 entry
->SetIsOverridingUserAgent(override
);
741 entry
->set_transferred_global_request_id(
742 params
.transferred_global_request_id
);
743 entry
->SetFrameToNavigate(params
.frame_name
);
745 #if defined(OS_ANDROID)
746 if (params
.intent_received_timestamp
> 0) {
747 entry
->set_intent_received_timestamp(
749 base::TimeDelta::FromMilliseconds(params
.intent_received_timestamp
));
753 switch (params
.load_type
) {
754 case LOAD_TYPE_DEFAULT
:
756 case LOAD_TYPE_BROWSER_INITIATED_HTTP_POST
:
757 entry
->SetHasPostData(true);
758 entry
->SetBrowserInitiatedPostData(
759 params
.browser_initiated_post_data
.get());
762 entry
->SetBaseURLForDataURL(params
.base_url_for_data_url
);
763 entry
->SetVirtualURL(params
.virtual_url_for_data_url
);
764 entry
->SetCanLoadLocalResources(params
.can_load_local_resources
);
774 bool NavigationControllerImpl::RendererDidNavigate(
775 RenderFrameHostImpl
* rfh
,
776 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
,
777 LoadCommittedDetails
* details
) {
778 is_initial_navigation_
= false;
780 // Save the previous state before we clobber it.
781 if (GetLastCommittedEntry()) {
782 details
->previous_url
= GetLastCommittedEntry()->GetURL();
783 details
->previous_entry_index
= GetLastCommittedEntryIndex();
785 details
->previous_url
= GURL();
786 details
->previous_entry_index
= -1;
789 // If we have a pending entry at this point, it should have a SiteInstance.
790 // Restored entries start out with a null SiteInstance, but we should have
791 // assigned one in NavigateToPendingEntry.
792 DCHECK(pending_entry_index_
== -1 || pending_entry_
->site_instance());
794 // If we are doing a cross-site reload, we need to replace the existing
795 // navigation entry, not add another entry to the history. This has the side
796 // effect of removing forward browsing history, if such existed.
797 // Or if we are doing a cross-site redirect navigation,
798 // we will do a similar thing.
799 details
->did_replace_entry
=
800 pending_entry_
&& pending_entry_
->should_replace_entry();
802 // Do navigation-type specific actions. These will make and commit an entry.
803 details
->type
= ClassifyNavigation(rfh
, params
);
805 // is_in_page must be computed before the entry gets committed.
806 details
->is_in_page
= AreURLsInPageNavigation(rfh
->GetLastCommittedURL(),
807 params
.url
, params
.was_within_same_page
, rfh
);
809 switch (details
->type
) {
810 case NAVIGATION_TYPE_NEW_PAGE
:
811 RendererDidNavigateToNewPage(rfh
, params
, details
->did_replace_entry
);
813 case NAVIGATION_TYPE_EXISTING_PAGE
:
814 RendererDidNavigateToExistingPage(rfh
, params
);
816 case NAVIGATION_TYPE_SAME_PAGE
:
817 RendererDidNavigateToSamePage(rfh
, params
);
819 case NAVIGATION_TYPE_IN_PAGE
:
820 RendererDidNavigateInPage(rfh
, params
, &details
->did_replace_entry
);
822 case NAVIGATION_TYPE_NEW_SUBFRAME
:
823 RendererDidNavigateNewSubframe(rfh
, params
);
825 case NAVIGATION_TYPE_AUTO_SUBFRAME
:
826 if (!RendererDidNavigateAutoSubframe(rfh
, params
))
829 case NAVIGATION_TYPE_NAV_IGNORE
:
830 // If a pending navigation was in progress, this canceled it. We should
831 // discard it and make sure it is removed from the URL bar. After that,
832 // there is nothing we can do with this navigation, so we just return to
833 // the caller that nothing has happened.
834 if (pending_entry_
) {
835 DiscardNonCommittedEntries();
836 delegate_
->NotifyNavigationStateChanged(INVALIDATE_TYPE_URL
);
843 // At this point, we know that the navigation has just completed, so
846 // TODO(akalin): Use "sane time" as described in
847 // http://www.chromium.org/developers/design-documents/sane-time .
848 base::Time timestamp
=
849 time_smoother_
.GetSmoothedTime(get_timestamp_callback_
.Run());
850 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
851 << timestamp
.ToInternalValue();
853 // We should not have a pending entry anymore. Clear it again in case any
854 // error cases above forgot to do so.
855 DiscardNonCommittedEntriesInternal();
857 // All committed entries should have nonempty content state so WebKit doesn't
858 // get confused when we go back to them (see the function for details).
859 DCHECK(params
.page_state
.IsValid());
860 NavigationEntryImpl
* active_entry
= GetLastCommittedEntry();
861 active_entry
->SetTimestamp(timestamp
);
862 active_entry
->SetHttpStatusCode(params
.http_status_code
);
863 active_entry
->SetPageState(params
.page_state
);
864 active_entry
->SetRedirectChain(params
.redirects
);
866 // Use histogram to track memory impact of redirect chain because it's now
867 // not cleared for committed entries.
868 size_t redirect_chain_size
= 0;
869 for (size_t i
= 0; i
< params
.redirects
.size(); ++i
) {
870 redirect_chain_size
+= params
.redirects
[i
].spec().length();
872 UMA_HISTOGRAM_COUNTS("Navigation.RedirectChainSize", redirect_chain_size
);
874 // Once it is committed, we no longer need to track several pieces of state on
876 active_entry
->ResetForCommit();
878 // The active entry's SiteInstance should match our SiteInstance.
879 // TODO(creis): This check won't pass for subframes until we create entries
880 // for subframe navigations.
881 if (ui::PageTransitionIsMainFrame(params
.transition
))
882 CHECK(active_entry
->site_instance() == rfh
->GetSiteInstance());
884 // Remember the bindings the renderer process has at this point, so that
885 // we do not grant this entry additional bindings if we come back to it.
886 active_entry
->SetBindings(rfh
->GetEnabledBindings());
888 // Now prep the rest of the details for the notification and broadcast.
889 details
->entry
= active_entry
;
890 details
->is_main_frame
=
891 ui::PageTransitionIsMainFrame(params
.transition
);
892 details
->serialized_security_info
= params
.security_info
;
893 details
->http_status_code
= params
.http_status_code
;
894 NotifyNavigationEntryCommitted(details
);
899 NavigationType
NavigationControllerImpl::ClassifyNavigation(
900 RenderFrameHostImpl
* rfh
,
901 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) const {
902 if (params
.page_id
== -1) {
903 // TODO(nasko, creis): An out-of-process child frame has no way of
904 // knowing the page_id of its parent, so it is passing back -1. The
905 // semantics here should be re-evaluated during session history refactor
906 // (see http://crbug.com/236848). For now, we assume this means the
907 // child frame loaded and proceed. Note that this may do the wrong thing
908 // for cross-process AUTO_SUBFRAME navigations.
909 if (rfh
->IsCrossProcessSubframe())
910 return NAVIGATION_TYPE_NEW_SUBFRAME
;
912 // The renderer generates the page IDs, and so if it gives us the invalid
913 // page ID (-1) we know it didn't actually navigate. This happens in a few
916 // - If a page makes a popup navigated to about blank, and then writes
917 // stuff like a subframe navigated to a real page. We'll get the commit
918 // for the subframe, but there won't be any commit for the outer page.
920 // - We were also getting these for failed loads (for example, bug 21849).
921 // The guess is that we get a "load commit" for the alternate error page,
922 // but that doesn't affect the page ID, so we get the "old" one, which
923 // could be invalid. This can also happen for a cross-site transition
924 // that causes us to swap processes. Then the error page load will be in
925 // a new process with no page IDs ever assigned (and hence a -1 value),
926 // yet the navigation controller still might have previous pages in its
929 // In these cases, there's nothing we can do with them, so ignore.
930 return NAVIGATION_TYPE_NAV_IGNORE
;
933 if (params
.page_id
> delegate_
->GetMaxPageIDForSiteInstance(
934 rfh
->GetSiteInstance())) {
935 // Greater page IDs than we've ever seen before are new pages. We may or may
936 // not have a pending entry for the page, and this may or may not be the
938 if (ui::PageTransitionIsMainFrame(params
.transition
))
939 return NAVIGATION_TYPE_NEW_PAGE
;
941 // When this is a new subframe navigation, we should have a committed page
942 // for which it's a suframe in. This may not be the case when an iframe is
943 // navigated on a popup navigated to about:blank (the iframe would be
944 // written into the popup by script on the main page). For these cases,
945 // there isn't any navigation stuff we can do, so just ignore it.
946 if (!GetLastCommittedEntry())
947 return NAVIGATION_TYPE_NAV_IGNORE
;
949 // Valid subframe navigation.
950 return NAVIGATION_TYPE_NEW_SUBFRAME
;
953 // We only clear the session history when navigating to a new page.
954 DCHECK(!params
.history_list_was_cleared
);
956 // Now we know that the notification is for an existing page. Find that entry.
957 int existing_entry_index
= GetEntryIndexWithPageID(
958 rfh
->GetSiteInstance(),
960 if (existing_entry_index
== -1) {
961 // The page was not found. It could have been pruned because of the limit on
962 // back/forward entries (not likely since we'll usually tell it to navigate
963 // to such entries). It could also mean that the renderer is smoking crack.
966 // Because the unknown entry has committed, we risk showing the wrong URL in
967 // release builds. Instead, we'll kill the renderer process to be safe.
968 LOG(ERROR
) << "terminating renderer for bad navigation: " << params
.url
;
969 RecordAction(base::UserMetricsAction("BadMessageTerminate_NC"));
971 // Temporary code so we can get more information. Format:
972 // http://url/foo.html#page1#max3#frame1#ids:2_Nx,1_1x,3_2
973 std::string temp
= params
.url
.spec();
974 temp
.append("#page");
975 temp
.append(base::IntToString(params
.page_id
));
977 temp
.append(base::IntToString(delegate_
->GetMaxPageID()));
978 temp
.append("#frame");
979 temp
.append(base::IntToString(rfh
->GetRoutingID()));
981 for (int i
= 0; i
< static_cast<int>(entries_
.size()); ++i
) {
982 // Append entry metadata (e.g., 3_7x):
984 // 7: SiteInstance ID, or N for null
985 // x: appended if not from the current SiteInstance
986 temp
.append(base::IntToString(entries_
[i
]->GetPageID()));
988 if (entries_
[i
]->site_instance())
989 temp
.append(base::IntToString(entries_
[i
]->site_instance()->GetId()));
992 if (entries_
[i
]->site_instance() != rfh
->GetSiteInstance())
997 rfh
->render_view_host()->Send(new ViewMsg_TempCrashWithData(url
));
998 return NAVIGATION_TYPE_NAV_IGNORE
;
1000 NavigationEntryImpl
* existing_entry
= entries_
[existing_entry_index
].get();
1002 if (!ui::PageTransitionIsMainFrame(params
.transition
)) {
1003 // All manual subframes would get new IDs and were handled above, so we
1004 // know this is auto. Since the current page was found in the navigation
1005 // entry list, we're guaranteed to have a last committed entry.
1006 DCHECK(GetLastCommittedEntry());
1007 return NAVIGATION_TYPE_AUTO_SUBFRAME
;
1010 // Anything below here we know is a main frame navigation.
1011 if (pending_entry_
&&
1012 !pending_entry_
->is_renderer_initiated() &&
1013 existing_entry
!= pending_entry_
&&
1014 pending_entry_
->GetPageID() == -1 &&
1015 existing_entry
== GetLastCommittedEntry()) {
1016 // In this case, we have a pending entry for a URL but WebCore didn't do a
1017 // new navigation. This happens when you press enter in the URL bar to
1018 // reload. We will create a pending entry, but WebKit will convert it to
1019 // a reload since it's the same page and not create a new entry for it
1020 // (the user doesn't want to have a new back/forward entry when they do
1021 // this). If this matches the last committed entry, we want to just ignore
1022 // the pending entry and go back to where we were (the "existing entry").
1023 return NAVIGATION_TYPE_SAME_PAGE
;
1026 // Any toplevel navigations with the same base (minus the reference fragment)
1027 // are in-page navigations. We weeded out subframe navigations above. Most of
1028 // the time this doesn't matter since WebKit doesn't tell us about subframe
1029 // navigations that don't actually navigate, but it can happen when there is
1030 // an encoding override (it always sends a navigation request).
1031 if (AreURLsInPageNavigation(existing_entry
->GetURL(), params
.url
,
1032 params
.was_within_same_page
, rfh
)) {
1033 return NAVIGATION_TYPE_IN_PAGE
;
1036 // Since we weeded out "new" navigations above, we know this is an existing
1037 // (back/forward) navigation.
1038 return NAVIGATION_TYPE_EXISTING_PAGE
;
1041 void NavigationControllerImpl::RendererDidNavigateToNewPage(
1042 RenderFrameHostImpl
* rfh
,
1043 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
,
1044 bool replace_entry
) {
1045 NavigationEntryImpl
* new_entry
;
1046 bool update_virtual_url
;
1047 // Only make a copy of the pending entry if it is appropriate for the new page
1048 // that was just loaded. We verify this at a coarse grain by checking that
1049 // the SiteInstance hasn't been assigned to something else.
1050 if (pending_entry_
&&
1051 (!pending_entry_
->site_instance() ||
1052 pending_entry_
->site_instance() == rfh
->GetSiteInstance())) {
1053 new_entry
= new NavigationEntryImpl(*pending_entry_
);
1055 update_virtual_url
= new_entry
->update_virtual_url_with_url();
1057 new_entry
= new NavigationEntryImpl
;
1059 // Find out whether the new entry needs to update its virtual URL on URL
1060 // change and set up the entry accordingly. This is needed to correctly
1061 // update the virtual URL when replaceState is called after a pushState.
1062 GURL url
= params
.url
;
1063 bool needs_update
= false;
1064 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1065 &url
, browser_context_
, &needs_update
);
1066 new_entry
->set_update_virtual_url_with_url(needs_update
);
1068 // When navigating to a new page, give the browser URL handler a chance to
1069 // update the virtual URL based on the new URL. For example, this is needed
1070 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1072 update_virtual_url
= needs_update
;
1075 // Don't use the page type from the pending entry. Some interstitial page
1076 // may have set the type to interstitial. Once we commit, however, the page
1077 // type must always be normal or error.
1078 new_entry
->set_page_type(params
.url_is_unreachable
? PAGE_TYPE_ERROR
1079 : PAGE_TYPE_NORMAL
);
1080 new_entry
->SetURL(params
.url
);
1081 if (update_virtual_url
)
1082 UpdateVirtualURLToURL(new_entry
, params
.url
);
1083 new_entry
->SetReferrer(params
.referrer
);
1084 new_entry
->SetPageID(params
.page_id
);
1085 new_entry
->SetTransitionType(params
.transition
);
1086 new_entry
->set_site_instance(
1087 static_cast<SiteInstanceImpl
*>(rfh
->GetSiteInstance()));
1088 new_entry
->SetHasPostData(params
.is_post
);
1089 new_entry
->SetPostID(params
.post_id
);
1090 new_entry
->SetOriginalRequestURL(params
.original_request_url
);
1091 new_entry
->SetIsOverridingUserAgent(params
.is_overriding_user_agent
);
1093 // history.pushState() is classified as a navigation to a new page, but
1094 // sets was_within_same_page to true. In this case, we already have the
1095 // title and favicon available, so set them immediately.
1096 if (params
.was_within_same_page
&& GetLastCommittedEntry()) {
1097 new_entry
->SetTitle(GetLastCommittedEntry()->GetTitle());
1098 new_entry
->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
1101 DCHECK(!params
.history_list_was_cleared
|| !replace_entry
);
1102 // The browser requested to clear the session history when it initiated the
1103 // navigation. Now we know that the renderer has updated its state accordingly
1104 // and it is safe to also clear the browser side history.
1105 if (params
.history_list_was_cleared
) {
1106 DiscardNonCommittedEntriesInternal();
1108 last_committed_entry_index_
= -1;
1111 InsertOrReplaceEntry(new_entry
, replace_entry
);
1114 void NavigationControllerImpl::RendererDidNavigateToExistingPage(
1115 RenderFrameHostImpl
* rfh
,
1116 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
1117 // We should only get here for main frame navigations.
1118 DCHECK(ui::PageTransitionIsMainFrame(params
.transition
));
1120 // This is a back/forward navigation. The existing page for the ID is
1121 // guaranteed to exist by ClassifyNavigation, and we just need to update it
1122 // with new information from the renderer.
1123 int entry_index
= GetEntryIndexWithPageID(rfh
->GetSiteInstance(),
1125 DCHECK(entry_index
>= 0 &&
1126 entry_index
< static_cast<int>(entries_
.size()));
1127 NavigationEntryImpl
* entry
= entries_
[entry_index
].get();
1129 // The URL may have changed due to redirects.
1130 entry
->set_page_type(params
.url_is_unreachable
? PAGE_TYPE_ERROR
1131 : PAGE_TYPE_NORMAL
);
1132 entry
->SetURL(params
.url
);
1133 entry
->SetReferrer(params
.referrer
);
1134 if (entry
->update_virtual_url_with_url())
1135 UpdateVirtualURLToURL(entry
, params
.url
);
1137 // The redirected to page should not inherit the favicon from the previous
1139 if (ui::PageTransitionIsRedirect(params
.transition
))
1140 entry
->GetFavicon() = FaviconStatus();
1142 // The site instance will normally be the same except during session restore,
1143 // when no site instance will be assigned.
1144 DCHECK(entry
->site_instance() == NULL
||
1145 entry
->site_instance() == rfh
->GetSiteInstance());
1146 entry
->set_site_instance(
1147 static_cast<SiteInstanceImpl
*>(rfh
->GetSiteInstance()));
1149 entry
->SetHasPostData(params
.is_post
);
1150 entry
->SetPostID(params
.post_id
);
1152 // The entry we found in the list might be pending if the user hit
1153 // back/forward/reload. This load should commit it (since it's already in the
1154 // list, we can just discard the pending pointer). We should also discard the
1155 // pending entry if it corresponds to a different navigation, since that one
1156 // is now likely canceled. If it is not canceled, we will treat it as a new
1157 // navigation when it arrives, which is also ok.
1159 // Note that we need to use the "internal" version since we don't want to
1160 // actually change any other state, just kill the pointer.
1161 DiscardNonCommittedEntriesInternal();
1163 // If a transient entry was removed, the indices might have changed, so we
1164 // have to query the entry index again.
1165 last_committed_entry_index_
=
1166 GetEntryIndexWithPageID(rfh
->GetSiteInstance(), params
.page_id
);
1169 void NavigationControllerImpl::RendererDidNavigateToSamePage(
1170 RenderFrameHostImpl
* rfh
,
1171 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
1172 // This mode implies we have a pending entry that's the same as an existing
1173 // entry for this page ID. This entry is guaranteed to exist by
1174 // ClassifyNavigation. All we need to do is update the existing entry.
1175 NavigationEntryImpl
* existing_entry
= GetEntryWithPageID(
1176 rfh
->GetSiteInstance(), params
.page_id
);
1178 // We assign the entry's unique ID to be that of the new one. Since this is
1179 // always the result of a user action, we want to dismiss infobars, etc. like
1180 // a regular user-initiated navigation.
1181 existing_entry
->set_unique_id(pending_entry_
->GetUniqueID());
1183 // The URL may have changed due to redirects.
1184 existing_entry
->set_page_type(params
.url_is_unreachable
? PAGE_TYPE_ERROR
1185 : PAGE_TYPE_NORMAL
);
1186 if (existing_entry
->update_virtual_url_with_url())
1187 UpdateVirtualURLToURL(existing_entry
, params
.url
);
1188 existing_entry
->SetURL(params
.url
);
1189 existing_entry
->SetReferrer(params
.referrer
);
1191 // The page may have been requested with a different HTTP method.
1192 existing_entry
->SetHasPostData(params
.is_post
);
1193 existing_entry
->SetPostID(params
.post_id
);
1195 DiscardNonCommittedEntries();
1198 void NavigationControllerImpl::RendererDidNavigateInPage(
1199 RenderFrameHostImpl
* rfh
,
1200 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
,
1201 bool* did_replace_entry
) {
1202 DCHECK(ui::PageTransitionIsMainFrame(params
.transition
)) <<
1203 "WebKit should only tell us about in-page navs for the main frame.";
1204 // We're guaranteed to have an entry for this one.
1205 NavigationEntryImpl
* existing_entry
= GetEntryWithPageID(
1206 rfh
->GetSiteInstance(), params
.page_id
);
1208 // Reference fragment navigation. We're guaranteed to have the last_committed
1209 // entry and it will be the same page as the new navigation (minus the
1210 // reference fragments, of course). We'll update the URL of the existing
1211 // entry without pruning the forward history.
1212 existing_entry
->set_page_type(params
.url_is_unreachable
? PAGE_TYPE_ERROR
1213 : PAGE_TYPE_NORMAL
);
1214 existing_entry
->SetURL(params
.url
);
1215 if (existing_entry
->update_virtual_url_with_url())
1216 UpdateVirtualURLToURL(existing_entry
, params
.url
);
1218 existing_entry
->SetHasPostData(params
.is_post
);
1219 existing_entry
->SetPostID(params
.post_id
);
1221 // This replaces the existing entry since the page ID didn't change.
1222 *did_replace_entry
= true;
1224 DiscardNonCommittedEntriesInternal();
1226 // If a transient entry was removed, the indices might have changed, so we
1227 // have to query the entry index again.
1228 last_committed_entry_index_
=
1229 GetEntryIndexWithPageID(rfh
->GetSiteInstance(), params
.page_id
);
1232 void NavigationControllerImpl::RendererDidNavigateNewSubframe(
1233 RenderFrameHostImpl
* rfh
,
1234 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
1235 if (!ui::PageTransitionCoreTypeIs(params
.transition
,
1236 ui::PAGE_TRANSITION_MANUAL_SUBFRAME
)) {
1237 // There was a comment here that said, "This is not user-initiated. Ignore."
1238 // But this makes no sense; non-user-initiated navigations should be
1239 // determined to be of type NAVIGATION_TYPE_AUTO_SUBFRAME and sent to
1240 // RendererDidNavigateAutoSubframe below.
1242 // This if clause dates back to https://codereview.chromium.org/115919 and
1243 // the handling of immediate redirects. TODO(avi): Is this still valid? I'm
1244 // pretty sure that's there's nothing left of that code and that we should
1247 // Except for cross-process iframes; this doesn't work yet for them.
1248 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
1249 switches::kSitePerProcess
)) {
1253 DiscardNonCommittedEntriesInternal();
1257 // Manual subframe navigations just get the current entry cloned so the user
1258 // can go back or forward to it. The actual subframe information will be
1259 // stored in the page state for each of those entries. This happens out of
1260 // band with the actual navigations.
1261 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
1262 << "that a last committed entry exists.";
1263 NavigationEntryImpl
* new_entry
=
1264 new NavigationEntryImpl(*GetLastCommittedEntry());
1265 new_entry
->SetPageID(params
.page_id
);
1266 InsertOrReplaceEntry(new_entry
, false);
1269 bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
1270 RenderFrameHostImpl
* rfh
,
1271 const FrameHostMsg_DidCommitProvisionalLoad_Params
& params
) {
1272 DCHECK(ui::PageTransitionCoreTypeIs(params
.transition
,
1273 ui::PAGE_TRANSITION_AUTO_SUBFRAME
));
1275 // We're guaranteed to have a previously committed entry, and we now need to
1276 // handle navigation inside of a subframe in it without creating a new entry.
1277 DCHECK(GetLastCommittedEntry());
1279 // Handle the case where we're navigating back/forward to a previous subframe
1280 // navigation entry. This is case "2." in NAV_AUTO_SUBFRAME comment in the
1281 // header file. In case "1." this will be a NOP.
1282 int entry_index
= GetEntryIndexWithPageID(
1283 rfh
->GetSiteInstance(),
1285 if (entry_index
< 0 ||
1286 entry_index
>= static_cast<int>(entries_
.size())) {
1291 // Update the current navigation entry in case we're going back/forward.
1292 if (entry_index
!= last_committed_entry_index_
) {
1293 last_committed_entry_index_
= entry_index
;
1294 DiscardNonCommittedEntriesInternal();
1298 // We do not need to discard the pending entry in this case, since we will
1299 // not generate commit notifications for this auto-subframe navigation.
1303 int NavigationControllerImpl::GetIndexOfEntry(
1304 const NavigationEntryImpl
* entry
) const {
1305 const NavigationEntries::const_iterator
i(std::find(
1309 return (i
== entries_
.end()) ? -1 : static_cast<int>(i
- entries_
.begin());
1312 bool NavigationControllerImpl::IsURLInPageNavigation(
1314 bool renderer_says_in_page
,
1315 RenderFrameHost
* rfh
) const {
1316 NavigationEntry
* last_committed
= GetLastCommittedEntry();
1317 return last_committed
&& AreURLsInPageNavigation(
1318 last_committed
->GetURL(), url
, renderer_says_in_page
, rfh
);
1321 void NavigationControllerImpl::CopyStateFrom(
1322 const NavigationController
& temp
) {
1323 const NavigationControllerImpl
& source
=
1324 static_cast<const NavigationControllerImpl
&>(temp
);
1325 // Verify that we look new.
1326 DCHECK(GetEntryCount() == 0 && !GetPendingEntry());
1328 if (source
.GetEntryCount() == 0)
1329 return; // Nothing new to do.
1331 needs_reload_
= true;
1332 InsertEntriesFrom(source
, source
.GetEntryCount());
1334 for (SessionStorageNamespaceMap::const_iterator it
=
1335 source
.session_storage_namespace_map_
.begin();
1336 it
!= source
.session_storage_namespace_map_
.end();
1338 SessionStorageNamespaceImpl
* source_namespace
=
1339 static_cast<SessionStorageNamespaceImpl
*>(it
->second
.get());
1340 session_storage_namespace_map_
[it
->first
] = source_namespace
->Clone();
1343 FinishRestore(source
.last_committed_entry_index_
, RESTORE_CURRENT_SESSION
);
1345 // Copy the max page id map from the old tab to the new tab. This ensures
1346 // that new and existing navigations in the tab's current SiteInstances
1347 // are identified properly.
1348 delegate_
->CopyMaxPageIDsFrom(source
.delegate()->GetWebContents());
1351 void NavigationControllerImpl::CopyStateFromAndPrune(
1352 NavigationController
* temp
,
1353 bool replace_entry
) {
1354 // It is up to callers to check the invariants before calling this.
1355 CHECK(CanPruneAllButLastCommitted());
1357 NavigationControllerImpl
* source
=
1358 static_cast<NavigationControllerImpl
*>(temp
);
1360 // Remove all the entries leaving the last committed entry.
1361 PruneAllButLastCommittedInternal();
1363 // We now have one entry, possibly with a new pending entry. Ensure that
1364 // adding the entries from source won't put us over the limit.
1365 DCHECK_EQ(1, GetEntryCount());
1367 source
->PruneOldestEntryIfFull();
1369 // Insert the entries from source. Don't use source->GetCurrentEntryIndex as
1370 // we don't want to copy over the transient entry. Ignore any pending entry,
1371 // since it has not committed in source.
1372 int max_source_index
= source
->last_committed_entry_index_
;
1373 if (max_source_index
== -1)
1374 max_source_index
= source
->GetEntryCount();
1378 // Ignore the source's current entry if merging with replacement.
1379 // TODO(davidben): This should preserve entries forward of the current
1380 // too. http://crbug.com/317872
1381 if (replace_entry
&& max_source_index
> 0)
1384 InsertEntriesFrom(*source
, max_source_index
);
1386 // Adjust indices such that the last entry and pending are at the end now.
1387 last_committed_entry_index_
= GetEntryCount() - 1;
1389 delegate_
->SetHistoryOffsetAndLength(last_committed_entry_index_
,
1392 // Copy the max page id map from the old tab to the new tab. This ensures that
1393 // new and existing navigations in the tab's current SiteInstances are
1394 // identified properly.
1395 NavigationEntryImpl
* last_committed
= GetLastCommittedEntry();
1396 int32 site_max_page_id
=
1397 delegate_
->GetMaxPageIDForSiteInstance(last_committed
->site_instance());
1398 delegate_
->CopyMaxPageIDsFrom(source
->delegate()->GetWebContents());
1399 delegate_
->UpdateMaxPageIDForSiteInstance(last_committed
->site_instance(),
1401 max_restored_page_id_
= source
->max_restored_page_id_
;
1404 bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
1405 // If there is no last committed entry, we cannot prune. Even if there is a
1406 // pending entry, it may not commit, leaving this WebContents blank, despite
1407 // possibly giving it new entries via CopyStateFromAndPrune.
1408 if (last_committed_entry_index_
== -1)
1411 // We cannot prune if there is a pending entry at an existing entry index.
1412 // It may not commit, so we have to keep the last committed entry, and thus
1413 // there is no sensible place to keep the pending entry. It is ok to have
1414 // a new pending entry, which can optionally commit as a new navigation.
1415 if (pending_entry_index_
!= -1)
1418 // We should not prune if we are currently showing a transient entry.
1419 if (transient_entry_index_
!= -1)
1425 void NavigationControllerImpl::PruneAllButLastCommitted() {
1426 PruneAllButLastCommittedInternal();
1428 DCHECK_EQ(0, last_committed_entry_index_
);
1429 DCHECK_EQ(1, GetEntryCount());
1431 delegate_
->SetHistoryOffsetAndLength(last_committed_entry_index_
,
1435 void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
1436 // It is up to callers to check the invariants before calling this.
1437 CHECK(CanPruneAllButLastCommitted());
1439 // Erase all entries but the last committed entry. There may still be a
1440 // new pending entry after this.
1441 entries_
.erase(entries_
.begin(),
1442 entries_
.begin() + last_committed_entry_index_
);
1443 entries_
.erase(entries_
.begin() + 1, entries_
.end());
1444 last_committed_entry_index_
= 0;
1447 void NavigationControllerImpl::ClearAllScreenshots() {
1448 screenshot_manager_
->ClearAllScreenshots();
1451 void NavigationControllerImpl::SetSessionStorageNamespace(
1452 const std::string
& partition_id
,
1453 SessionStorageNamespace
* session_storage_namespace
) {
1454 if (!session_storage_namespace
)
1457 // We can't overwrite an existing SessionStorage without violating spec.
1458 // Attempts to do so may give a tab access to another tab's session storage
1459 // so die hard on an error.
1460 bool successful_insert
= session_storage_namespace_map_
.insert(
1461 make_pair(partition_id
,
1462 static_cast<SessionStorageNamespaceImpl
*>(
1463 session_storage_namespace
)))
1465 CHECK(successful_insert
) << "Cannot replace existing SessionStorageNamespace";
1468 void NavigationControllerImpl::SetMaxRestoredPageID(int32 max_id
) {
1469 max_restored_page_id_
= max_id
;
1472 int32
NavigationControllerImpl::GetMaxRestoredPageID() const {
1473 return max_restored_page_id_
;
1476 bool NavigationControllerImpl::IsUnmodifiedBlankTab() const {
1477 return IsInitialNavigation() &&
1478 !GetLastCommittedEntry() &&
1479 !delegate_
->HasAccessedInitialDocument();
1482 SessionStorageNamespace
*
1483 NavigationControllerImpl::GetSessionStorageNamespace(SiteInstance
* instance
) {
1484 std::string partition_id
;
1486 // TODO(ajwong): When GetDefaultSessionStorageNamespace() goes away, remove
1487 // this if statement so |instance| must not be NULL.
1489 GetContentClient()->browser()->GetStoragePartitionIdForSite(
1490 browser_context_
, instance
->GetSiteURL());
1493 SessionStorageNamespaceMap::const_iterator it
=
1494 session_storage_namespace_map_
.find(partition_id
);
1495 if (it
!= session_storage_namespace_map_
.end())
1496 return it
->second
.get();
1498 // Create one if no one has accessed session storage for this partition yet.
1500 // TODO(ajwong): Should this use the |partition_id| directly rather than
1501 // re-lookup via |instance|? http://crbug.com/142685
1502 StoragePartition
* partition
=
1503 BrowserContext::GetStoragePartition(browser_context_
, instance
);
1504 SessionStorageNamespaceImpl
* session_storage_namespace
=
1505 new SessionStorageNamespaceImpl(
1506 static_cast<DOMStorageContextWrapper
*>(
1507 partition
->GetDOMStorageContext()));
1508 session_storage_namespace_map_
[partition_id
] = session_storage_namespace
;
1510 return session_storage_namespace
;
1513 SessionStorageNamespace
*
1514 NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
1515 // TODO(ajwong): Remove if statement in GetSessionStorageNamespace().
1516 return GetSessionStorageNamespace(NULL
);
1519 const SessionStorageNamespaceMap
&
1520 NavigationControllerImpl::GetSessionStorageNamespaceMap() const {
1521 return session_storage_namespace_map_
;
1524 bool NavigationControllerImpl::NeedsReload() const {
1525 return needs_reload_
;
1528 void NavigationControllerImpl::SetNeedsReload() {
1529 needs_reload_
= true;
1531 if (last_committed_entry_index_
!= -1) {
1532 entries_
[last_committed_entry_index_
]->SetTransitionType(
1533 ui::PAGE_TRANSITION_RELOAD
);
1537 void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index
) {
1538 DCHECK(index
< GetEntryCount());
1539 DCHECK(index
!= last_committed_entry_index_
);
1541 DiscardNonCommittedEntries();
1543 entries_
.erase(entries_
.begin() + index
);
1544 if (last_committed_entry_index_
> index
)
1545 last_committed_entry_index_
--;
1548 void NavigationControllerImpl::DiscardNonCommittedEntries() {
1549 bool transient
= transient_entry_index_
!= -1;
1550 DiscardNonCommittedEntriesInternal();
1552 // If there was a transient entry, invalidate everything so the new active
1553 // entry state is shown.
1555 delegate_
->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL
);
1559 NavigationEntryImpl
* NavigationControllerImpl::GetPendingEntry() const {
1560 return pending_entry_
;
1563 int NavigationControllerImpl::GetPendingEntryIndex() const {
1564 return pending_entry_index_
;
1567 void NavigationControllerImpl::InsertOrReplaceEntry(NavigationEntryImpl
* entry
,
1569 DCHECK(entry
->GetTransitionType() != ui::PAGE_TRANSITION_AUTO_SUBFRAME
);
1571 // Copy the pending entry's unique ID to the committed entry.
1572 // I don't know if pending_entry_index_ can be other than -1 here.
1573 const NavigationEntryImpl
* const pending_entry
=
1574 (pending_entry_index_
== -1) ?
1575 pending_entry_
: entries_
[pending_entry_index_
].get();
1577 entry
->set_unique_id(pending_entry
->GetUniqueID());
1579 DiscardNonCommittedEntriesInternal();
1581 int current_size
= static_cast<int>(entries_
.size());
1582 DCHECK_IMPLIES(replace
, current_size
> 0);
1584 if (current_size
> 0) {
1585 // Prune any entries which are in front of the current entry.
1586 // Also prune the current entry if we are to replace the current entry.
1587 // last_committed_entry_index_ must be updated here since calls to
1588 // NotifyPrunedEntries() below may re-enter and we must make sure
1589 // last_committed_entry_index_ is not left in an invalid state.
1591 --last_committed_entry_index_
;
1594 while (last_committed_entry_index_
< (current_size
- 1)) {
1596 entries_
.pop_back();
1599 if (num_pruned
> 0) // Only notify if we did prune something.
1600 NotifyPrunedEntries(this, false, num_pruned
);
1603 PruneOldestEntryIfFull();
1605 entries_
.push_back(linked_ptr
<NavigationEntryImpl
>(entry
));
1606 last_committed_entry_index_
= static_cast<int>(entries_
.size()) - 1;
1608 // This is a new page ID, so we need everybody to know about it.
1609 delegate_
->UpdateMaxPageID(entry
->GetPageID());
1612 void NavigationControllerImpl::PruneOldestEntryIfFull() {
1613 if (entries_
.size() >= max_entry_count()) {
1614 DCHECK_EQ(max_entry_count(), entries_
.size());
1615 DCHECK_GT(last_committed_entry_index_
, 0);
1616 RemoveEntryAtIndex(0);
1617 NotifyPrunedEntries(this, true, 1);
1621 void NavigationControllerImpl::NavigateToPendingEntry(ReloadType reload_type
) {
1622 needs_reload_
= false;
1624 // If we were navigating to a slow-to-commit page, and the user performs
1625 // a session history navigation to the last committed page, RenderViewHost
1626 // will force the throbber to start, but WebKit will essentially ignore the
1627 // navigation, and won't send a message to stop the throbber. To prevent this
1628 // from happening, we drop the navigation here and stop the slow-to-commit
1629 // page from loading (which would normally happen during the navigation).
1630 if (pending_entry_index_
!= -1 &&
1631 pending_entry_index_
== last_committed_entry_index_
&&
1632 (entries_
[pending_entry_index_
]->restore_type() ==
1633 NavigationEntryImpl::RESTORE_NONE
) &&
1634 (entries_
[pending_entry_index_
]->GetTransitionType() &
1635 ui::PAGE_TRANSITION_FORWARD_BACK
)) {
1638 // If an interstitial page is showing, we want to close it to get back
1639 // to what was showing before.
1640 if (delegate_
->GetInterstitialPage())
1641 delegate_
->GetInterstitialPage()->DontProceed();
1643 DiscardNonCommittedEntries();
1647 // If an interstitial page is showing, the previous renderer is blocked and
1648 // cannot make new requests. Unblock (and disable) it to allow this
1649 // navigation to succeed. The interstitial will stay visible until the
1650 // resulting DidNavigate.
1651 if (delegate_
->GetInterstitialPage()) {
1652 static_cast<InterstitialPageImpl
*>(delegate_
->GetInterstitialPage())->
1653 CancelForNavigation();
1656 // For session history navigations only the pending_entry_index_ is set.
1657 if (!pending_entry_
) {
1658 DCHECK_NE(pending_entry_index_
, -1);
1659 pending_entry_
= entries_
[pending_entry_index_
].get();
1662 // This call does not support re-entrancy. See http://crbug.com/347742.
1663 CHECK(!in_navigate_to_pending_entry_
);
1664 in_navigate_to_pending_entry_
= true;
1665 bool success
= delegate_
->NavigateToPendingEntry(reload_type
);
1666 in_navigate_to_pending_entry_
= false;
1669 DiscardNonCommittedEntries();
1671 // If the entry is being restored and doesn't have a SiteInstance yet, fill
1672 // it in now that we know. This allows us to find the entry when it commits.
1673 if (pending_entry_
&& !pending_entry_
->site_instance() &&
1674 pending_entry_
->restore_type() != NavigationEntryImpl::RESTORE_NONE
) {
1675 pending_entry_
->set_site_instance(static_cast<SiteInstanceImpl
*>(
1676 delegate_
->GetPendingSiteInstance()));
1677 pending_entry_
->set_restore_type(NavigationEntryImpl::RESTORE_NONE
);
1681 void NavigationControllerImpl::NotifyNavigationEntryCommitted(
1682 LoadCommittedDetails
* details
) {
1683 details
->entry
= GetLastCommittedEntry();
1685 // We need to notify the ssl_manager_ before the web_contents_ so the
1686 // location bar will have up-to-date information about the security style
1687 // when it wants to draw. See http://crbug.com/11157
1688 ssl_manager_
.DidCommitProvisionalLoad(*details
);
1690 delegate_
->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL
);
1691 delegate_
->NotifyNavigationEntryCommitted(*details
);
1693 // TODO(avi): Remove. http://crbug.com/170921
1694 NotificationDetails notification_details
=
1695 Details
<LoadCommittedDetails
>(details
);
1696 NotificationService::current()->Notify(
1697 NOTIFICATION_NAV_ENTRY_COMMITTED
,
1698 Source
<NavigationController
>(this),
1699 notification_details
);
1703 size_t NavigationControllerImpl::max_entry_count() {
1704 if (max_entry_count_for_testing_
!= kMaxEntryCountForTestingNotSet
)
1705 return max_entry_count_for_testing_
;
1706 return kMaxSessionHistoryEntries
;
1709 void NavigationControllerImpl::SetActive(bool is_active
) {
1710 if (is_active
&& needs_reload_
)
1714 void NavigationControllerImpl::LoadIfNecessary() {
1718 // Calling Reload() results in ignoring state, and not loading.
1719 // Explicitly use NavigateToPendingEntry so that the renderer uses the
1721 pending_entry_index_
= last_committed_entry_index_
;
1722 NavigateToPendingEntry(NO_RELOAD
);
1725 void NavigationControllerImpl::NotifyEntryChanged(const NavigationEntry
* entry
,
1727 EntryChangedDetails det
;
1728 det
.changed_entry
= entry
;
1730 NotificationService::current()->Notify(
1731 NOTIFICATION_NAV_ENTRY_CHANGED
,
1732 Source
<NavigationController
>(this),
1733 Details
<EntryChangedDetails
>(&det
));
1736 void NavigationControllerImpl::FinishRestore(int selected_index
,
1738 DCHECK(selected_index
>= 0 && selected_index
< GetEntryCount());
1739 ConfigureEntriesForRestore(&entries_
, type
);
1741 SetMaxRestoredPageID(static_cast<int32
>(GetEntryCount()));
1743 last_committed_entry_index_
= selected_index
;
1746 void NavigationControllerImpl::DiscardNonCommittedEntriesInternal() {
1747 DiscardPendingEntry();
1748 DiscardTransientEntry();
1751 void NavigationControllerImpl::DiscardPendingEntry() {
1752 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
1753 // progress, since this will cause a use-after-free. (We only allow this
1754 // when the tab is being destroyed for shutdown, since it won't return to
1755 // NavigateToEntry in that case.) http://crbug.com/347742.
1756 CHECK(!in_navigate_to_pending_entry_
|| delegate_
->IsBeingDestroyed());
1758 if (pending_entry_index_
== -1)
1759 delete pending_entry_
;
1760 pending_entry_
= NULL
;
1761 pending_entry_index_
= -1;
1764 void NavigationControllerImpl::DiscardTransientEntry() {
1765 if (transient_entry_index_
== -1)
1767 entries_
.erase(entries_
.begin() + transient_entry_index_
);
1768 if (last_committed_entry_index_
> transient_entry_index_
)
1769 last_committed_entry_index_
--;
1770 transient_entry_index_
= -1;
1773 int NavigationControllerImpl::GetEntryIndexWithPageID(
1774 SiteInstance
* instance
, int32 page_id
) const {
1775 for (int i
= static_cast<int>(entries_
.size()) - 1; i
>= 0; --i
) {
1776 if ((entries_
[i
]->site_instance() == instance
) &&
1777 (entries_
[i
]->GetPageID() == page_id
))
1783 NavigationEntryImpl
* NavigationControllerImpl::GetTransientEntry() const {
1784 if (transient_entry_index_
== -1)
1786 return entries_
[transient_entry_index_
].get();
1789 void NavigationControllerImpl::SetTransientEntry(NavigationEntry
* entry
) {
1790 // Discard any current transient entry, we can only have one at a time.
1792 if (last_committed_entry_index_
!= -1)
1793 index
= last_committed_entry_index_
+ 1;
1794 DiscardTransientEntry();
1796 entries_
.begin() + index
, linked_ptr
<NavigationEntryImpl
>(
1797 NavigationEntryImpl::FromNavigationEntry(entry
)));
1798 transient_entry_index_
= index
;
1799 delegate_
->NotifyNavigationStateChanged(INVALIDATE_TYPE_ALL
);
1802 void NavigationControllerImpl::InsertEntriesFrom(
1803 const NavigationControllerImpl
& source
,
1805 DCHECK_LE(max_index
, source
.GetEntryCount());
1806 size_t insert_index
= 0;
1807 for (int i
= 0; i
< max_index
; i
++) {
1808 // When cloning a tab, copy all entries except interstitial pages
1809 if (source
.entries_
[i
].get()->GetPageType() !=
1810 PAGE_TYPE_INTERSTITIAL
) {
1811 entries_
.insert(entries_
.begin() + insert_index
++,
1812 linked_ptr
<NavigationEntryImpl
>(
1813 new NavigationEntryImpl(*source
.entries_
[i
])));
1818 void NavigationControllerImpl::SetGetTimestampCallbackForTest(
1819 const base::Callback
<base::Time()>& get_timestamp_callback
) {
1820 get_timestamp_callback_
= get_timestamp_callback
;
1823 } // namespace content