blob: abaf52f044143af2ce1449f9d2435e5ebc3f680f [file] [log] [blame]
Avi Drissman4e1b7bc32022-09-15 14:03:501// Copyright 2013 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
creis4e2ecb72015-06-20 00:46:305/*
6 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
9 * (http://www.torchmobile.com/)
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 *
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
21 * its contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
25 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
28 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35
danakjc492bf82020-09-09 20:02:4436#include "content/browser/renderer_host/navigation_controller_impl.h"
initial.commit09911bf2008-07-26 23:55:2937
Lei Zhang96031532019-10-10 19:05:4738#include <algorithm>
dcheng36b6aec92015-12-26 06:16:3639#include <utility>
40
[email protected]c5b88d82012-10-06 17:03:3341#include "base/bind.h"
[email protected]eabfe1912014-05-12 10:07:2842#include "base/command_line.h"
Ayu Ishii2f825852022-03-08 19:47:3843#include "base/containers/adapters.h"
Rakina Zata Amni627360d2022-02-24 00:53:4044#include "base/debug/dump_without_crashing.h"
initial.commit09911bf2008-07-26 23:55:2945#include "base/logging.h"
asvitkine30330812016-08-30 04:01:0846#include "base/metrics/histogram_macros.h"
Charlie Reis23c26da2022-01-29 00:57:4747#include "base/numerics/safe_conversions.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3948#include "base/strings/escape.h"
Peter Kastingb53b81912021-04-28 19:23:3049#include "base/strings/string_piece.h"
[email protected]348fbaac2013-06-11 06:31:5150#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0051#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3752#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0053#include "base/trace_event/optional_trace_event.h"
Carlos Caballeroede6f8c2021-01-28 11:01:5054#include "base/trace_event/trace_conversion_helper.h"
ssid3e765612015-01-28 04:03:4255#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0856#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5957#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2858#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1859#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3960#include "content/browser/blob_storage/chrome_blob_storage_context.h"
[email protected]825b1662012-03-12 19:07:3161#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4162#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0463#include "content/browser/dom_storage/session_storage_namespace_impl.h"
danakjc492bf82020-09-09 20:02:4464#include "content/browser/renderer_host/debug_urls.h"
65#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0066#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3367#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4468#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5769#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4470#include "content/browser/renderer_host/navigation_request.h"
71#include "content/browser/renderer_host/navigator.h"
72#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0073#include "content/browser/renderer_host/render_view_host_impl.h"
Sharon Yangd70a5392021-10-26 23:06:3274#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3375#include "content/browser/site_instance_impl.h"
Kunihiko Sakamoto346a74e2021-03-10 08:57:4876#include "content/browser/web_package/subresource_web_bundle_navigation_info.h"
Tsuyoshi Horo37493af2019-11-21 23:43:1477#include "content/browser/web_package/web_bundle_navigation_info.h"
Camille Lamy5193caa2018-10-12 11:59:4278#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5779#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5180#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1181#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1982#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1183#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4684#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0085#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3886#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1687#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4788#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5889#include "content/public/browser/render_widget_host.h"
90#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1091#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3492#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1993#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3894#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1095#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4796#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:4397#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:5998#include "media/base/mime_util.h"
Arthur Sonzogni620cec62018-12-13 13:08:5799#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18100#include "services/metrics/public/cpp/ukm_builders.h"
101#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17102#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37103#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44104#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58105#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39106#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30107#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21108#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06109#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43110#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50111#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31112#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51113#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
[email protected]cca6f392014-05-28 21:32:26114#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29115
[email protected]8ff00d72012-10-23 19:12:21116namespace content {
[email protected]e9ba4472008-09-14 15:42:43117namespace {
118
119// Invoked when entries have been pruned, or removed. For example, if the
120// current entries are [google, digg, yahoo], with the current entry google,
121// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47122void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50123 int index,
[email protected]c12bf1a12008-09-17 16:28:49124 int count) {
[email protected]8ff00d72012-10-23 19:12:21125 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50126 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49127 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14128 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43129}
130
[email protected]e9ba4472008-09-14 15:42:43131// Configure all the NavigationEntries in entries for restore. This resets
132// the transition type to reload and makes sure the content state isn't empty.
133void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57134 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48135 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47136 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43137 // Use a transition type of reload so that we don't incorrectly increase
138 // the typed count.
Lei Zhang96031532019-10-10 19:05:47139 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
140 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43141 }
142}
143
[email protected]bf70edce2012-06-20 22:32:22144// Determines whether or not we should be carrying over a user agent override
145// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57146bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22147 return last_entry && last_entry->GetIsOverridingUserAgent();
148}
149
Camille Lamy5193caa2018-10-12 11:59:42150// Determines whether to override user agent for a navigation.
151bool ShouldOverrideUserAgent(
152 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57153 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42154 switch (override_user_agent) {
155 case NavigationController::UA_OVERRIDE_INHERIT:
156 return ShouldKeepOverride(last_committed_entry);
157 case NavigationController::UA_OVERRIDE_TRUE:
158 return true;
159 case NavigationController::UA_OVERRIDE_FALSE:
160 return false;
Camille Lamy5193caa2018-10-12 11:59:42161 }
162 NOTREACHED();
163 return false;
164}
165
Rakina Zata Amni312822d72021-06-04 16:13:37166// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28167// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37168// link which results in a navigation to the last committed URL (but wasn't
169// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04170// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
171// |base_url_for_data_url|, |transition_type| correspond to the new navigation
172// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
173// navigation that committed.
174bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
175 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57176 const GURL& virtual_url,
177 const GURL& base_url_for_data_url,
178 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57179 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37180 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57181 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37182 // Navigations intended to do a replacement shouldn't be converted to do a
183 // reload.
184 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28185 return false;
clamy0a656e42018-02-06 18:18:28186 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45187 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55188 return false;
189
arthursonzogni7a8243682017-12-14 16:41:42190 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28191 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42192 return false;
193
ananta3bdd8ae2016-12-22 17:11:55194 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
195 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
196 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28197 bool transition_type_can_be_converted = false;
198 if (ui::PageTransitionCoreTypeIs(transition_type,
199 ui::PAGE_TRANSITION_RELOAD) &&
200 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
201 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55202 }
clamy0a656e42018-02-06 18:18:28203 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55204 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28205 transition_type_can_be_converted = true;
206 }
207 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
208 transition_type_can_be_converted = true;
209 if (!transition_type_can_be_converted)
210 return false;
211
212 // This check is required for cases like view-source:, etc. Here the URL of
213 // the navigation entry would contain the url of the page, while the virtual
214 // URL contains the full URL including the view-source prefix.
215 if (virtual_url != last_committed_entry->GetVirtualURL())
216 return false;
217
Fergal Daly766177d2020-07-07 07:54:04218 // Check that the URLs match.
219 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
220 // If there's no frame entry then by definition the URLs don't match.
221 if (!frame_entry)
222 return false;
223
224 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28225 return false;
226
227 // This check is required for Android WebView loadDataWithBaseURL. Apps
228 // can pass in anything in the base URL and we need to ensure that these
229 // match before classifying it as a reload.
230 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
231 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
232 return false;
ananta3bdd8ae2016-12-22 17:11:55233 }
234
clamy0a656e42018-02-06 18:18:28235 // Skip entries with SSL errors.
236 if (last_committed_entry->ssl_error())
237 return false;
238
239 // Don't convert to a reload when the last navigation was a POST or the new
240 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04241 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28242 return false;
243
244 return true;
ananta3bdd8ae2016-12-22 17:11:55245}
246
Anton Bikineevf62d1bf2021-05-15 17:56:07247absl::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12248 const mojom::DidCommitProvisionalLoadParams& params,
249 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32250 // Error pages commit in an opaque origin, yet have the real URL that resulted
251 // in an error as the |params.url|. Since successful reload of an error page
252 // should commit in the correct origin, setting the opaque origin on the
253 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17254 if (request && request->DidEncounterError())
Anton Bikineevf62d1bf2021-05-15 17:56:07255 return absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:32256
Anton Bikineevf62d1bf2021-05-15 17:56:07257 return absl::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32258}
259
Camille Lamy5193caa2018-10-12 11:59:42260bool IsValidURLForNavigation(bool is_main_frame,
261 const GURL& virtual_url,
262 const GURL& dest_url) {
263 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
264 if (is_main_frame && !virtual_url.is_valid() && !virtual_url.is_empty()) {
265 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
266 << virtual_url.possibly_invalid_spec();
267 return false;
268 }
269
270 // Don't attempt to navigate to non-empty invalid URLs.
271 if (!dest_url.is_valid() && !dest_url.is_empty()) {
272 LOG(WARNING) << "Refusing to load invalid URL: "
273 << dest_url.possibly_invalid_spec();
274 return false;
275 }
276
277 // The renderer will reject IPC messages with URLs longer than
278 // this limit, so don't attempt to navigate with a longer URL.
279 if (dest_url.spec().size() > url::kMaxURLChars) {
280 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
281 << " characters.";
282 return false;
283 }
284
Aaron Colwell33109c592020-04-21 21:31:19285 // Reject renderer debug URLs because they should have been handled before
286 // we get to this point. This check handles renderer debug URLs
287 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
288 // provides defense-in-depth if a renderer debug URL manages to get here via
289 // some other path. We want to reject the navigation here so it doesn't
290 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30291 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19292 LOG(WARNING) << "Refusing to load renderer debug URL: "
293 << dest_url.possibly_invalid_spec();
294 return false;
295 }
296
Camille Lamy5193caa2018-10-12 11:59:42297 return true;
298}
299
Mikel Astizba9cf2fd2017-12-17 10:38:10300// See replaced_navigation_entry_data.h for details: this information is meant
301// to ensure |*output_entry| keeps track of its original URL (landing page in
302// case of server redirects) as it gets replaced (e.g. history.replaceState()),
303// without overwriting it later, for main frames.
304void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57305 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10306 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17307 if (output_entry->GetReplacedEntryData().has_value() ||
308 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10309 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17310 }
Mikel Astizba9cf2fd2017-12-17 10:38:10311
312 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57313 data.first_committed_url = replaced_entry->GetURL();
314 data.first_timestamp = replaced_entry->GetTimestamp();
315 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29316 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10317}
318
Minggang Wangb9f3fa92021-07-01 15:30:31319blink::mojom::NavigationType GetNavigationType(
320 const GURL& old_url,
321 const GURL& new_url,
322 ReloadType reload_type,
323 NavigationEntryImpl* entry,
324 const FrameNavigationEntry& frame_entry,
325 bool has_pending_cross_document_commit,
326 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49327 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13328 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49329 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23330 // Reload navigations
331 switch (reload_type) {
332 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31333 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23334 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31335 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23336 case ReloadType::ORIGINAL_REQUEST_URL:
Minggang Wangb9f3fa92021-07-01 15:30:31337 return blink::mojom::NavigationType::RELOAD_ORIGINAL_REQUEST_URL;
clamyea99ea12018-05-28 13:54:23338 case ReloadType::NONE:
339 break; // Fall through to rest of function.
340 }
341
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08342 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31343 return entry->GetHasPostData()
344 ? blink::mojom::NavigationType::RESTORE_WITH_POST
345 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23346 }
347
danakjb952ef12021-01-14 19:58:49348 const bool can_be_same_document =
349 // A pending cross-document commit means this navigation will not occur in
350 // the current document, as that document would end up being replaced in
351 // the meantime.
352 !has_pending_cross_document_commit &&
353 // If the current document is an error page, we should always treat it as
354 // a different-document navigation so that we'll attempt to load the
355 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49356 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13357 // If the navigation is an embedder-initiated navigation of a fenced
358 // frame root (i.e. enters a fenced frame tree from outside),
359 // same-document navigations should be disabled because we don't want to
360 // allow information to be joined across multiple embedder-initiated
361 // fenced frame navigations (which may contain separate cross-site data).
362 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49363 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
364 // same-document navigations should be disabled because we want to force
365 // the creation of a new browsing context group.
366 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12367
clamyea99ea12018-05-28 13:54:23368 // History navigations.
369 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12370 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31371 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
372 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23373 }
374 DCHECK(!is_same_document_history_load);
375
376 // A same-document fragment-navigation happens when the only part of the url
377 // that is modified is after the '#' character.
378 //
379 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12380 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23381 //
382 // Note: this check is only valid for navigations that are not history
383 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
384 // history navigation from 'A#foo' to 'A#bar' is not a same-document
385 // navigation, but a different-document one. This is why history navigation
386 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47387 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
388 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12389
390 // The one case where we do the wrong thing here and incorrectly choose
391 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
392 // the renderer is a frameset. All frameset navigations should be
393 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
394 // navigation would do the right thing, as it would send it to the browser and
395 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
396 // into this method). But since we can't tell that case here for browser-
397 // initiated navigations, we have to get the renderer involved. In that case
398 // the navigation would be restarted due to the renderer spending a reply of
399 // mojom::CommitResult::RestartCrossDocument.
400
401 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31402 ? blink::mojom::NavigationType::SAME_DOCUMENT
403 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23404}
405
Camille Lamy5193caa2018-10-12 11:59:42406// Adjusts the original input URL if needed, to get the URL to actually load and
407// the virtual URL, which may differ.
408void RewriteUrlForNavigation(const GURL& original_url,
409 BrowserContext* browser_context,
410 GURL* url_to_load,
411 GURL* virtual_url,
412 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42413 // Allow the browser URL handler to rewrite the URL. This will, for example,
414 // remove "view-source:" from the beginning of the URL to get the URL that
415 // will actually be loaded. This real URL won't be shown to the user, just
416 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31417 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42418 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
419 url_to_load, browser_context, reverse_on_redirect);
420}
421
422#if DCHECK_IS_ON()
423// Helper sanity check function used in debug mode.
424void ValidateRequestMatchesEntry(NavigationRequest* request,
425 NavigationEntryImpl* entry) {
426 if (request->frame_tree_node()->IsMainFrame()) {
427 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
428 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31429 ui::PageTransitionFromInt(request->common_params().transition),
430 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42431 }
Nasko Oskovc36327d2019-01-03 23:23:04432 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42433 entry->should_clear_history_list());
434 DCHECK_EQ(request->common_params().has_user_gesture,
435 entry->has_user_gesture());
436 DCHECK_EQ(request->common_params().base_url_for_data_url,
437 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04438 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42439 entry->GetCanLoadLocalResources());
440 DCHECK_EQ(request->common_params().started_from_context_menu,
441 entry->has_started_from_context_menu());
442
443 FrameNavigationEntry* frame_entry =
444 entry->GetFrameEntry(request->frame_tree_node());
445 if (!frame_entry) {
446 NOTREACHED();
447 return;
448 }
449
Camille Lamy5193caa2018-10-12 11:59:42450 DCHECK_EQ(request->common_params().method, frame_entry->method());
451
Nasko Oskovc36327d2019-01-03 23:23:04452 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42453 if (redirect_size == frame_entry->redirect_chain().size()) {
454 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04455 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42456 frame_entry->redirect_chain()[i]);
457 }
458 } else {
459 NOTREACHED();
460 }
461}
462#endif // DCHECK_IS_ON()
463
Dave Tapuska8bfd84c2019-03-26 20:47:16464// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20465// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16466bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20467 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16468 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20469 DCHECK(sandboxed_initiator_rfh);
470 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
471 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16472 for (auto& item : navigations) {
473 bool within_subtree = false;
474 // Check whether this NavigationRequest affects a frame within the
475 // sandboxed frame's subtree by walking up the tree looking for the
476 // sandboxed frame.
477 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03478 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20479 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16480 within_subtree = true;
481 break;
482 }
483 }
484 if (!within_subtree)
485 return false;
486 }
487 return true;
488}
489
[email protected]e9ba4472008-09-14 15:42:43490} // namespace
491
arthursonzogni66f711c2019-10-08 14:40:36492// NavigationControllerImpl::PendingEntryRef------------------------------------
493
494NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
495 base::WeakPtr<NavigationControllerImpl> controller)
496 : controller_(controller) {}
497
498NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
499 if (!controller_) // Can be null with interstitials.
500 return;
501
502 controller_->PendingEntryRefDeleted(this);
503}
504
[email protected]d202a7c2012-01-04 07:53:47505// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29506
[email protected]23a918b2014-07-15 09:51:36507const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23508
[email protected]765b35502008-08-21 00:51:20509// static
[email protected]d202a7c2012-01-04 07:53:47510size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23511 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20512
[email protected]e6fec472013-05-14 05:29:02513// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20514// when testing.
515static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29516
[email protected]71fde352011-12-29 03:29:56517// static
dcheng9bfa5162016-04-09 01:00:57518std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
519 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10520 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07521 absl::optional<url::Origin> initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:10522 ui::PageTransition transition,
523 bool is_renderer_initiated,
524 const std::string& extra_headers,
525 BrowserContext* browser_context,
526 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
527 return NavigationControllerImpl::CreateNavigationEntry(
528 url, referrer, std::move(initiator_origin),
529 nullptr /* source_site_instance */, transition, is_renderer_initiated,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17530 extra_headers, browser_context, std::move(blob_url_loader_factory),
531 true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10532}
533
534// static
535std::unique_ptr<NavigationEntryImpl>
536NavigationControllerImpl::CreateNavigationEntry(
537 const GURL& url,
538 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07539 absl::optional<url::Origin> initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:10540 SiteInstance* source_site_instance,
dcheng9bfa5162016-04-09 01:00:57541 ui::PageTransition transition,
542 bool is_renderer_initiated,
543 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09544 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17545 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
546 bool rewrite_virtual_urls) {
547 GURL url_to_load = url;
548 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56549 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17550 if (rewrite_virtual_urls) {
551 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
552 &reverse_on_redirect);
553 }
Lukasz Anforowicz641234d52019-11-07 21:07:10554 // Let the NTP override the navigation params and pretend that this is a
555 // browser-initiated, bookmark-like navigation.
556 GetContentClient()->browser()->OverrideNavigationParams(
Scott Violetcf6ea7e2021-06-09 21:09:21557 source_site_instance, &transition, &is_renderer_initiated, &referrer,
558 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10559
Patrick Monettef507e982019-06-19 20:18:06560 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28561 nullptr, // The site instance for tabs is sent on navigation
562 // (WebContents::GetSiteInstance).
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:58563 url_to_load, referrer, initiator_origin, std::u16string(), transition,
Rakina Zata Amniafd3c6582021-11-30 06:19:17564 is_renderer_initiated, blob_url_loader_factory,
565 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42566 entry->SetVirtualURL(virtual_url);
567 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56568 entry->set_update_virtual_url_with_url(reverse_on_redirect);
569 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06570 return entry;
[email protected]71fde352011-12-29 03:29:56571}
572
[email protected]cdcb1dee2012-01-04 00:46:20573// static
574void NavigationController::DisablePromptOnRepost() {
575 g_check_for_repost = false;
576}
577
[email protected]c5b88d82012-10-06 17:03:33578base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
579 base::Time t) {
580 // If |t| is between the water marks, we're in a run of duplicates
581 // or just getting out of it, so increase the high-water mark to get
582 // a time that probably hasn't been used before and return it.
583 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35584 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33585 return high_water_mark_;
586 }
587
588 // Otherwise, we're clear of the last duplicate run, so reset the
589 // water marks.
590 low_water_mark_ = high_water_mark_ = t;
591 return t;
592}
593
ckitagawa0faa5e42020-06-17 17:30:54594NavigationControllerImpl::ScopedShowRepostDialogForTesting::
595 ScopedShowRepostDialogForTesting()
596 : was_disallowed_(g_check_for_repost) {
597 g_check_for_repost = true;
598}
599
600NavigationControllerImpl::ScopedShowRepostDialogForTesting::
601 ~ScopedShowRepostDialogForTesting() {
602 g_check_for_repost = was_disallowed_;
603}
604
Nate Chapin9eb16be72022-09-23 22:54:31605NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
606 base::SafeRef<NavigationControllerImpl> controller)
607 : controller_(controller) {
608 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
609 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
610 frame_tree_node_id_to_keys_.insert(
611 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
612 if (auto* frame_entry = frame_tree_node->current_frame_host()
613 ->last_committed_frame_entry()) {
614 frame_tree_node_id_to_doc_seq_nos_.insert(
615 {frame_tree_node->frame_tree_node_id(),
616 frame_entry->document_sequence_number()});
617 }
618 }
619 PopulateKeySet(Direction::kBack);
620 PopulateKeySet(Direction::kForward);
621}
622
623void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
624 Direction direction) {
625 // Keep track of which FrameTreeNodes may still have relevant API keys in
626 // additional FrameNavigationEntries.
627 std::set<FrameTreeNode*> nodes_to_process;
628 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
629 nodes_to_process.insert(node);
630 }
631
632 const int offset = direction == Direction::kForward ? 1 : -1;
633 const int start = direction == Direction::kForward
634 ? controller_->GetLastCommittedEntryIndex()
635 : controller_->GetLastCommittedEntryIndex() - 1;
636 for (int i = start;
637 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
638 i += offset) {
639 std::set<FrameTreeNode*> nodes_to_continue_processing;
640
641 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
642 entry->ForEachFrameEntry([this, &nodes_to_process,
643 &nodes_to_continue_processing,
644 &entry](FrameNavigationEntry* frame_entry) {
645 // Find the |node| that matches |frame_entry|, if any.
646 FrameTreeNode* node = nullptr;
647 if (frame_entry == entry->root_node()->frame_entry) {
648 node = controller_->frame_tree().root();
649 } else {
650 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
651 if (it == names_to_nodes_.end())
652 return;
653 node = it->second;
654 }
655
656 // Skip this node if a previous step determine there are no longer
657 // relevant navigation API keys in this direction.
658 if (nodes_to_process.find(node) == nodes_to_process.end())
659 return;
660
661 // Stop processing |node| if we reach a point where it's cross-origin.
662 // See also PopulateSingleNavigationApiHistoryEntryVector().
663 url::Origin frame_entry_origin =
664 frame_entry->committed_origin().value_or(url::Origin::Resolve(
665 frame_entry->url(),
666 frame_entry->initiator_origin().value_or(url::Origin())));
667 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
668 return;
669
670 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
671 frame_entry->navigation_api_key());
672 // Mark |node| as needing more processing for the next entry.
673 nodes_to_continue_processing.insert(node);
674
675 // Check whether |node| went cross-document. If so, its children are
676 // no longer the same conceptual iframe as the current one, and
677 // should no longer be processed. This check is intentionally done
678 // after processing the current |node|, which may still have relevant
679 // discarded API keys.
680 if (frame_entry->document_sequence_number() !=
681 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
682 for (auto* descendant : node->frame_tree()->SubtreeNodes(node))
683 nodes_to_process.erase(descendant);
684 }
685 });
686
687 nodes_to_process.swap(nodes_to_continue_processing);
688 }
689}
690
691NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
692 std::set<std::string> all_keys;
693 // Find all remaining navigation API keys after some entries have been
694 // removed.
695 for (auto& entry : controller_->entries_) {
696 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
697 all_keys.insert(frame_entry->navigation_api_key());
698 });
699 }
700
701 // Notify each frame in the renderer of any disposed navigation API keys.
702 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
703 std::vector<std::string> disposed_keys;
704 for (const auto& key : id_to_keys.second) {
705 if (all_keys.find(key) == all_keys.end())
706 disposed_keys.push_back(key);
707 }
708 if (disposed_keys.empty())
709 continue;
710
711 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
712 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
713 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
714 }
715}
716
[email protected]d202a7c2012-01-04 07:53:47717NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00718 BrowserContext* browser_context,
719 FrameTree& frame_tree,
720 NavigationControllerDelegate* delegate)
721 : frame_tree_(frame_tree),
722 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57723 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22724 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47725 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37726 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29727}
728
[email protected]d202a7c2012-01-04 07:53:47729NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00730 // The NavigationControllerImpl might be called inside its delegate
731 // destructor. Calling it is not valid anymore.
732 delegate_ = nullptr;
733 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29734}
735
Matt Falkenhagen548ed1562021-07-06 01:38:26736WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
737 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32738}
739
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57740BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55741 return browser_context_;
742}
743
[email protected]d202a7c2012-01-04 07:53:47744void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30745 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36746 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57747 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47748 // Note that it's possible for `entries_` to contain multiple entries at this
749 // point, as Restore() might be called on a NavigationController that is
750 // already used (e.g. due to WebView's restoreState() API), not only for fresh
751 // NavigationControllers. These entries are not cleared to preserve legacy
752 // behavior and also because `pending_entry_` might point to one of the
753 // pre-existing entries. An exception for this is when `entries_` contains
754 // only the initial NavigationEntry, which must be removed.
755
756 // Do not proceed if selected_navigation will be out of bounds for the updated
757 // entries_ list, since it will be assigned to last_committed_entry_index_ and
758 // used to index entries_.
759 // TODO(https://crbug.com/1287624): Consider also returning early if entries
760 // is empty, since there should be no work to do (rather than marking the
761 // existing entries as needing reload). Also consider returning early if the
762 // selected index is -1, which represents a no-committed-entry state.
763 if (selected_navigation < -1 ||
764 selected_navigation >=
765 base::checked_cast<int>(entries->size() + entries_.size())) {
766 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24767 }
Charlie Reis23c26da2022-01-29 00:57:47768
Rakina Zata Amni46087a12022-11-11 08:28:38769 // There will always be at least one entry (new NavigationControllers will
770 // have the initial NavigationEntry).
771 if (selected_navigation == -1)
772 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47773
Rakina Zata Amni46087a12022-11-11 08:28:38774 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
775 // If we are on the initial NavigationEntry, it must be the only entry in
776 // the list. Since it's impossible to do a history navigation to the
777 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
778 // `pending_entry` might be set for a new non-history navigation).
779 // Note that we should not clear `entries_` if `entries` is empty (when
780 // InitialNavigationEntry mode is enabled), since that would leave us
781 // without any NavigationEntry.
782 CHECK_EQ(1, GetEntryCount());
783 CHECK_EQ(-1, pending_entry_index_);
784 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47785 }
[email protected]ce3fa3c2009-04-20 19:55:57786
[email protected]ce3fa3c2009-04-20 19:55:57787 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44788 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03789 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47790 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43791 if (entry->GetURL().is_empty()) {
792 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01793 // persisting the initial NavigationEntry [which is no longer possible but
794 // some old persisted sessions might still contain it] or when the
795 // serializer failed to write the URL because it's too long). Trying to
796 // restore and navigate to an entry with an empty URL will result in
797 // crashes, so change the URL to about:blank. See also
798 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43799 entry->SetURL(GURL(url::kAboutBlankURL));
800 }
dcheng36b6aec92015-12-26 06:16:36801 entries_.push_back(
802 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47803 }
avif16f85a72015-11-13 18:25:03804
805 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
806 // cleared out safely.
807 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57808
809 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36810 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57811}
812
toyoshim6142d96f2016-12-19 09:07:25813void NavigationControllerImpl::Reload(ReloadType reload_type,
814 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03815 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
816 (int)reload_type);
817 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
818 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28819 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28820 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32821 int current_index = -1;
822
Carlos IL42b416592019-10-07 23:10:36823 if (entry_replaced_by_post_commit_error_) {
824 // If there is an entry that was replaced by a currently active post-commit
825 // error navigation, this can't be the initial navigation.
826 DCHECK(!IsInitialNavigation());
827 // If the current entry is a post commit error, we reload the entry it
828 // replaced instead. We leave the error entry in place until a commit
829 // replaces it, but the pending entry points to the original entry in the
830 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
831 // case that pending_entry_ != entries_[pending_entry_index_].
832 entry = entry_replaced_by_post_commit_error_.get();
833 current_index = GetCurrentEntryIndex();
834 } else if (IsInitialNavigation() && pending_entry_) {
835 // If we are reloading the initial navigation, just use the current
836 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32837 entry = pending_entry_;
838 // The pending entry might be in entries_ (e.g., after a Clone), so we
839 // should also update the current_index.
840 current_index = pending_entry_index_;
841 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00842 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32843 current_index = GetCurrentEntryIndex();
844 if (current_index != -1) {
creis3da03872015-02-20 21:12:32845 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32846 }
[email protected]979a4bc2013-04-24 01:27:15847 }
[email protected]241db352013-04-22 18:04:05848
[email protected]59167c22013-06-03 18:07:32849 // If we are no where, then we can't reload. TODO(darin): We should add a
850 // CanReload method.
851 if (!entry)
852 return;
853
Rakina Zata Amnif297a802022-01-18 03:53:43854 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
855 // We should never navigate to an existing initial NavigationEntry that is
856 // the initial NavigationEntry for the initial empty document that hasn't
857 // been overridden by the synchronous about:blank commit, to preserve
858 // legacy behavior where trying to reload when the main frame is on the
859 // initial empty document won't result in a navigation. See also
860 // https://crbug.com/1277414.
861 return;
862 }
863
Aran Gilman37d11632019-10-08 23:07:15864 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30865 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07866 // they really want to do this. If they do, the dialog will call us back
867 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57868 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02869
[email protected]106a0812010-03-18 00:15:12870 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57871 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47872 return;
initial.commit09911bf2008-07-26 23:55:29873 }
Lei Zhang96031532019-10-10 19:05:47874
Wang Huia25efabc2022-09-24 17:27:22875 // Set ReloadType for |entry|.
876 entry->set_reload_type(reload_type);
877
Lei Zhang96031532019-10-10 19:05:47878 if (!IsInitialNavigation())
879 DiscardNonCommittedEntries();
880
881 pending_entry_ = entry;
882 pending_entry_index_ = current_index;
883 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
884
Nate Chapin45f620582021-09-30 17:45:43885 // location.reload() goes through BeginNavigation, so all reloads triggered
886 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13887 NavigateToExistingPendingEntry(
888 reload_type,
889 /*initiator_rfh=*/nullptr,
890 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
891 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29892}
893
[email protected]d202a7c2012-01-04 07:53:47894void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48895 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12896}
897
[email protected]d202a7c2012-01-04 07:53:47898void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49899 // If the pending reload type has been cleared by another navigation
900 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48901 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49902 return;
[email protected]106a0812010-03-18 00:15:12903 }
Wang Hui96ab1012022-10-11 02:05:49904 Reload(pending_reload_, false);
905 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12906}
907
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57908bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09909 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11910}
911
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57912bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38913 // Check that we're on the initial NavigationEntry and that this is not a
914 // cloned tab.
915 return IsInitialNavigation() && GetEntryCount() == 1 &&
916 GetLastCommittedEntry()->IsInitialEntry() &&
917 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40918}
919
Aran Gilman37d11632019-10-08 23:07:15920NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
921 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58922 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03923 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58924}
925
Adithya Srinivasan9b0c99c2021-08-10 15:19:45926NavigationEntryImpl*
927NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
928 int nav_entry_id) const {
929 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
930 if (entry)
931 return entry;
932 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52933 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45934 : nullptr;
935}
936
W. James MacLeanc07dc41b2022-07-25 18:52:16937void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57938 const url::Origin& origin) {
939 for (int i = 0; i < GetEntryCount(); i++) {
940 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16941 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57942 }
943 if (entry_replaced_by_post_commit_error_) {
944 // It's possible we could come back to this entry if the error
945 // page/interstitial goes away.
946 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16947 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57948 }
W. James MacLean1c40862c2020-04-27 21:05:57949}
950
avi25764702015-06-23 15:43:37951void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57952 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00953 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37954 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27955 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20956}
957
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57958NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47959 if (pending_entry_)
960 return pending_entry_;
961 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20962}
963
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57964NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32965 // The pending entry is safe to return for new (non-history), browser-
966 // initiated navigations. Most renderer-initiated navigations should not
967 // show the pending entry, to prevent URL spoof attacks.
968 //
969 // We make an exception for renderer-initiated navigations in new tabs, as
970 // long as no other page has tried to access the initial empty document in
971 // the new tab. If another page modifies this blank page, a URL spoof is
972 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:32973 bool safe_to_show_pending =
974 pending_entry_ &&
975 // Require a new navigation.
avi0dca04d2015-01-26 20:21:09976 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:32977 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:46978 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:32979
980 // Also allow showing the pending entry for history navigations in a new tab,
981 // such as Ctrl+Back. In this case, no existing page is visible and no one
982 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:15983 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
984 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:32985 safe_to_show_pending = true;
986
987 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:19988 return pending_entry_;
989 return GetLastCommittedEntry();
990}
991
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57992int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:20993 if (pending_entry_index_ != -1)
994 return pending_entry_index_;
995 return last_committed_entry_index_;
996}
997
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57998NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:38999 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031000 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201001}
1002
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571003bool NavigationControllerImpl::CanViewSource() {
Jeremy Roman2d8dfe132021-07-06 20:51:261004 const std::string& mime_type =
Ali Hijazid87307d2022-11-07 20:15:031005 frame_tree_->root()->current_frame_host()->GetPage().contents_mime_type();
Kinuko Yasuda74702f92017-07-31 03:27:531006 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1007 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271008 NavigationEntry* visible_entry = GetVisibleEntry();
1009 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391010 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161011}
1012
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571013int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271014 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451015 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271016 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551017 return last_committed_entry_index_;
1018}
1019
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571020int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451021 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291022 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551023 return static_cast<int>(entries_.size());
1024}
1025
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571026NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371027 if (index < 0 || index >= GetEntryCount())
1028 return nullptr;
1029
avif16f85a72015-11-13 18:25:031030 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251031}
1032
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571033NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471034 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201035}
1036
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571037int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461038 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031039}
1040
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571041bool NavigationControllerImpl::CanGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031042 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
1043 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1044 return true;
1045 }
1046 return false;
[email protected]765b35502008-08-21 00:51:201047}
1048
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571049bool NavigationControllerImpl::CanGoForward() {
WangHui74286d52021-03-31 16:17:151050 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1051 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1052 return true;
1053 }
1054 return false;
[email protected]765b35502008-08-21 00:51:201055}
1056
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571057bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031058 int index = GetIndexForOffset(offset);
1059 return index >= 0 && index < GetEntryCount();
1060}
1061
Xiaohan Wang7f8052e02022-01-14 18:44:281062#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151063bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151064 if (offset == 0)
1065 return true;
1066 int increment = offset > 0 ? 1 : -1;
1067 int non_skippable_entries = 0;
1068 for (int index = GetIndexForOffset(increment);
1069 index >= 0 && index < GetEntryCount(); index += increment) {
1070 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1071 non_skippable_entries++;
1072
1073 if (non_skippable_entries == std::abs(offset))
1074 return true;
1075 }
1076 return false;
1077}
1078#endif
1079
[email protected]d202a7c2012-01-04 07:53:471080void NavigationControllerImpl::GoBack() {
shivanisha55201872018-12-13 04:29:061081 int target_index = GetIndexForOffset(-1);
1082
Elly Fong-Jones40ee8112021-06-23 19:10:521083 // Move the target index past the skippable entries.
Shivani Sharma298d12852019-01-22 20:04:031084 bool all_skippable_entries = true;
Elly Fong-Jones40ee8112021-06-23 19:10:521085 while (target_index >= 0) {
1086 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui()) {
Shivani Sharma298d12852019-01-22 20:04:031087 all_skippable_entries = false;
shivanisha55201872018-12-13 04:29:061088 break;
Shivani Sharma2d5b4b6b2019-01-08 16:07:161089 }
Elly Fong-Jones40ee8112021-06-23 19:10:521090 target_index--;
shivanisha55201872018-12-13 04:29:061091 }
Miyoung Shin1c565c912021-03-17 12:11:211092
Shivani Sharma298d12852019-01-22 20:04:031093 // Do nothing if all entries are skippable. Normally this path would not
1094 // happen as consumers would have already checked it in CanGoBack but a lot of
1095 // tests do not do that.
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421096 if (all_skippable_entries)
Shivani Sharma298d12852019-01-22 20:04:031097 return;
shivanisha55201872018-12-13 04:29:061098
shivanisha55201872018-12-13 04:29:061099 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201100}
1101
[email protected]d202a7c2012-01-04 07:53:471102void NavigationControllerImpl::GoForward() {
shivanisha55201872018-12-13 04:29:061103 int target_index = GetIndexForOffset(1);
1104
Shivani Sharma2d5b4b6b2019-01-08 16:07:161105 // Note that at least one entry (the last one) will be non-skippable since
1106 // entries are marked skippable only when they add another entry because of
1107 // redirect or pushState.
Elly Fong-Jones40ee8112021-06-23 19:10:521108 while (target_index < static_cast<int>(entries_.size())) {
1109 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui())
shivanisha55201872018-12-13 04:29:061110 break;
Elly Fong-Jones40ee8112021-06-23 19:10:521111 target_index++;
shivanisha55201872018-12-13 04:29:061112 }
shivanisha55201872018-12-13 04:29:061113 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201114}
1115
[email protected]d202a7c2012-01-04 07:53:471116void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131117 GoToIndex(index, /*initiator_rfh=*/nullptr,
1118 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1119 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161120}
1121
Nate Chapinbf682fa32022-09-26 22:41:201122void NavigationControllerImpl::GoToIndex(
1123 int index,
1124 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131125 absl::optional<blink::scheduler::TaskAttributionId>
1126 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201127 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031128 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441129 TRACE_EVENT0("browser,navigation,benchmark",
1130 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201131 if (index < 0 || index >= static_cast<int>(entries_.size())) {
1132 NOTREACHED();
1133 return;
1134 }
1135
Rakina Zata Amnif297a802022-01-18 03:53:431136 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1137 // We should never navigate to an existing initial NavigationEntry that is
1138 // the initial NavigationEntry for the initial empty document that hasn't
1139 // been overridden by the synchronous about:blank commit, to preserve
1140 // legacy behavior where trying to reload when the main frame is on the
1141 // initial empty document won't result in a navigation. See also
1142 // https://crbug.com/1277414.
1143 return;
1144 }
1145
[email protected]cbab76d2008-10-13 22:42:471146 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201147
arthursonzogni5c4c202d2017-04-25 23:41:271148 DCHECK_EQ(nullptr, pending_entry_);
1149 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431150
arthursonzogni5c4c202d2017-04-25 23:41:271151 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201152 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271153 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1154 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201155 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131156 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201157 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201158}
1159
[email protected]d202a7c2012-01-04 07:53:471160void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121161 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031162 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201163 return;
1164
[email protected]9ba14052012-06-22 23:50:031165 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201166}
1167
Nate Chapinbf682fa32022-09-26 22:41:201168void NavigationControllerImpl::GoToOffsetFromRenderer(
1169 int offset,
Yoav Weiss8c573952022-11-17 17:35:131170 RenderFrameHostImpl* initiator_rfh,
1171 absl::optional<blink::scheduler::TaskAttributionId>
1172 soft_navigation_heuristics_task_id) {
Nate Chapin45f620582021-09-30 17:45:431173 // Note: This is actually reached in unit tests.
1174 if (!CanGoToOffset(offset))
1175 return;
1176
Nate Chapinbf682fa32022-09-26 22:41:201177 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131178 soft_navigation_heuristics_task_id,
1179 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431180}
1181
Xiaohan Wang7f8052e02022-01-14 18:44:281182#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151183void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1184 // Note: This is actually reached in unit tests.
1185 if (!CanGoToOffsetWithSkipping(offset))
1186 return;
1187
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421188 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151189 GoToIndex(GetIndexForOffset(offset));
1190 return;
1191 }
1192 int increment = offset > 0 ? 1 : -1;
1193 // Find the offset without counting skippable entries.
1194 int target_index = GetIndexForOffset(increment);
1195 int non_skippable_entries = 0;
1196 for (int index = target_index; index >= 0 && index < GetEntryCount();
1197 index += increment) {
1198 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1199 non_skippable_entries++;
1200
1201 if (non_skippable_entries == std::abs(offset)) {
1202 target_index = index;
1203 break;
1204 }
1205 }
1206
1207 GoToIndex(target_index);
1208}
1209#endif
1210
[email protected]41374f12013-07-24 02:49:281211bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151212 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281213 return false;
[email protected]6a13a6c2011-12-20 21:47:121214
[email protected]43032342011-03-21 14:10:311215 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281216 return true;
[email protected]cbab76d2008-10-13 22:42:471217}
1218
Michael Thiessen9b14d512019-09-23 21:19:471219void NavigationControllerImpl::PruneForwardEntries() {
1220 DiscardNonCommittedEntries();
1221 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471222 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471223 if (num_removed <= 0)
1224 return;
Nate Chapin9eb16be72022-09-23 22:54:311225 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471226 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1227 NotifyPrunedEntries(this, remove_start_index /* start index */,
1228 num_removed /* count */);
1229}
1230
Aran Gilman37d11632019-10-08 23:07:151231void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1232 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321233 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311234 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511235 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1236 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321237 }
1238}
1239
Harkiran Bolariaba823e42021-05-21 18:30:361240base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1241 const GURL& url,
1242 const Referrer& referrer,
1243 ui::PageTransition transition,
1244 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471245 LoadURLParams params(url);
1246 params.referrer = referrer;
1247 params.transition_type = transition;
1248 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361249 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471250}
1251
Harkiran Bolariaba823e42021-05-21 18:30:361252base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1253 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061254 if (params.is_renderer_initiated)
1255 DCHECK(params.initiator_origin.has_value());
1256
naskob8744d22014-08-28 17:07:431257 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151258 "NavigationControllerImpl::LoadURLWithParams", "url",
1259 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291260 bool is_explicit_navigation =
1261 GetContentClient()->browser()->IsExplicitNavigation(
1262 params.transition_type);
1263 if (HandleDebugURL(params.url, params.transition_type,
1264 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431265 // If Telemetry is running, allow the URL load to proceed as if it's
1266 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491267 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431268 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361269 return nullptr;
[email protected]47752982014-07-29 08:01:431270 }
[email protected]8bf1048012012-02-08 01:22:181271
[email protected]cf002332012-08-14 19:17:471272 // Checks based on params.load_type.
1273 switch (params.load_type) {
1274 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431275 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471276 break;
1277 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261278 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471279 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361280 return nullptr;
[email protected]cf002332012-08-14 19:17:471281 }
1282 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461283 }
[email protected]e47ae9472011-10-13 19:48:341284
[email protected]e47ae9472011-10-13 19:48:341285 // The user initiated a load, we don't need to reload anymore.
1286 needs_reload_ = false;
1287
Harkiran Bolariaba823e42021-05-21 18:30:361288 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441289}
1290
Mohamed Abdelhalim833de902019-09-16 17:41:451291bool NavigationControllerImpl::PendingEntryMatchesRequest(
1292 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191293 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451294 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191295}
1296
[email protected]d202a7c2012-01-04 07:53:471297bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321298 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071299 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331300 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441301 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251302 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471303 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131304 NavigationRequest* navigation_request) {
1305 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331306
1307 // Note: validation checks and renderer kills due to invalid commit messages
1308 // must happen before getting here, in
1309 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1310 // effects of the navigation have already occurred.
1311
[email protected]cd2e15742013-03-08 04:08:311312 is_initial_navigation_ = false;
1313
Wang Hui96ab1012022-10-11 02:05:491314 // Any pending request to repost a form submission is no longer valid, since a
1315 // different NavigationEntry is committing.
1316 pending_reload_ = ReloadType::NONE;
1317
[email protected]0e8db942008-09-24 21:21:481318 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431319 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451320 if (entry_replaced_by_post_commit_error_) {
1321 // Same document navigation events with a post-commit error should already
1322 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1323 // reaching here.
1324 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331325
Rakina Zata Amnie2d31312022-11-18 03:38:451326 // Any commit while a post-commit error page is showing should put the
1327 // original entry back, replacing the error page's entry. This includes
1328 // reloads, where the original entry was used as the pending entry and
1329 // should now be at the correct index at commit time.
1330 entries_[last_committed_entry_index_] =
1331 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481332 }
Rakina Zata Amnie2d31312022-11-18 03:38:451333 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1334 details->previous_entry_index = GetLastCommittedEntryIndex();
1335 if (PendingEntryMatchesRequest(navigation_request) &&
1336 pending_entry_->GetIsOverridingUserAgent() !=
1337 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1338 overriding_user_agent_changed = true;
1339 }
1340#if BUILDFLAG(IS_ANDROID)
1341 // TODO(crbug.com/1266277): Clean up the logic of setting
1342 // |overriding_user_agent_changed| post-launch.
1343 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1344 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1345 // Must honor user agent overrides in the |navigation_request|, such as
1346 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1347 // result, besides comparing |pending_entry_|'s user agent against
1348 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1349 // agent against LastCommittedEntry's.
1350 if (navigation_request->is_overriding_user_agent() !=
1351 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1352 overriding_user_agent_changed = true;
1353 }
1354 }
1355#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171356
Dave Tapuskaa2ab4f252021-07-08 21:31:281357 bool is_main_frame_navigation = !rfh->GetParent();
1358
Alexander Timind2f2e4f22019-04-02 20:04:531359 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1360 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281361 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141362 // BackForwardCacheMetrics to be associated with the new navigation's
1363 // NavigationEntry, by either creating a new object or reusing the previous
1364 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281365 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
1366 if (navigation_request->frame_tree_node()->frame_tree()->type() ==
1367 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141368 back_forward_cache_metrics = BackForwardCacheMetrics::
1369 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281370 GetLastCommittedEntry(), is_main_frame_navigation,
1371 params.document_sequence_number);
1372 }
Alexander Timind2f2e4f22019-04-02 20:04:531373 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281374 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451375 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1376 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531377 }
1378 }
1379
Rakina Zata Amnifd8370b2022-11-14 13:32:251380 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1381 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091382 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251383 details->did_replace_entry =
1384 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091385
fdegans9caf66a2015-07-30 21:10:421386 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111387 // except for restored entries. This should be true even if the current commit
1388 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291389 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481390 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081391 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111392
1393 // Only make changes based on the pending entry if the NavigationRequest
1394 // matches it. Otherwise, the pending entry may be for a different request
1395 // (e.g., if a slow history navigation is pending while an auto-subframe
1396 // commit occurs).
1397 if (PendingEntryMatchesRequest(navigation_request)) {
1398 // It is no longer necessary to consider the pending entry as restored.
1399 if (pending_entry_->IsRestored()) {
1400 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1401 was_restored = true;
1402 }
[email protected]e9ba4472008-09-14 15:42:431403
Charlie Reisf8cde712022-10-20 16:25:091404 // If the SiteInstance has changed from the matching pending entry, this
1405 // must be treated as a new navigation with replacement. Set the replacement
1406 // bit here and ClassifyNavigation will identify this case and return
1407 // NEW_ENTRY.
1408 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1409 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1410 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251411 // TODO(nasko,creis,rakina): Move this to happen before committing the
1412 // navigation. This is a bit complicated because we don't currently
1413 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091414 details->did_replace_entry = true;
1415 }
Nasko Oskovaee2f862018-06-15 00:05:521416 }
[email protected]bcd904482012-02-01 01:54:221417
[email protected]e9ba4472008-09-14 15:42:431418 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101419 NavigationType navigation_type =
1420 ClassifyNavigation(rfh, params, navigation_request);
1421 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451422
Rakina Zata Amnie2d31312022-11-18 03:38:451423 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451424 // Ensure that this navigation does not add a navigation entry, since
1425 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1426 // beyond the last committed one. Therefore, `should_replace_current_entry`
1427 // should be set, which replaces the current entry, or this should be a
1428 // reload, which does not create a new entry.
1429 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1430 // navigation that is restored will not be creating a new entry anyways, so
1431 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1432 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1433 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251434 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451435 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101436 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451437 }
1438
Rakina Zata Amnie2d31312022-11-18 03:38:451439 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551440 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241441 // This is a subframe navigation on the initial empty document, which used
1442 // to not have a NavigationEntry to attach to. Now it can attach to the
1443 // initial NavigationEntry, and we must ensure that its NavigationEntry
1444 // will keep the "initial NavigationEntry" status and won't append a new
1445 // NavigationEntry (it should always do replacement instead).
1446 // See also https://crbug.com/1277414.
1447 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551448 // Subframe navigation on initial NavigationEntry must not append a new
1449 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1450 // means every subframe navigation that happens while we're on the initial
1451 // NavigationEntry will always reuse the existing NavigationEntry and
1452 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101453 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1454 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551455 // This is a navigation that modifies the initial NavigationEntry, either
1456 // for a replacement or a reload. The initial NavigationEntry should
1457 // retain its "initial NavigationEntry" status in this case.
1458 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241459 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251460 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1461 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241462 // This is a synchronous about:blank navigation on the main frame, which
1463 // used to not create a NavigationEntry when we have no NavigationEntry on
1464 // FrameTree creation. We now have the initial NavigationEntry and are on
1465 // the initial NavigationEntry. To preserve old behavior, we should still
1466 // keep the "initial" status for the new NavigationEntry that we will
1467 // create for this navigation, so that subframe navigations under the
1468 // synchronously committed about:blank document will never append new
1469 // NavigationEntry, and instead will just reuse the initial
1470 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1471 // See also https://crbug.com/1277414.
1472 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551473 }
1474 }
1475 DCHECK(!details->should_stay_as_initial_entry ||
1476 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201477
eugenebutee08663a2017-04-27 17:43:121478 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441479 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121480
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071481 details->is_prerender_activation =
1482 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241483 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1484 ->GetOutermostMainFrame()
1485 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071486
Peter Boströmd7592132019-01-30 04:50:311487 // Make sure we do not discard the pending entry for a different ongoing
1488 // navigation when a same document commit comes in unexpectedly from the
1489 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1490 // other navigation types. See https://crbug.com/900036.
1491 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061492 bool keep_pending_entry =
1493 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101494 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061495 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311496
Miyoung Shin3299cbf2022-11-22 01:41:101497 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061498 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491499 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051500 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001501 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431502 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061503 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491504 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1505 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001506 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431507 break;
[email protected]8ff00d72012-10-23 19:12:211508 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471509 RendererDidNavigateNewSubframe(
1510 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001511 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431512 break;
[email protected]8ff00d72012-10-23 19:12:211513 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391514 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251515 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001516 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081517 // We don't send a notification about auto-subframe PageState during
1518 // UpdateStateForFrame, since it looks like nothing has changed. Send
1519 // it here at commit time instead.
1520 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431521 return false;
creis59d5a47cb2016-08-24 23:57:191522 }
[email protected]e9ba4472008-09-14 15:42:431523 break;
Aran Gilman37d11632019-10-08 23:07:151524 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431525 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151526 break;
[email protected]765b35502008-08-21 00:51:201527 }
1528
[email protected]688aa65c62012-09-28 04:32:221529 // At this point, we know that the navigation has just completed, so
1530 // record the time.
1531 //
1532 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261533 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331534 base::Time timestamp =
1535 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1536 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131537 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221538
Peter Boströmd7592132019-01-30 04:50:311539 // If we aren't keeping the pending entry, there shouldn't be one at this
1540 // point. Clear it again in case any error cases above forgot to do so.
1541 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1542 // been cleared instead of protecting against it.
1543 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551544 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141545
[email protected]e9ba4472008-09-14 15:42:431546 // All committed entries should have nonempty content state so WebKit doesn't
1547 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471548 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321549 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221550 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441551 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141552
Alexander Timind2f2e4f22019-04-02 20:04:531553 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1554 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281555 if (back_forward_cache_metrics &&
1556 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531557 active_entry->set_back_forward_cache_metrics(
1558 std::move(back_forward_cache_metrics));
1559 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281560
1561 // `back_forward_cache_metrics()` may return null as we do not record
1562 // back-forward cache metrics for navigations in non-primary frame trees.
1563 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141564 // TODO(https://crbug.com/1338089): Remove this.
1565 // These are both only available from details at this point, so we capture
1566 // them here.
1567 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101568 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141569 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1570 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281571 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1572 navigation_request,
1573 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1574 }
naskoc7533512016-05-06 17:01:121575
Charles Reisc0507202017-09-21 00:40:021576 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1577 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1578 // A mismatch can occur if the renderer lies or due to a unique name collision
1579 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121580 FrameNavigationEntry* frame_entry =
1581 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021582 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1583 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031584 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081585 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1586 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031587 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201588
1589 // Remember the bindings the renderer process has at this point, so that
1590 // we do not grant this entry additional bindings if we come back to it.
1591 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301592 }
[email protected]132e281a2012-07-31 18:32:441593
[email protected]97d8f0d2013-10-29 16:49:211594 // Once it is committed, we no longer need to track several pieces of state on
1595 // the entry.
naskoc7533512016-05-06 17:01:121596 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131597
[email protected]49bd30e62011-03-22 20:12:591598 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221599 // TODO(creis): This check won't pass for subframes until we create entries
1600 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001601 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421602 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591603
[email protected]e9ba4472008-09-14 15:42:431604 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001605 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001606 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311607 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531608
arthursonzogni7ddc6542021-04-09 09:16:501609 active_entry->SetIsOverridingUserAgent(
1610 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031611
[email protected]93f230e02011-06-01 14:40:001612 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291613
aelias100c9192017-01-13 00:01:431614 if (overriding_user_agent_changed)
1615 delegate_->UpdateOverridingUserAgent();
1616
creis03b48002015-11-04 00:54:561617 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1618 // one knows the latest NavigationEntry it is showing (whether it has
1619 // committed anything in this navigation or not). This allows things like
1620 // state and title updates from RenderFrames to apply to the latest relevant
1621 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381622 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031623 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381624 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431625
1626 if (navigation_request->IsPrerenderedPageActivation()) {
1627 BroadcastHistoryOffsetAndLength();
1628 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1629 // is activated. As a result, a "prerenderingchange" event listener sees the
1630 // history.length which is not updated yet. We should guarantee that
1631 // history's length and offset should be updated before a
1632 // "prerenderingchange" event listener runs. One possible approach is to use
1633 // the same IPC which "prerenderingchange" uses, and propagate history's
1634 // length and offset together with that.
1635 }
1636
[email protected]e9ba4472008-09-14 15:42:431637 return true;
initial.commit09911bf2008-07-26 23:55:291638}
1639
[email protected]8ff00d72012-10-23 19:12:211640NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321641 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101642 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241643 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591644 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511645 "ClassifyNavigation");
1646
avi7c6f35e2015-05-08 17:52:381647 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241648 // A new entry. We may or may not have a corresponding pending entry, and
1649 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001650 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491651 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061652 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381653 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241654 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511655 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381656 return NAVIGATION_TYPE_NEW_SUBFRAME;
1657 }
1658
Charlie Reisc0f17d2d2021-01-12 18:52:491659 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381660 DCHECK(!params.history_list_was_cleared);
1661
avi39c1edd32015-06-04 20:06:001662 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381663 // All manual subframes would be did_create_new_entry and handled above, so
1664 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081665 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1666 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381667 }
1668
Rakina Zata Amnif6950d552020-11-24 03:26:101669 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1670 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381671 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1672 // create a new page.
1673
Hayato Ito2ae49442021-07-02 02:59:251674 // This main frame navigation is not a history navigation (since
1675 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1676 // reload or a replacement navigation, which will modify the existing entry.
1677 //
Nasko Oskov332593c2018-08-16 17:21:341678 // TODO(nasko): With error page isolation, reloading an existing session
1679 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491680 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341681 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511682 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491683 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061684 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381685 }
1686
Charlie Reisf8cde712022-10-20 16:25:091687 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521688 // If the SiteInstance of the |pending_entry_| does not match the
1689 // SiteInstance that got committed, treat this as a new navigation with
1690 // replacement. This can happen if back/forward/reload encounters a server
1691 // redirect to a different site or an isolated error page gets successfully
1692 // reloaded into a different SiteInstance.
1693 if (pending_entry_->site_instance() &&
1694 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491695 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061696 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521697 }
creis77c9aa32015-09-25 19:59:421698
Nasko Oskovaee2f862018-06-15 00:05:521699 if (pending_entry_index_ == -1) {
1700 // In this case, we have a pending entry for a load of a new URL but Blink
1701 // didn't do a new navigation (params.did_create_new_entry). First check
1702 // to make sure Blink didn't treat a new cross-process navigation as
1703 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161704 // we must treat it as NEW rather than the converted reload case below,
1705 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451706 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161707 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061708 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521709 }
1710
1711 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161712 // We will create a pending entry, but NavigateWithoutEntry will convert
1713 // it to a reload since it's the same page and not create a new entry for
1714 // it. (The user doesn't want to have a new back/forward entry when they
1715 // do this.) Therefore we want to just ignore the pending entry and go
1716 // back to where we were (the "existing entry").
1717 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061718 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521719 }
avi7c6f35e2015-05-08 17:52:381720 }
1721
Rakina Zata Amni153d5702021-09-13 22:48:001722 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381723 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491724 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1725 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161726 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061727 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381728 }
1729
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121730 if (navigation_request->DidEncounterError() &&
1731 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101732 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381733 // If the renderer was going to a new pending entry that got cleared because
1734 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491735 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381736 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511737 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491738 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061739 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381740 }
1741
Charlie Reisc0f17d2d2021-01-12 18:52:491742 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101743 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511744 trace_return.traced_value()->SetInteger("existing_entry_index",
1745 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381746 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441747 // The renderer has committed a navigation to an entry that no longer
1748 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491749 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061750 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381751 }
1752
avi7c6f35e2015-05-08 17:52:381753 // Since we weeded out "new" navigations above, we know this is an existing
1754 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491755 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061756 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381757}
1758
Rakina Zata Amni3460d382021-10-29 00:43:371759void NavigationControllerImpl::UpdateNavigationEntryDetails(
1760 NavigationEntryImpl* entry,
1761 RenderFrameHostImpl* rfh,
1762 const mojom::DidCommitProvisionalLoadParams& params,
1763 NavigationRequest* request,
1764 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001765 bool is_new_entry,
1766 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371767 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171768 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371769 entry->AddOrUpdateFrameEntry(
1770 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571771 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371772 rfh->GetSiteInstance(), nullptr, params.url,
1773 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171774 Referrer(*params.referrer),
1775 request ? request->common_params().initiator_origin : params.origin,
1776 request ? request->GetRedirectChain() : redirects, params.page_state,
1777 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
1778 (request && request->web_bundle_navigation_info())
Rakina Zata Amni3460d382021-10-29 00:43:371779 ? request->web_bundle_navigation_info()->Clone()
1780 : nullptr,
Rakina Zata Amniafd3c6582021-11-30 06:19:171781 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371782 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171783 rfh, request && request->IsSameDocument(),
1784 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371785
1786 if (rfh->GetParent()) {
1787 // Only modify the NavigationEntry for main frame navigations.
1788 return;
1789 }
1790 if (entry->update_virtual_url_with_url())
1791 UpdateVirtualURLToURL(entry, params.url);
1792 // Don't use the page type from the pending entry. Some interstitial page
1793 // may have set the type to interstitial. Once we commit, however, the page
1794 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171795 entry->set_page_type((request && request->DidEncounterError())
1796 ? PAGE_TYPE_ERROR
1797 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431798 if (commit_details && commit_details->should_stay_as_initial_entry) {
1799 // Retain the "initial NavigationEntry" status.
1800 if (request->IsSameDocument()) {
1801 // If this is for a same-document navigation, the NavigationEntry must be
1802 // reused and should already be marked as the initial NavigationEntry.
1803 DCHECK(entry->IsInitialEntry());
1804 } else {
1805 // If this is for a cross-document navigation, it can be caused by a
1806 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1807 // "for synchronous about:blank" in the latter case, and also when it is
1808 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1809 // is not for a synchronous about:blank commit.
1810 NavigationEntryImpl::InitialNavigationEntryState new_state =
1811 NavigationEntryImpl::InitialNavigationEntryState::
1812 kInitialNotForSynchronousAboutBlank;
1813 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1814 request->is_synchronous_renderer_commit()) {
1815 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1816 kInitialForSynchronousAboutBlank;
1817 }
1818 entry->set_initial_navigation_entry_state(new_state);
1819 }
1820 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1821 // Remove the "initial NavigationEntry" status.
1822 entry->set_initial_navigation_entry_state(
1823 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001824 }
Rakina Zata Amniddf10502022-01-15 02:56:551825
Rakina Zata Amni3460d382021-10-29 00:43:371826 if (is_new_entry) {
1827 // Some properties of the NavigationEntry are only set when the entry is
1828 // new (we aren't reusing it).
1829 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171830 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1831 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371832 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1833 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1834 } else {
1835 // We are reusing the NavigationEntry. The site instance will normally be
1836 // the same except for a few cases:
1837 // 1) session restore, when no site instance will be assigned or
1838 // 2) redirect, when the site instance is reset.
1839 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1840 entry->site_instance() == rfh->GetSiteInstance());
1841 }
1842}
1843
Rakina Zata Amniafd3c6582021-11-30 06:19:171844void NavigationControllerImpl::CreateInitialEntry() {
1845 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031846 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171847 auto params = mojom::DidCommitProvisionalLoadParams::New();
1848 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1849 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1850 // before we have initial NavigationEntries.
1851 params->url = GURL::EmptyGURL();
1852 params->http_status_code = 0;
1853 params->url_is_unreachable = false;
1854 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171855 params->post_id = -1;
1856 params->embedding_token = base::UnguessableToken::Create();
1857 params->navigation_token = base::UnguessableToken::Create();
1858 params->did_create_new_entry = true;
1859 params->origin = rfh->GetLastCommittedOrigin();
1860 params->should_update_history = true;
1861 params->item_sequence_number = 0;
1862 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151863 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171864 params->transition = is_in_fenced_frame_tree
1865 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1866 : ui::PAGE_TRANSITION_LINK;
1867 params->referrer = blink::mojom::Referrer::New();
1868
1869 // Create and insert the initial NavigationEntry.
1870 auto new_entry = std::make_unique<NavigationEntryImpl>(
1871 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
1872 rfh->GetLastCommittedOrigin(), std::u16string() /* title */,
1873 ui::PAGE_TRANSITION_TYPED, false /* renderer_initiated */,
1874 nullptr /* blob_url_loader_factory */, true /* is_initial_entry */);
1875 UpdateNavigationEntryDetails(
1876 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001877 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1878 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171879
1880 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1881 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001882 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171883}
1884
Charlie Reisc0f17d2d2021-01-12 18:52:491885void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321886 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071887 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361888 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441889 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471890 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001891 NavigationRequest* request,
1892 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571893 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071894 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451895 request->common_params().initiator_origin;
Lukasz Anforowicz435bcb582019-07-12 20:50:061896
creisf49dfc92016-07-26 17:05:181897 // First check if this is an in-page navigation. If so, clone the current
1898 // entry instead of looking at the pending entry, because the pending entry
1899 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451900 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301901 FrameNavigationEntry* previous_frame_entry =
1902 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451903 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481904 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571905 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081906 rfh->GetSiteInstance(), nullptr, params.url,
1907 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amni82fafba2021-03-11 07:07:091908 Referrer(*params.referrer), initiator_origin,
1909 request->GetRedirectChain(), params.page_state, params.method,
1910 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:391911 nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481912 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391913 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301914 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571915 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301916 // FrameNavigationEntry.
1917 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571918 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031919
creisf49dfc92016-07-26 17:05:181920 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031921 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521922 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1923 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571924 // TODO(jam): we had one report of this with a URL that was redirecting to
1925 // only tildes. Until we understand that better, don't copy the cert in
1926 // this case.
1927 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571928 }
creisf49dfc92016-07-26 17:05:181929
Patrick Monette50e8bd82019-06-13 22:40:451930 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1931 // that |frame_entry| should now have a reference count of exactly 2: one
1932 // due to the local variable |frame_entry|, and another due to |new_entry|
1933 // also retaining one. This should never fail, because it's the main frame.
1934 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181935 }
1936
Harkiran Bolaria59290d62021-03-17 01:53:011937 // If this is an activation navigation from a prerendered page, transfer the
1938 // new entry from an entry already created and stored in the
1939 // NavigationRequest. |new_entry| will not have been set prior to this as
1940 // |is_same_document| is mutually exclusive with
1941 // |IsPrerenderedPageActivation|.
1942 if (request->IsPrerenderedPageActivation()) {
1943 DCHECK(!is_same_document);
1944 DCHECK(!new_entry);
1945 new_entry = request->TakePrerenderNavigationEntry();
1946 DCHECK(new_entry);
1947 }
1948
Charlie Reisc0f17d2d2021-01-12 18:52:491949 // Only make a copy of the pending entry if it is appropriate for the new
1950 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451951 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041952 // 1. The SiteInstance hasn't been assigned to something else.
1953 // 2. The pending entry was intended as a new entry, rather than being a
1954 // history navigation that was interrupted by an unrelated,
1955 // renderer-initiated navigation.
1956 // TODO(csharrison): Investigate whether we can remove some of the coarser
1957 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451958 if (!new_entry && PendingEntryMatchesRequest(request) &&
1959 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341960 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431961 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351962 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431963
Camille Lamy62b826012019-02-26 09:15:471964 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451965 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181966 }
1967
Charlie Reisc0f17d2d2021-01-12 18:52:491968 // For cross-document commits with no matching pending entry, create a new
1969 // entry.
creisf49dfc92016-07-26 17:05:181970 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061971 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:071972 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
1973 initiator_origin,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:581974 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:451975 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:171976 nullptr, // blob_url_loader_factory
1977 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:241978
1979 // Find out whether the new entry needs to update its virtual URL on URL
1980 // change and set up the entry accordingly. This is needed to correctly
1981 // update the virtual URL when replaceState is called after a pushState.
1982 GURL url = params.url;
1983 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:491984 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:411985 // update the virtual URL based on the new URL. For example, this is needed
1986 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1987 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:371988 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1989 &url, browser_context_, &needs_update);
1990 new_entry->set_update_virtual_url_with_url(needs_update);
1991
Camille Lamy62b826012019-02-26 09:15:471992 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451993 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:431994 }
1995
Harkiran Bolaria59290d62021-03-17 01:53:011996 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
1997 // for prerendered contents, if any. This is because prerendering/activation
1998 // technically won't be creating a new document. Unlike BFCache, prerendering
1999 // creates a new NavigationEntry rather than using an existing one.
2000 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372001 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2002 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002003 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082004
Harkiran Bolaria59290d62021-03-17 01:53:012005 // history.pushState() is classified as a navigation to a new page, but sets
2006 // is_same_document to true. In this case, we already have the title and
2007 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452008 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012009 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2010 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2011 }
[email protected]3a868f212014-08-09 10:41:192012 }
[email protected]ff64b3e2014-05-31 04:07:332013
[email protected]60d6cca2013-04-30 08:47:132014 DCHECK(!params.history_list_was_cleared || !replace_entry);
2015 // The browser requested to clear the session history when it initiated the
2016 // navigation. Now we know that the renderer has updated its state accordingly
2017 // and it is safe to also clear the browser side history.
2018 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552019 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132020 entries_.clear();
2021 last_committed_entry_index_ = -1;
2022 }
2023
Nasko Oskovaee2f862018-06-15 00:05:522024 // If this is a new navigation with replacement and there is a
2025 // pending_entry_ which matches the navigation reported by the renderer
2026 // process, then it should be the one replaced, so update the
2027 // last_committed_entry_index_ to use it.
2028 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092029 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522030 last_committed_entry_index_ = pending_entry_index_;
2031 }
2032
Alexander Timine3ec4192020-04-20 16:39:402033 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412034 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402035 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052036
Yuzu Saijoa725585f2022-11-28 04:14:032037 // If this is a history navigation and the old entry has an existing
2038 // back/forward cache metrics object, keep using the old one so that the
2039 // reasons logged from the last time the page navigated gets preserved.
2040 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2041 request)) {
2042 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2043 // because some tests do not have a pending entry.
2044 NavigationEntryImpl* entry =
2045 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2046 if (entry && entry->back_forward_cache_metrics()) {
2047 scoped_refptr<BackForwardCacheMetrics> metrics =
2048 entry->TakeBackForwardCacheMetrics();
2049 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2050 }
2051 }
2052
Carlos IL42b416592019-10-07 23:10:362053 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312054 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152055 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432056}
2057
Charlie Reisc0f17d2d2021-01-12 18:52:492058void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322059 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072060 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362061 bool is_same_document,
jam48cea9082017-02-15 06:13:292062 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452063 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002064 bool keep_pending_entry,
2065 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562066 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2067 << "that a last committed entry exists.";
2068
[email protected]e9ba4472008-09-14 15:42:432069 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002070 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432071
Charlie Reis7e2cb6d2021-01-26 01:27:162072 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002073 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162074 // We're guaranteed to have a last committed entry if intended_as_new_entry
2075 // is true.
avicbdc4c12015-07-01 16:07:112076 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162077
2078 // If the NavigationRequest matches a new pending entry and is classified as
2079 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2080 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092081 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162082 // Note: The pending entry will usually have a real ReloadType here, but
2083 // it can still be ReloadType::NONE in cases that
2084 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2085
2086 // If we classified this correctly, the SiteInstance should not have
2087 // changed.
2088 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2089
2090 // For converted reloads, we assign the entry's unique ID to be that of
2091 // the new one. Since this is always the result of a user action, we want
2092 // to dismiss infobars, etc. like a regular user-initiated navigation.
2093 entry->set_unique_id(pending_entry_->GetUniqueID());
2094
2095 // The extra headers may have changed due to reloading with different
2096 // headers.
2097 entry->set_extra_headers(pending_entry_->extra_headers());
2098 }
2099 // Otherwise, this was intended as a new entry but the pending entry was
2100 // lost in the meantime and no new entry was created. We are stuck at the
2101 // last committed entry.
2102
2103 // Even if this is a converted reload from pressing enter in the omnibox,
2104 // the server could redirect, requiring an update to the SSL status. If this
2105 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452106 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162107 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472108 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452109 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162110 }
Rakina Zata Amnif6950d552020-11-24 03:26:102111 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112112 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102113 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162114
eugenebut604866f2017-05-10 21:35:362115 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452116 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362117 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2118 // this was a restored same document navigation entry, then it won't have
2119 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2120 // navigated it.
jam48cea9082017-02-15 06:13:292121 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522122 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2123 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292124 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2125 was_restored) {
2126 entry->GetSSL() = last_entry->GetSSL();
2127 }
2128 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452129 // In rapid back/forward navigations |request| sometimes won't have a cert
2130 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192131 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452132 if (request->GetSSLInfo().has_value() &&
2133 request->GetSSLInfo()->is_valid()) {
2134 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522135 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2136 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192137 entry->GetSSL() = SSLStatus();
2138 }
jam48cea9082017-02-15 06:13:292139 }
avicbdc4c12015-07-01 16:07:112140 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272141 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572142 // navigations that are EXISTING_ENTRY are same-document navigations that
2143 // result in replacement (e.g. history.replaceState(), location.replace(),
2144 // forced replacements for trivial session history contexts). For these
2145 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112146 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102147
Mikel Astizba9cf2fd2017-12-17 10:38:102148 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2149 // to avoid misleading interpretations (e.g. URLs paired with
2150 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2151 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2152 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2153
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572154 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102155
eugenebut604866f2017-05-10 21:35:362156 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452157 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362158 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472159 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452160 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112161 }
2162 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432163
Rakina Zata Amni3460d382021-10-29 00:43:372164 UpdateNavigationEntryDetails(entry, rfh, params, request,
2165 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002166 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302167
[email protected]5ccd4dc2012-10-24 02:28:142168 // The redirected to page should not inherit the favicon from the previous
2169 // page.
eugenebut604866f2017-05-10 21:35:362170 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482171 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142172
Peter Boströmd7592132019-01-30 04:50:312173 // We should also usually discard the pending entry if it corresponds to a
2174 // different navigation, since that one is now likely canceled. In rare
2175 // cases, we leave the pending entry for another navigation in place when we
2176 // know it is still ongoing, to avoid a flicker in the omnibox (see
2177 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432178 //
2179 // Note that we need to use the "internal" version since we don't want to
2180 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312181 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002182 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392183
Carlos IL4dea8902020-05-26 15:14:292184 // Update the last committed index to reflect the committed entry.
avicbdc4c12015-07-01 16:07:112185 last_committed_entry_index_ = GetIndexOfEntry(entry);
[email protected]e9ba4472008-09-14 15:42:432186}
2187
[email protected]d202a7c2012-01-04 07:53:472188void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322189 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072190 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362191 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472192 bool replace_entry,
2193 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002194 NavigationRequest* request,
2195 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262196 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2197 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552198 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2199 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112200
[email protected]e9ba4472008-09-14 15:42:432201 // Manual subframe navigations just get the current entry cloned so the user
2202 // can go back or forward to it. The actual subframe information will be
2203 // stored in the page state for each of those entries. This happens out of
2204 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092205 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2206 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382207
Mikel Astizba9cf2fd2017-12-17 10:38:102208 // The DCHECK below documents the fact that we don't know of any situation
2209 // where |replace_entry| is true for subframe navigations. This simplifies
2210 // reasoning about the replacement struct for subframes (see
2211 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2212 DCHECK(!replace_entry);
2213
Patrick Monette50e8bd82019-06-13 22:40:452214 // This FrameNavigationEntry might not end up being used in the
2215 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072216 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452217 request->common_params().initiator_origin;
Nate Chapin63db0d12022-01-20 22:03:302218 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2219 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2220 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572221 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302222 if (is_same_document) {
2223 FrameNavigationEntry* previous_frame_entry =
2224 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572225 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302226 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572227 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302228 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572229 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302230 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572231 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302232 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572233 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302234 policy_container_policies->referrer_policy);
2235 }
2236
Patrick Monette50e8bd82019-06-13 22:40:452237 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482238 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572239 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082240 rfh->GetSiteInstance(), nullptr, params.url,
2241 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amni82fafba2021-03-11 07:07:092242 Referrer(*params.referrer), initiator_origin, request->GetRedirectChain(),
arthursonzogni73fe3212020-11-17 13:24:072243 params.page_state, params.method, params.post_id,
2244 nullptr /* blob_url_loader_factory */,
Tsuyoshi Horo0c605782020-05-27 00:21:032245 request->web_bundle_navigation_info()
2246 ? request->web_bundle_navigation_info()->Clone()
Antonio Sartori78a749f2020-11-30 12:03:392247 : nullptr,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482248 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572249 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032250
creisce0ef3572017-01-26 17:53:082251 std::unique_ptr<NavigationEntryImpl> new_entry =
2252 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452253 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032254 frame_tree_->root());
creise062d542015-08-25 02:01:552255
Alexander Timine3ec4192020-04-20 16:39:402256 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412257 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402258 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472259
creisce0ef3572017-01-26 17:53:082260 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452261 // to replace, which can happen due to a unique name change. See
2262 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2263 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382264
Dave Tapuska87696ae2021-11-18 18:48:312265 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152266 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432267}
2268
[email protected]d202a7c2012-01-04 07:53:472269bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322270 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072271 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392272 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252273 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002274 NavigationRequest* request,
2275 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292276 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2277 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2278
[email protected]e9ba4472008-09-14 15:42:432279 // We're guaranteed to have a previously committed entry, and we now need to
2280 // handle navigation inside of a subframe in it without creating a new entry.
2281 DCHECK(GetLastCommittedEntry());
2282
creis913c63ce2016-07-16 19:52:522283 // For newly created subframes, we don't need to send a commit notification.
2284 // This is only necessary for history navigations in subframes.
2285 bool send_commit_notification = false;
2286
Rakina Zata Amnif6950d552020-11-24 03:26:102287 // If |nav_entry_id| is non-zero and matches an existing entry, this
2288 // is a history navigation. Update the last committed index accordingly. If
2289 // we don't recognize the |nav_entry_id|, it might be a recently
2290 // pruned entry. We'll handle it below.
2291 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2292 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472293 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062294 // Make sure that a subframe commit isn't changing the main frame's
2295 // origin. Otherwise the renderer process may be confused, leading to a
2296 // URL spoof. We can't check the path since that may change
2297 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572298 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2299 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242300 // We should use checks similar to RenderFrameHostImpl's
2301 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2302 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572303 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2304 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2305 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2306 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522307 current_top_url.DeprecatedGetOriginAsURL() !=
2308 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442309 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512310 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062311 }
creis3cdc3b02015-05-29 23:00:472312
creis913c63ce2016-07-16 19:52:522313 // We only need to discard the pending entry in this history navigation
2314 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062315 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002316 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522317
2318 // History navigations should send a commit notification.
2319 send_commit_notification = true;
avi98405c22015-05-21 20:47:062320 }
[email protected]e9ba4472008-09-14 15:42:432321 }
[email protected]f233e4232013-02-23 00:55:142322
creisce0ef3572017-01-26 17:53:082323 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2324 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372325 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2326 // exists), or we may want to clobber it and create a new one. We update in
2327 // cases where the corresponding FrameNavigationEntry is conceptually similar
2328 // to the document described by the commit params: same-document
2329 // navigations, history traversal to an existing entry, and reloads (including
2330 // a "soft reload" where we navigate to the same url without flagging it as a
2331 // reload). But in the case of a different document that is not logically
2332 // related to the committed FrameNavigationEntry's document (cross-document,
2333 // not same url, not a reload, not a history traversal), we replace rather
2334 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252335 //
Nate Chapin9f169072021-06-09 19:32:372336 // In the case where we update, the FrameNavigationEntry will potentially be
2337 // shared across multiple NavigationEntries, and any updates will be reflected
2338 // in all of those NavigationEntries. In the replace case, any existing
2339 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252340 //
2341 // When navigating away from the initial empty document, we also update rather
2342 // than replace. Either update or replace will overwrite the initial empty
2343 // document state for |last_committed|, but if the FrameNavigationEntry for
2344 // the initial empty document is shared across multiple NavigationEntries (due
2345 // to a navigation in another frame), we want to make sure we overwrite the
2346 // initial empty document state everywhere this FrameNavigationEntry is used,
2347 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452348 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372349 FrameNavigationEntry* last_committed_frame_entry =
2350 last_committed->GetFrameEntry(rfh->frame_tree_node());
2351 NavigationEntryImpl::UpdatePolicy update_policy =
2352 NavigationEntryImpl::UpdatePolicy::kUpdate;
2353 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312354 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372355 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252356 last_committed_frame_entry->url() != params.url &&
2357 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372358 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2359 }
2360
Rakina Zata Amni3460d382021-10-29 00:43:372361 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002362 update_policy, false /* is_new_entry */,
2363 commit_details);
creis625a0c7d2015-03-24 23:17:122364
creis913c63ce2016-07-16 19:52:522365 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432366}
2367
[email protected]d202a7c2012-01-04 07:53:472368int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232369 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032370 for (size_t i = 0; i < entries_.size(); ++i) {
2371 if (entries_[i].get() == entry)
2372 return i;
2373 }
2374 return -1;
[email protected]765b35502008-08-21 00:51:202375}
2376
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572377void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242378 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572379 NavigationControllerImpl* source =
2380 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572381 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382382 DCHECK_EQ(1, GetEntryCount());
2383 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472384 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172385 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572386
Francois Dorayeaace782017-06-21 16:37:242387 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442388 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572389 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572390
Fergal Dalya1d569972021-03-16 03:24:532391 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302392 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532393 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2394 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302395 }
[email protected]4e6419c2010-01-15 04:50:342396
Lukasz Anforowicz0de0f452020-12-02 19:57:152397 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572398}
2399
Aran Gilman37d11632019-10-08 23:07:152400void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2401 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162402 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012403 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162404
[email protected]d202a7c2012-01-04 07:53:472405 NavigationControllerImpl* source =
2406 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252407
avi2b177592014-12-10 02:08:022408 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012409 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252410
[email protected]474f8512013-05-31 22:31:162411 // We now have one entry, possibly with a new pending entry. Ensure that
2412 // adding the entries from source won't put us over the limit.
2413 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572414 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572415 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252416
Carlos IL4dea8902020-05-26 15:14:292417 // Insert the entries from source. Ignore any pending entry, since it has not
2418 // committed in source.
[email protected]474f8512013-05-31 22:31:162419 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172420 DCHECK_NE(max_source_index, -1);
2421 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572422
2423 // Ignore the source's current entry if merging with replacement.
2424 // TODO(davidben): This should preserve entries forward of the current
2425 // too. http://crbug.com/317872
2426 if (replace_entry && max_source_index > 0)
2427 max_source_index--;
2428
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572429 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252430
2431 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552432 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142433
Hayato Ito2c8c08d02021-06-23 03:38:432434 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252435}
2436
[email protected]79368982013-11-13 01:11:012437bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162438 // If there is no last committed entry, we cannot prune. Even if there is a
2439 // pending entry, it may not commit, leaving this WebContents blank, despite
2440 // possibly giving it new entries via CopyStateFromAndPrune.
2441 if (last_committed_entry_index_ == -1)
2442 return false;
[email protected]9350602e2013-02-26 23:27:442443
[email protected]474f8512013-05-31 22:31:162444 // We cannot prune if there is a pending entry at an existing entry index.
2445 // It may not commit, so we have to keep the last committed entry, and thus
2446 // there is no sensible place to keep the pending entry. It is ok to have
2447 // a new pending entry, which can optionally commit as a new navigation.
2448 if (pending_entry_index_ != -1)
2449 return false;
2450
[email protected]474f8512013-05-31 22:31:162451 return true;
2452}
2453
[email protected]79368982013-11-13 01:11:012454void NavigationControllerImpl::PruneAllButLastCommitted() {
2455 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162456
avi2b177592014-12-10 02:08:022457 DCHECK_EQ(0, last_committed_entry_index_);
2458 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442459
Hayato Ito2c8c08d02021-06-23 03:38:432460 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442461}
2462
[email protected]79368982013-11-13 01:11:012463void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162464 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012465 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262466
Nate Chapin9eb16be72022-09-23 22:54:312467 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2468
[email protected]474f8512013-05-31 22:31:162469 // Erase all entries but the last committed entry. There may still be a
2470 // new pending entry after this.
2471 entries_.erase(entries_.begin(),
2472 entries_.begin() + last_committed_entry_index_);
2473 entries_.erase(entries_.begin() + 1, entries_.end());
2474 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262475}
2476
Christian Dullweber1af31e62018-02-22 11:49:482477void NavigationControllerImpl::DeleteNavigationEntries(
2478 const DeletionPredicate& deletionPredicate) {
2479 // It is up to callers to check the invariants before calling this.
2480 CHECK(CanPruneAllButLastCommitted());
2481 std::vector<int> delete_indices;
2482 for (size_t i = 0; i < entries_.size(); i++) {
2483 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572484 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482485 delete_indices.push_back(i);
2486 }
2487 }
2488 if (delete_indices.empty())
2489 return;
2490
2491 if (delete_indices.size() == GetEntryCount() - 1U) {
2492 PruneAllButLastCommitted();
2493 } else {
2494 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382495 for (const auto& index : base::Reversed(delete_indices)) {
2496 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482497 }
Hayato Ito2c8c08d02021-06-23 03:38:432498 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482499 }
2500 delegate()->NotifyNavigationEntriesDeleted();
2501}
2502
Shivani Sharma883f5f32019-02-12 18:20:012503bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2504 auto* entry = GetEntryAtIndex(index);
2505 return entry && entry->should_skip_on_back_forward_ui();
2506}
2507
Carlos Caballero35ce710c2019-09-19 10:59:452508BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2509 return back_forward_cache_;
2510}
2511
clamy987a3752018-05-03 17:36:262512void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2513 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2514 // progress, since this will cause a use-after-free. (We only allow this
2515 // when the tab is being destroyed for shutdown, since it won't return to
2516 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032517 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262518
2519 if (was_failure && pending_entry_) {
2520 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2521 } else {
2522 failed_pending_entry_id_ = 0;
2523 }
2524
2525 if (pending_entry_) {
2526 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332527 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262528 pending_entry_index_ = -1;
2529 pending_entry_ = nullptr;
2530 }
arthursonzogni66f711c2019-10-08 14:40:362531
2532 // Ensure any refs to the current pending entry are ignored if they get
2533 // deleted, by clearing the set of known refs. All future pending entries will
2534 // only be affected by new refs.
2535 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262536}
2537
2538void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2539 if (pending_entry_)
2540 pending_entry_->set_ssl_error(error);
2541}
2542
Xiaohan Wang7f8052e02022-01-14 18:44:282543#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422544// static
2545bool NavigationControllerImpl::ValidateDataURLAsString(
2546 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2547 if (!data_url_as_string)
2548 return false;
2549
2550 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2551 return false;
2552
2553 // The number of characters that is enough for validating a data: URI.
2554 // From the GURL's POV, the only important part here is scheme, it doesn't
2555 // check the actual content. Thus we can take only the prefix of the url, to
2556 // avoid unneeded copying of a potentially long string.
2557 const size_t kDataUriPrefixMaxLen = 64;
2558 GURL data_url(
2559 std::string(data_url_as_string->front_as<char>(),
2560 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2561 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2562 return false;
2563
2564 return true;
2565}
2566#endif
2567
Shivani Sharma194877032019-03-07 17:52:472568void NavigationControllerImpl::NotifyUserActivation() {
2569 // When a user activation occurs, ensure that all adjacent entries for the
2570 // same document clear their skippable bit, so that the history manipulation
2571 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372572 if (base::FeatureList::IsEnabled(
2573 features::kDebugHistoryInterventionNoUserActivation)) {
2574 return;
2575 }
2576
Shivani Sharmac4cc8922019-04-18 03:11:172577 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472578}
2579
clamy987a3752018-05-03 17:36:262580bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2581 RenderFrameHostImpl* render_frame_host,
Julie Jeongeun Kimed2e5ba72019-09-12 10:14:172582 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client) {
clamy987a3752018-05-03 17:36:262583 NavigationEntryImpl* entry =
2584 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2585 if (!entry)
2586 return false;
2587
2588 FrameNavigationEntry* frame_entry =
2589 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2590 if (!frame_entry)
2591 return false;
2592
Nate Chapin45f620582021-09-30 17:45:432593 // |is_browser_initiated| is false here because a navigation in a new subframe
2594 // always begins with renderer action (i.e., an HTML element being inserted
2595 // into the DOM), so it is always renderer-initiated.
Camille Lamy5193caa2018-10-12 11:59:422596 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572597 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232598 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432599 true /* is_history_navigation_in_new_child */,
2600 false /* is_browser_initiated */);
clamyea99ea12018-05-28 13:54:232601
2602 if (!request)
2603 return false;
2604
arthursonzognif046d4a2019-12-12 19:08:102605 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412606
Lukasz Anforowicz9ee83c272020-12-01 20:14:052607 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2608 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232609
2610 return true;
clamy987a3752018-05-03 17:36:262611}
2612
Tsuyoshi Horo52fd08e2020-07-07 07:03:452613bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2614 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2615 if (!entry)
2616 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432617
2618 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2619 // We should never navigate to an existing initial NavigationEntry that is
2620 // the initial NavigationEntry for the initial empty document that hasn't
2621 // been overridden by the synchronous about:blank commit, to preserve
2622 // legacy behavior where trying to reload when the main frame is on the
2623 // initial empty document won't result in a navigation. See also
2624 // https://crbug.com/1277414.
2625 return false;
2626 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452627 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2628 if (!frame_entry)
2629 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142630 ReloadType reload_type = ReloadType::NORMAL;
2631 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452632 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142633 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452634 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432635 false /* is_history_navigation_in_new_child */,
2636 true /* is_browser_initiated */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452637 if (!request)
2638 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052639 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452640 return true;
2641}
2642
clamy987a3752018-05-03 17:36:262643void NavigationControllerImpl::NavigateFromFrameProxy(
2644 RenderFrameHostImpl* render_frame_host,
2645 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022646 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452647 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072648 const absl::optional<url::Origin>& initiator_origin,
clamy987a3752018-05-03 17:36:262649 bool is_renderer_initiated,
2650 SiteInstance* source_site_instance,
2651 const Referrer& referrer,
2652 ui::PageTransition page_transition,
2653 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252654 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262655 const std::string& method,
2656 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092657 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142658 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212659 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502660 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392661 const absl::optional<blink::Impression>& impression,
Nan Lin944e9b4e2022-04-12 13:51:222662 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492663 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462664 bool is_unfenced_top_navigation,
2665 bool force_new_browsing_instance) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582666 if (is_renderer_initiated)
2667 DCHECK(initiator_origin.has_value());
2668
clamy987a3752018-05-03 17:36:262669 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582670
Rakina Zata Amni2322f4f82022-01-24 13:24:242671 // Don't allow an entry replacement if there is no entry to replace.
2672 // http://crbug.com/457149
2673 if (GetEntryCount() == 0)
2674 should_replace_current_entry = false;
2675
clamy987a3752018-05-03 17:36:262676 // Create a NavigationEntry for the transfer, without making it the pending
2677 // entry. Subframe transfers should have a clone of the last committed entry
2678 // with a FrameNavigationEntry for the target frame. Main frame transfers
2679 // should have a new NavigationEntry.
2680 // TODO(creis): Make this unnecessary by creating (and validating) the params
2681 // directly, passing them to the destination RenderFrameHost. See
2682 // https://crbug.com/536906.
2683 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262684 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262685 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452686 DCHECK(GetLastCommittedEntry());
2687 entry = GetLastCommittedEntry()->Clone();
2688 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172689 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2690 // Renderer-initiated navigation that target a remote frame are currently
2691 // classified as browser-initiated when this one has already navigated.
2692 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372693 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2694 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2695 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2696 // same-document navigation), they will still be present in the
2697 // committed NavigationEntry that will be referenced to construct the new
2698 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262699 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082700 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582701 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072702 absl::nullopt /* commit_origin */, referrer, initiator_origin,
Miyoung Shin5d77f72072020-10-09 15:14:202703 std::vector<GURL>(), blink::PageState(), method, -1,
Antonio Sartori78a749f2020-11-30 12:03:392704 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482705 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542706 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262707 } else {
2708 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172709 // If `node` is the outermost main frame, it rewrites a virtual url in order
2710 // to adjust the original input url if needed. For inner frames such as
2711 // fenced frames or subframes, they don't rewrite urls as the urls are not
2712 // input urls by users.
2713 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy987a3752018-05-03 17:36:262714 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz641234d52019-11-07 21:07:102715 url, referrer, initiator_origin, source_site_instance, page_transition,
2716 is_renderer_initiated, extra_headers, browser_context_,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172717 blob_url_loader_factory, rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262718 entry->root_node()->frame_entry->set_source_site_instance(
2719 static_cast<SiteInstanceImpl*>(source_site_instance));
2720 entry->root_node()->frame_entry->set_method(method);
2721 }
clamy987a3752018-05-03 17:36:262722
Camille Lamy5193caa2018-10-12 11:59:422723 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452724 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262725 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422726 override_user_agent = true;
clamy987a3752018-05-03 17:36:262727 }
2728 // TODO(creis): Set user gesture and intent received timestamp on Android.
2729
2730 // We may not have successfully added the FrameNavigationEntry to |entry|
2731 // above (per https://crbug.com/608402), in which case we create it from
2732 // scratch. This works because we do not depend on |frame_entry| being inside
2733 // |entry| during NavigateToEntry. This will go away when we shortcut this
2734 // further in https://crbug.com/536906.
2735 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2736 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452737 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082738 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582739 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072740 absl::nullopt /* origin */, referrer, initiator_origin,
Rakina Zata Amni3a1c0ec2021-04-15 03:35:122741 std::vector<GURL>(), blink::PageState(), method, -1,
2742 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482743 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302744 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572745 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262746 }
2747
Camille Lamy5193caa2018-10-12 11:59:422748 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022749 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452750 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292751 params.initiator_origin = initiator_origin;
Camille Lamy5193caa2018-10-12 11:59:422752 params.source_site_instance = source_site_instance;
2753 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2754 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032755 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422756 params.referrer = referrer;
2757 /* params.redirect_chain: skip */
2758 params.extra_headers = extra_headers;
2759 params.is_renderer_initiated = is_renderer_initiated;
2760 params.override_user_agent = UA_OVERRIDE_INHERIT;
2761 /* params.base_url_for_data_url: skip */
2762 /* params.virtual_url_for_data_url: skip */
2763 /* params.data_url_as_string: skip */
2764 params.post_data = post_body;
2765 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582766 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422767 /* params.frame_name: skip */
2768 // TODO(clamy): See if user gesture should be propagated to this function.
2769 params.has_user_gesture = false;
2770 params.should_clear_history_list = false;
2771 params.started_from_context_menu = false;
2772 /* params.navigation_ui_data: skip */
2773 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222774 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542775 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212776 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412777 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502778 params.is_form_submission = is_form_submission;
Camille Lamy5193caa2018-10-12 11:59:422779
2780 std::unique_ptr<NavigationRequest> request =
2781 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032782 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142783 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392784 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492785 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
2786 is_unfenced_top_navigation);
clamyea99ea12018-05-28 13:54:232787
2788 if (!request)
2789 return;
2790
Garrett Tanzerbb8db412022-09-27 21:59:462791 // Force the navigation to take place in a new browsing instance.
2792 // This is used by _unfencedTop in fenced frames to ensure that navigations
2793 // leaving the fenced context create a new browsing instance.
2794 if (force_new_browsing_instance) {
2795 request->coop_status().ForceBrowsingInstanceSwap();
2796 }
2797
Arthur Hemery948742762019-09-18 10:06:242798 // At this stage we are proceeding with this navigation. If this was renderer
2799 // initiated with user gesture, we need to make sure we clear up potential
2800 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2801 DiscardNonCommittedEntries();
2802
Lukasz Anforowicz9ee83c272020-12-01 20:14:052803 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262804}
2805
[email protected]d1198fd2012-08-13 22:50:192806void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252807 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212808 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192809 if (!session_storage_namespace)
2810 return;
2811
2812 // We can't overwrite an existing SessionStorage without violating spec.
2813 // Attempts to do so may give a tab access to another tab's session storage
2814 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152815 bool successful_insert =
2816 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252817 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052818 static_cast<SessionStorageNamespaceImpl*>(
2819 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302820 .second;
2821 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192822}
2823
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572824bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452825 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032826 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462827}
2828
Aran Gilman37d11632019-10-08 23:07:152829SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252830 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302831 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252832 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032833 DOMStorageContextWrapper* context_wrapper =
2834 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2835
2836 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252837 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032838 if (it != session_storage_namespace_map_.end()) {
2839 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152840 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2841 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472842
michaelnbacbcbd2016-02-09 00:32:032843 return it->second.get();
2844 }
2845
2846 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102847 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2848 SessionStorageNamespaceImpl::Create(context_wrapper);
2849 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2850 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252851 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102852 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302853
Daniel Murphy31bbb8b12018-02-07 21:44:102854 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302855}
2856
2857SessionStorageNamespace*
2858NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252859 return GetSessionStorageNamespace(
2860 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302861}
2862
2863const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572864NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302865 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552866}
[email protected]d202a7c2012-01-04 07:53:472867
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572868bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562869 return needs_reload_;
2870}
[email protected]a26023822011-12-29 00:23:552871
[email protected]46bb5e9c2013-10-03 22:16:472872void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412873 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2874}
2875
2876void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472877 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412878 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542879
2880 if (last_committed_entry_index_ != -1) {
2881 entries_[last_committed_entry_index_]->SetTransitionType(
2882 ui::PAGE_TRANSITION_RELOAD);
2883 }
[email protected]46bb5e9c2013-10-03 22:16:472884}
2885
[email protected]d202a7c2012-01-04 07:53:472886void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572887 DCHECK_LT(index, GetEntryCount());
2888 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312889 DiscardNonCommittedEntries();
2890
Nate Chapin9eb16be72022-09-23 22:54:312891 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312892 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122893 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312894 last_committed_entry_index_--;
2895}
2896
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572897NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272898 // If there is no pending_entry_, there should be no pending_entry_index_.
2899 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2900
2901 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362902 // at that index. An exception is while a reload of a post commit error page
2903 // is ongoing; in that case pending entry will point to the entry replaced
2904 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272905 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362906 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2907 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272908
[email protected]022af742011-12-28 18:37:252909 return pending_entry_;
2910}
2911
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572912int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272913 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:272914 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:552915 return pending_entry_index_;
2916}
2917
avi25764702015-06-23 15:43:372918void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:572919 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:362920 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:312921 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:002922 bool in_fenced_frame_tree,
2923 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:312924 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
2925 // set because:
2926 // 1) They don't influence the history of the outer page.
2927 // 2) They are always replace only navigation (there is always only one entry
2928 // in their history stack).
2929 // 3) Are not top level navigations and appear similar to iframes.
2930 // Navigations of the fenced frame might create a new NavigationEntry, which
2931 // will call this function. Non fenced frame navigations will never have
2932 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
2933 // InsertOrReplaceEntry.
2934 DCHECK_EQ(in_fenced_frame_tree,
2935 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
2936 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:202937
avi5cad4912015-06-19 05:25:442938 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
2939 // need to keep continuity with the pending entry, so copy the pending entry's
2940 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
2941 // then the renderer navigated on its own, independent of the pending entry,
2942 // so don't copy anything.
2943 if (pending_entry_ && pending_entry_index_ == -1)
2944 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:202945
Rakina Zata Amnia4e27222021-12-22 01:05:002946 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:202947
creisee17e932015-07-17 17:56:222948 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:452949 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:102950 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572951 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:362952 // If the new entry is a post-commit error page, we store the current last
2953 // committed entry to the side so that we can put it back when navigating
2954 // away from the error.
2955 if (was_post_commit_error) {
2956 DCHECK(!entry_replaced_by_post_commit_error_);
2957 entry_replaced_by_post_commit_error_ =
2958 std::move(entries_[last_committed_entry_index_]);
2959 }
dcheng36b6aec92015-12-26 06:16:362960 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:222961 return;
2962 }
[email protected]765b35502008-08-21 00:51:202963
creis37979a62015-08-04 19:48:182964 // We shouldn't see replace == true when there's no committed entries.
2965 DCHECK(!replace);
2966
Michael Thiessen9b14d512019-09-23 21:19:472967 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:202968
Shivani Sharmad8c8d652019-02-13 17:27:572969 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:202970
dcheng36b6aec92015-12-26 06:16:362971 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:202972 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:292973}
2974
Shivani Sharmad8c8d652019-02-13 17:27:572975void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:162976 if (entries_.size() < max_entry_count())
2977 return;
2978
2979 DCHECK_EQ(max_entry_count(), entries_.size());
2980 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:572981 CHECK_EQ(pending_entry_index_, -1);
2982
2983 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:422984 // Retrieve the oldest skippable entry.
2985 for (; index < GetEntryCount(); index++) {
2986 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
2987 break;
Shivani Sharmad8c8d652019-02-13 17:27:572988 }
2989
2990 // If there is no skippable entry or if it is the last committed entry then
2991 // fall back to pruning the oldest entry. It is not safe to prune the last
2992 // committed entry.
2993 if (index == GetEntryCount() || index == last_committed_entry_index_)
2994 index = 0;
2995
2996 bool should_succeed = RemoveEntryAtIndex(index);
2997 DCHECK_EQ(true, should_succeed);
2998
2999 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253000}
3001
clamy3cb9bea92018-07-10 12:42:023002void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163003 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203004 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133005 absl::optional<blink::scheduler::TaskAttributionId>
3006 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203007 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503008 TRACE_EVENT0("navigation",
3009 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273010 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023011 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363012 if (pending_entry_index_ != -1) {
3013 // The pending entry may not be in entries_ if a post-commit error page is
3014 // showing.
3015 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3016 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3017 }
Gyuyoung Kim107c2a02021-04-13 01:49:303018 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573019 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013020 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033021 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573022 int nav_entry_id = pending_entry_->GetUniqueID();
Nate Chapinbf682fa32022-09-26 22:41:203023 bool is_browser_initiated = !initiator_rfh;
Yoav Weiss8c573952022-11-17 17:35:133024 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3025 // the same as the top level frame being navigated.
3026 if (root->current_frame_host() != initiator_rfh) {
3027 soft_navigation_heuristics_task_id = absl::nullopt;
3028 }
Arthur Sonzogni620cec62018-12-13 13:08:573029
[email protected]83c2e232011-10-07 21:36:463030 // If we were navigating to a slow-to-commit page, and the user performs
3031 // a session history navigation to the last committed page, RenderViewHost
3032 // will force the throbber to start, but WebKit will essentially ignore the
3033 // navigation, and won't send a message to stop the throbber. To prevent this
3034 // from happening, we drop the navigation here and stop the slow-to-commit
3035 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023036 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083037 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273038 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033039 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123040
[email protected]83c2e232011-10-07 21:36:463041 DiscardNonCommittedEntries();
3042 return;
3043 }
3044
creisce0ef3572017-01-26 17:53:083045 // Compare FrameNavigationEntries to see which frames in the tree need to be
3046 // navigated.
clamy3cb9bea92018-07-10 12:42:023047 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3048 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Nate Chapin45f620582021-09-30 17:45:433049 FindFramesToNavigate(root, reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133050 soft_navigation_heuristics_task_id, &same_document_loads,
3051 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303052
3053 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573054 // We were unable to match any frames to navigate. This can happen if a
3055 // history navigation targets a subframe that no longer exists
3056 // (https://crbug.com/705550). In this case, we need to update the current
3057 // history entry to the pending one but keep the main document loaded. We
3058 // also need to ensure that observers are informed about the updated
3059 // current history entry (e.g., for greying out back/forward buttons), and
3060 // that renderer processes update their history offsets. The easiest way
3061 // to do all that is to schedule a "redundant" same-document navigation in
3062 // the main frame.
3063 //
3064 // Note that we don't want to remove this history entry, as it might still
3065 // be valid later, since a frame that it's targeting may be recreated.
3066 //
3067 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3068 // need to repeat history navigations until finding the one that works.
3069 // Consider changing this behavior to keep looking for the first valid
3070 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023071 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423072 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573073 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573074 ReloadType::NONE /* reload_type */,
3075 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433076 false /* is_history_navigation_in_new_child */,
3077 is_browser_initiated);
clamy3cb9bea92018-07-10 12:42:023078 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573079 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023080 DiscardPendingEntry(false);
3081 return;
3082 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573083 same_document_loads.push_back(std::move(navigation_request));
3084
3085 // Sanity check that we never take this branch for any kinds of reloads,
3086 // as those should've queued a different-document load in the main frame.
3087 DCHECK(!is_forced_reload);
3088 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303089 }
3090
Nate Chapinbf682fa32022-09-26 22:41:203091 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163092 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203093 if (initiator_rfh && initiator_rfh->IsSandboxed(
3094 network::mojom::WebSandboxFlags::kTopNavigation)) {
3095 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3096 initiator_rfh, same_document_loads) &&
3097 DoesSandboxNavigationStayWithinSubtree(
3098 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503099 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163100 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203101 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3102 initiator_rfh,
3103 navigates_inside_tree
3104 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3105 : blink::mojom::WebFeature::
3106 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523107
3108 // If the navigation occurred outside the tree discard it because
3109 // the sandboxed frame didn't have permission to navigate outside
3110 // its tree. If it is possible that the navigation is both inside and
3111 // outside the frame tree and we discard it entirely because we don't
3112 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143113 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203114 // If a |navigation_api_key| was provided, this navigation originated from
3115 // the navigation API. Notify the renderer that the navigation was
3116 // cancelled so the navigation API can fire an error event and reject the
3117 // relevant promise.
3118 if (navigation_api_key) {
3119 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3120 *navigation_api_key,
3121 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3122 }
Dave Tapuska855c1e12019-08-23 20:45:523123 DiscardPendingEntry(false);
3124 return;
3125 }
Dave Tapuska8bfd84c2019-03-26 20:47:163126 }
3127
Carlos Caballero539a421c2020-07-06 10:25:573128 // BackForwardCache:
3129 // Navigate immediately if the document is in the BackForwardCache.
3130 if (back_forward_cache_.GetEntry(nav_entry_id)) {
3131 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3132 DCHECK_EQ(reload_type, ReloadType::NONE);
3133 auto navigation_request = CreateNavigationRequestFromEntry(
3134 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3135 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433136 false /* is_history_navigation_in_new_child */, is_browser_initiated);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053137 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573138
3139 return;
3140 }
3141
3142 // History navigation might try to reuse a specific BrowsingInstance, already
3143 // used by a page in the cache. To avoid having two different main frames that
3144 // live in the same BrowsingInstance, evict the all pages with this
3145 // BrowsingInstance from the cache.
3146 //
3147 // For example, take the following scenario:
3148 //
3149 // A1 = Some page on a.com
3150 // A2 = Some other page on a.com
3151 // B3 = An uncacheable page on b.com
3152 //
3153 // Then the following navigations occur:
3154 // A1->A2->B3->A1
3155 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3156 // take its place) and A1 will be created in the same BrowsingInstance (and
3157 // SiteInstance), as A2.
3158 //
3159 // If we didn't do anything, both A1 and A2 would remain alive in the same
3160 // BrowsingInstance/SiteInstance, which is unsupported by
3161 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3162 // A2 from the cache.
3163 if (pending_entry_->site_instance()) {
3164 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3165 pending_entry_->site_instance());
3166 }
3167
Rakina Zata Amnid605d462022-06-01 10:17:033168 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3169 pending_entry_ && pending_entry_->IsRestored());
3170 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3171 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3172 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3173 pending_entry_index_);
3174 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3175 last_committed_entry_index_);
3176 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3177 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3178 pending_entry_ && pending_entry_->IsInitialEntry());
3179 SCOPED_CRASH_KEY_BOOL(
3180 "nav_reentrancy", "pending_entry_initial2",
3181 pending_entry_ &&
3182 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3183 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3184 IsInitialNavigation());
3185 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3186 IsInitialBlankNavigation());
3187 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3188 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3189 (int)pending_reload_);
3190
clamy3cb9bea92018-07-10 12:42:023191 // This call does not support re-entrancy. See http://crbug.com/347742.
3192 CHECK(!in_navigate_to_pending_entry_);
3193 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303194
Rakina Zata Amnid605d462022-06-01 10:17:033195 // If the navigation-reentrancy is caused by calling
3196 // NavigateToExistingPendingEntry twice, this will note the previous call's
3197 // pending entry's ID.
3198 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3199 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3200
arthursonzogni66f711c2019-10-08 14:40:363201 // It is not possible to delete the pending NavigationEntry while navigating
3202 // to it. Grab a reference to delay potential deletion until the end of this
3203 // function.
3204 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3205
creis4e2ecb72015-06-20 00:46:303206 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023207 for (auto& item : same_document_loads) {
3208 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053209 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303210 }
clamy3cb9bea92018-07-10 12:42:023211 for (auto& item : different_document_loads) {
3212 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053213 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303214 }
clamy3cb9bea92018-07-10 12:42:023215
3216 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303217}
3218
Alex Moshchuk3a4e77a2020-05-29 21:32:573219NavigationControllerImpl::HistoryNavigationAction
3220NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303221 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573222 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423223 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583224 // Only active and prerendered documents are allowed to navigate in their
3225 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423226 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013227 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583228 // - If the document is in pending deletion, the browser already committed
3229 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3230 // - If the document is in back-forward cache, it's not allowed to navigate
3231 // as it should remain frozen. Ignore the request and evict the document
3232 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423233 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583234 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423235 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113236 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3237 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423238 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113239 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423240 }
arthursonzogni03f76152019-02-12 10:35:203241
Alex Moshchuk3a4e77a2020-05-29 21:32:573242 // Reloads should result in a different-document load. Note that reloads may
3243 // also happen via the |needs_reload_| mechanism where the reload_type is
3244 // NONE, so detect this by comparing whether we're going to the same
3245 // entry that we're currently on. Similarly to above, only main frames
3246 // should reach this. Note that subframes support reloads, but that's done
3247 // via a different path that doesn't involve FindFramesToNavigate (see
3248 // RenderFrameHost::Reload()).
3249 if (reload_type != ReloadType::NONE ||
3250 pending_entry_index_ == last_committed_entry_index_) {
3251 DCHECK(frame->IsMainFrame());
3252 return HistoryNavigationAction::kDifferentDocument;
3253 }
3254
Alex Moshchuk47d1a4bd2020-06-01 22:15:343255 // If there is no new FrameNavigationEntry for the frame, ignore the
3256 // load. For example, this may happen when going back to an entry before a
3257 // frame was created. Suppose we commit a same-document navigation that also
3258 // results in adding a new subframe somewhere in the tree. If we go back,
3259 // the new subframe will be missing a FrameNavigationEntry in the previous
3260 // NavigationEntry, but we shouldn't delete or change what's loaded in
3261 // it.
3262 //
Alex Moshchuke65c39272020-06-03 17:55:373263 // Note that in this case, there is no need to keep looking for navigations
3264 // in subframes, which would be missing FrameNavigationEntries as well.
3265 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343266 // It's important to check this before checking |old_item| below, since both
3267 // might be null, and in that case we still shouldn't change what's loaded in
3268 // this frame. Note that scheduling any loads assumes that |new_item| is
3269 // non-null. See https://crbug.com/1088354.
3270 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3271 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373272 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343273
Charlie Reisa474fb62022-03-17 02:31:363274 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3275 // which history item it is currently on, since this may be different than the
3276 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3277 // (e.g., if a history navigation is targeting multiple frames and only some
3278 // have committed so far).
creis4e2ecb72015-06-20 00:46:303279 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363280 frame->current_frame_host()->last_committed_frame_entry();
3281 if (!old_item) {
3282 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3283 // fall back to the last committed NavigationEntry's record for this frame.
3284 // This may happen in cases like the initial state of the RenderFrameHost.
3285 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3286 // accurate FrameNavigationEntry and eliminate this case.
3287 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3288 }
3289 // If neither approach finds a FrameNavigationEntry, schedule a
3290 // different-document load.
3291 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573292 if (!old_item)
3293 return HistoryNavigationAction::kDifferentDocument;
3294
Alex Moshchuk3a4e77a2020-05-29 21:32:573295 // If the new item is not in the same SiteInstance, schedule a
3296 // different-document load. Newly restored items may not have a SiteInstance
3297 // yet, in which case it will be assigned on first commit.
3298 if (new_item->site_instance() &&
3299 new_item->site_instance() != old_item->site_instance())
3300 return HistoryNavigationAction::kDifferentDocument;
3301
3302 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313303 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3304 // that we do this even if the history navigation would not be modifying this
3305 // frame were it live.
3306 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573307 return HistoryNavigationAction::kDifferentDocument;
3308
3309 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313310 // Starting a navigation after a crash early-promotes the speculative
3311 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3312 // committed yet, so we can not possibly perform a same-document history
3313 // navigation. The frame would need to be reloaded with a cross-document
3314 // navigation.
3315 if (!frame->current_frame_host()->has_committed_any_navigation())
3316 return HistoryNavigationAction::kDifferentDocument;
3317
creis54131692016-08-12 18:32:253318 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493319 // sequence number but different item sequence number.
3320 if (new_item->document_sequence_number() ==
3321 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573322 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493323 }
avib48cb312016-05-05 21:35:003324
Alex Moshchuk3a4e77a2020-05-29 21:32:573325 // Otherwise, if both item and document sequence numbers differ, this
3326 // should be a different document load.
3327 return HistoryNavigationAction::kDifferentDocument;
3328 }
3329
3330 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373331 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573332 DCHECK_EQ(new_item->document_sequence_number(),
3333 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373334 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573335}
3336
3337void NavigationControllerImpl::FindFramesToNavigate(
3338 FrameTreeNode* frame,
3339 ReloadType reload_type,
Nate Chapin45f620582021-09-30 17:45:433340 bool is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133341 absl::optional<blink::scheduler::TaskAttributionId>
3342 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573343 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3344 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3345 DCHECK(pending_entry_);
3346 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3347
3348 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3349
3350 if (action == HistoryNavigationAction::kSameDocument) {
3351 std::unique_ptr<NavigationRequest> navigation_request =
3352 CreateNavigationRequestFromEntry(
3353 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133354 /*is_same_document_history_load=*/true,
3355 /*is_history_navigation_in_new_child_frame=*/false,
3356 is_browser_initiated, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573357 if (navigation_request) {
3358 // Only add the request if was properly created. It's possible for the
3359 // creation to fail in certain cases, e.g. when the URL is invalid.
3360 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303361 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573362 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473363 std::unique_ptr<NavigationRequest> navigation_request =
3364 CreateNavigationRequestFromEntry(
3365 frame, pending_entry_, new_item, reload_type,
3366 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433367 false /* is_history_navigation_in_new_child */,
3368 is_browser_initiated);
Lei Zhang96031532019-10-10 19:05:473369 if (navigation_request) {
3370 // Only add the request if was properly created. It's possible for the
3371 // creation to fail in certain cases, e.g. when the URL is invalid.
3372 different_document_loads->push_back(std::move(navigation_request));
3373 }
3374 // For a different document, the subframes will be destroyed, so there's
3375 // no need to consider them.
3376 return;
Alex Moshchuke65c39272020-06-03 17:55:373377 } else if (action == HistoryNavigationAction::kStopLooking) {
3378 return;
creis4e2ecb72015-06-20 00:46:303379 }
3380
Yoav Weiss8c573952022-11-17 17:35:133381 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3382 // we currently only support soft navigation heuristics for the top level
3383 // frame.
creis4e2ecb72015-06-20 00:46:303384 for (size_t i = 0; i < frame->child_count(); i++) {
Nate Chapin45f620582021-09-30 17:45:433385 FindFramesToNavigate(frame->child_at(i), reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133386 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433387 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303388 }
3389}
3390
Harkiran Bolariaba823e42021-05-21 18:30:363391base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243392 const LoadURLParams& params) {
3393 // Find the appropriate FrameTreeNode.
3394 FrameTreeNode* node = nullptr;
3395 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3396 !params.frame_name.empty()) {
3397 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033398 ? frame_tree_->FindByID(params.frame_tree_node_id)
3399 : frame_tree_->FindByName(params.frame_name);
3400 DCHECK(!node || node->frame_tree() == &*frame_tree_);
clamy21718cc22018-06-13 13:34:243401 }
3402
3403 // If no FrameTreeNode was specified, navigate the main frame.
3404 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033405 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243406
Camille Lamy5193caa2018-10-12 11:59:423407 // Compute overrides to the LoadURLParams for |override_user_agent|,
3408 // |should_replace_current_entry| and |has_user_gesture| that will be used
3409 // both in the creation of the NavigationEntry and the NavigationRequest.
3410 // Ideally, the LoadURLParams themselves would be updated, but since they are
3411 // passed as a const reference, this is not possible.
3412 // TODO(clamy): When we only create a NavigationRequest, move this to
3413 // CreateNavigationRequestFromLoadURLParams.
3414 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3415 GetLastCommittedEntry());
3416
Rakina Zata Amnie2d31312022-11-18 03:38:453417 // An entry replacement must happen if the current browsing context should
3418 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333419 bool should_replace_current_entry =
3420 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453421 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423422
clamy21718cc22018-06-13 13:34:243423 // Javascript URLs should not create NavigationEntries. All other navigations
3424 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243425 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373426 std::unique_ptr<NavigationEntryImpl> entry =
3427 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3428 should_replace_current_entry,
3429 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243430 DiscardPendingEntry(false);
3431 SetPendingEntry(std::move(entry));
3432 }
3433
3434 // Renderer-debug URLs are sent to the renderer process immediately for
3435 // processing and don't need to create a NavigationRequest.
3436 // Note: this includes navigations to JavaScript URLs, which are considered
3437 // renderer-debug URLs.
3438 // Note: we intentionally leave the pending entry in place for renderer debug
3439 // URLs, unlike the cases below where we clear it if the navigation doesn't
3440 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303441 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483442 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3443 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153444 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Oleg Davydov2cc0167b2019-02-05 14:32:483445 params.url, browser_context_)) {
3446 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363447 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483448 }
3449
clamy21718cc22018-06-13 13:34:243450 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363451 return nullptr;
clamy21718cc22018-06-13 13:34:243452 }
3453
Antonio Sartori78a749f2020-11-30 12:03:393454 DCHECK(pending_entry_);
3455
clamy21718cc22018-06-13 13:34:243456 // Convert navigations to the current URL to a reload.
3457 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3458 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3459 // DevTools sometimes issues navigations to main frames that they do not
3460 // expect to see treated as reload, and it only works because they pass a
3461 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3462 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543463 ReloadType reload_type = params.reload_type;
3464 if (reload_type == ReloadType::NONE &&
3465 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043466 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243467 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243468 params.load_type ==
3469 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543470 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243471 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473472 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393473
3474 // If this is a reload of an existing FrameNavigationEntry and we had a
3475 // policy container for it, then we should copy it into the pending entry,
3476 // so that it is copied to the navigation request in
3477 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453478 FrameNavigationEntry* previous_frame_entry =
3479 GetLastCommittedEntry()->GetFrameEntry(node);
3480 if (previous_frame_entry &&
3481 previous_frame_entry->policy_container_policies()) {
3482 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3483 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393484 }
3485 }
3486
3487 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173488 // document, then we should copy the document polices from RenderFrameHost's
3489 // PolicyContainerHost. The NavigationRequest will create a new
3490 // PolicyContainerHost with the document policies from the |pending_entry_|,
3491 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3492 // the navigation. This way, we ensure that we keep enforcing the right
3493 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453494 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393495 if (node->current_frame_host() &&
3496 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193497 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163498 node->current_frame_host()
3499 ->policy_container_host()
3500 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233501 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393502 }
clamy21718cc22018-06-13 13:34:243503 }
3504
3505 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263506 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243507
Tsuyoshi Horo167ca6432022-03-09 05:16:393508 // This will be used to set the Navigation Timing API navigationStart
3509 // parameter for browser navigations in new tabs (intents, tabs opened through
3510 // "Open link in new tab"). If the navigation must wait on the current
3511 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3512 // will be updated when the BeforeUnload ack is received.
3513 const auto navigation_start_time = base::TimeTicks::Now();
3514
Camille Lamy5193caa2018-10-12 11:59:423515 std::unique_ptr<NavigationRequest> request =
3516 CreateNavigationRequestFromLoadParams(
3517 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143518 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393519 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3520 navigation_start_time);
clamy21718cc22018-06-13 13:34:243521
3522 // If the navigation couldn't start, return immediately and discard the
3523 // pending NavigationEntry.
3524 if (!request) {
3525 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363526 return nullptr;
clamy21718cc22018-06-13 13:34:243527 }
3528
Camille Lamy5193caa2018-10-12 11:59:423529#if DCHECK_IS_ON()
3530 // Safety check that NavigationRequest and NavigationEntry match.
3531 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3532#endif
3533
clamy21718cc22018-06-13 13:34:243534 // This call does not support re-entrancy. See http://crbug.com/347742.
3535 CHECK(!in_navigate_to_pending_entry_);
3536 in_navigate_to_pending_entry_ = true;
3537
arthursonzogni66f711c2019-10-08 14:40:363538 // It is not possible to delete the pending NavigationEntry while navigating
3539 // to it. Grab a reference to delay potential deletion until the end of this
3540 // function.
3541 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3542
Harkiran Bolariaba823e42021-05-21 18:30:363543 base::WeakPtr<NavigationHandle> created_navigation_handle(
3544 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053545 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243546
3547 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363548 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243549}
3550
clamyea99ea12018-05-28 13:54:233551void NavigationControllerImpl::HandleRendererDebugURL(
3552 FrameTreeNode* frame_tree_node,
3553 const GURL& url) {
3554 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243555 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3556 // the renderer process is not live, unless it is the initial navigation
3557 // of the tab.
clamyea99ea12018-05-28 13:54:233558 if (!IsInitialNavigation()) {
3559 DiscardNonCommittedEntries();
3560 return;
3561 }
Fergal Dalyecd3b0202020-06-25 01:57:373562 // The current frame is always a main frame. If IsInitialNavigation() is
3563 // true then there have been no navigations and any frames of this tab must
3564 // be in the same renderer process. If that has crashed then the only frame
3565 // that can be revived is the main frame.
3566 frame_tree_node->render_manager()
3567 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233568 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223569
3570 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3571 // notification, so set is loading to true here to properly surface it when
3572 // the renderer process is done handling the URL.
3573 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3574 if (!url.SchemeIs(url::kJavaScriptScheme)) {
3575 bool was_loading = frame_tree_node->frame_tree()
3576 ->LoadingTree()
3577 ->IsLoadingIncludingInnerFrameTrees();
3578 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
3579 frame_tree_node->DidStartLoading(true /* should_show_loading_ui */,
3580 was_loading);
3581 }
clamyea99ea12018-05-28 13:54:233582 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3583}
3584
clamy21718cc22018-06-13 13:34:243585std::unique_ptr<NavigationEntryImpl>
3586NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3587 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423588 const LoadURLParams& params,
3589 bool override_user_agent,
3590 bool should_replace_current_entry,
3591 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393592 // Browser initiated navigations might not have a blob_url_loader_factory set
3593 // in params even if the navigation is to a blob URL. If that happens, lookup
3594 // the correct url loader factory to use here.
3595 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483596 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473597 // Resolve the blob URL in the storage partition associated with the target
3598 // frame. This is the storage partition the URL will be loaded in, and only
3599 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393600 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473601 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393602 }
3603
clamy21718cc22018-06-13 13:34:243604 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443605 // extra_headers in params are \n separated; navigation entries want \r\n.
3606 std::string extra_headers_crlf;
3607 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243608
3609 // For subframes, create a pending entry with a corresponding frame entry.
3610 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453611 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243612 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083613 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243614 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073615 params.url, absl::nullopt, params.referrer, params.initiator_origin,
Miyoung Shin5d77f72072020-10-09 15:14:203616 params.redirect_chain, blink::PageState(), "GET", -1,
Antonio Sartori78a749f2020-11-30 12:03:393617 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483618 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393619 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163620 // a conversion of a new navigation into a reload, we will set the right
3621 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193622 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243623 } else {
3624 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173625 // If `node` is the outermost main frame, it rewrites a virtual url in order
3626 // to adjust the original input url if needed. For inner frames such as
3627 // fenced frames or subframes, they don't rewrite urls as the urls are not
3628 // input urls by users.
3629 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy21718cc22018-06-13 13:34:243630 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063631 params.url, params.referrer, params.initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:103632 params.source_site_instance.get(), params.transition_type,
3633 params.is_renderer_initiated, extra_headers_crlf, browser_context_,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173634 blob_url_loader_factory, rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243635 entry->set_source_site_instance(
3636 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3637 entry->SetRedirectChain(params.redirect_chain);
3638 }
3639
3640 // Set the FTN ID (only used in non-site-per-process, for tests).
3641 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243642 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423643 entry->SetIsOverridingUserAgent(override_user_agent);
3644 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543645 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243646
clamy21718cc22018-06-13 13:34:243647 switch (params.load_type) {
3648 case LOAD_TYPE_DEFAULT:
3649 break;
3650 case LOAD_TYPE_HTTP_POST:
3651 entry->SetHasPostData(true);
3652 entry->SetPostData(params.post_data);
3653 break;
3654 case LOAD_TYPE_DATA:
3655 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3656 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283657#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243658 entry->SetDataURLAsString(params.data_url_as_string);
3659#endif
3660 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3661 break;
clamy21718cc22018-06-13 13:34:243662 }
3663
3664 // TODO(clamy): NavigationEntry is meant for information that will be kept
3665 // after the navigation ended and therefore is not appropriate for
3666 // started_from_context_menu. Move started_from_context_menu to
3667 // NavigationUIData.
3668 entry->set_started_from_context_menu(params.started_from_context_menu);
3669
3670 return entry;
3671}
3672
clamyea99ea12018-05-28 13:54:233673std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423674NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3675 FrameTreeNode* node,
3676 const LoadURLParams& params,
3677 bool override_user_agent,
3678 bool should_replace_current_entry,
3679 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143680 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423681 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573682 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393683 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223684 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493685 bool is_embedder_initiated_fenced_frame_navigation,
3686 bool is_unfenced_top_navigation) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573687 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283688 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533689 // All renderer-initiated navigations must have an initiator_origin.
3690 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513691
Camille Lamy5193caa2018-10-12 11:59:423692 GURL url_to_load;
3693 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323694
Camille Lamy2baa8022018-10-19 16:43:173695 // For main frames, rewrite the URL if necessary and compute the virtual URL
3696 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263697 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423698 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173699 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423700 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423701
Camille Lamy2baa8022018-10-19 16:43:173702 // For DATA loads, override the virtual URL.
3703 if (params.load_type == LOAD_TYPE_DATA)
3704 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423705
Camille Lamy2baa8022018-10-19 16:43:173706 if (virtual_url.is_empty())
3707 virtual_url = url_to_load;
3708
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573709 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283710
Aran Gilman249eb122019-12-02 23:32:463711 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3712 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3713 // return different results, leading to a different URL in the
3714 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3715 // pending NavigationEntry, as we'll only make one call to
3716 // RewriteUrlForNavigation.
3717 VLOG_IF(1, (url_to_load != frame_entry->url()))
3718 << "NavigationRequest and FrameEntry have different URLs: "
3719 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283720
Camille Lamy2baa8022018-10-19 16:43:173721 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423722 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173723 // NavigationRequest.
3724 } else {
3725 url_to_load = params.url;
3726 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243727 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173728 }
Camille Lamy5193caa2018-10-12 11:59:423729
Ehsan Karamad44fc72112019-02-26 18:15:473730 if (node->render_manager()->is_attaching_inner_delegate()) {
3731 // Avoid starting any new navigations since this node is now preparing for
3732 // attaching an inner delegate.
3733 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203734 }
Camille Lamy5193caa2018-10-12 11:59:423735
Ian Vollick1c6dd3e2022-04-13 02:06:263736 if (!IsValidURLForNavigation(node->IsOutermostMainFrame(), virtual_url,
3737 url_to_load))
Camille Lamy5193caa2018-10-12 11:59:423738 return nullptr;
3739
danakjd83d706d2020-11-25 22:11:123740 // Look for a pending commit that is to another document in this
3741 // FrameTreeNode. If one exists, then the last committed URL will not be the
3742 // current URL by the time this navigation commits.
3743 bool has_pending_cross_document_commit =
3744 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213745 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123746
Minggang Wangb9f3fa92021-07-01 15:30:313747 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493748 /*old_url=*/node->current_url(),
3749 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3750 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133751 /*is_same_document_history_load=*/false,
3752 is_embedder_initiated_fenced_frame_navigation,
3753 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423754
3755 // Create the NavigationParams based on |params|.
3756
Hiroki Nakagawa4ed61282021-06-18 05:37:233757 bool is_view_source_mode = entry->IsViewSourceMode();
3758 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293759
Antonio Sartori6984c742021-08-26 08:03:413760 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Hiroki Nakagawa4ed61282021-06-18 05:37:233761 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293762 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253763 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293764
Minggang Wangb9f3fa92021-07-01 15:30:313765 blink::mojom::CommonNavigationParamsPtr common_params =
3766 blink::mojom::CommonNavigationParams::New(
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513767 url_to_load, params.initiator_origin,
3768 blink::mojom::Referrer::New(params.referrer.url,
3769 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213770 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513771 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393772 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513773 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143774 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413775 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273776 false /* has_text_fragment_token */,
3777 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3778 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513779 false /* is_history_navigation_in_new_child_frame */,
Nan Lind91c8152021-10-21 16:22:373780 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423781
Minggang Wangb9f3fa92021-07-01 15:30:313782 blink::mojom::CommitNavigationParamsPtr commit_params =
3783 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403784 absl::nullopt,
Antonio Sartori3e8de6d2021-07-26 10:28:413785 // The correct storage key will be computed before committing the
3786 // navigation.
Pâris Meuleman4d97a702022-07-05 10:42:003787 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323788 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503789 std::vector<net::RedirectInfo>(), params.post_content_type,
3790 common_params->url, common_params->method,
3791 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313792 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133793 entry->GetSubframeUniqueNames(node),
3794 /*intended_as_new_entry=*/true,
3795 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143796 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3797 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133798 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313799 params.should_clear_history_list,
3800 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223801 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133802 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513803 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283804#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133805 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143806#endif
Yoav Weiss8c573952022-11-17 17:35:133807 /*is_browser_initiated=*/!params.is_renderer_initiated,
3808 /*web_bundle_physical_url=*/GURL(),
3809 /*base_url_override_for_web_bundle=*/GURL(),
3810 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073811 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133812 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3813 /*origin_agent_cluster=*/false,
3814 /*origin_agent_cluster_left_as_default=*/true,
3815 /*enabled_client_hints=*/
3816 std::vector<network::mojom::WebClientHintsType>(),
3817 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3818 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013819 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133820 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
3821 /*ad_auction_components=*/absl::nullopt,
shivanigithubc7b97ca2022-04-05 19:41:403822 /*fenced_frame_reporting_metadata=*/nullptr,
Clark DuVall8ee487a22021-11-10 02:25:583823 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133824 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
3825 /*fallback_srcdoc_baseurl_value=*/GURL(),
3826 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283827 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133828 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443829 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423830 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133831 /*view_transition_state=*/absl::nullopt,
3832 /*soft_navigation_heuristics_task_id=*/absl::nullopt);
Xiaohan Wang7f8052e02022-01-14 18:44:283833#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423834 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143835 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423836 }
3837#endif
3838
Lucas Furukawa Gadania9c45682019-07-31 22:05:143839 commit_params->was_activated = params.was_activated;
Camille Lamy5193caa2018-10-12 11:59:423840
Camille Lamy5193caa2018-10-12 11:59:423841 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3842 std::string extra_headers_crlf;
3843 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093844
3845 auto navigation_request = NavigationRequest::CreateBrowserInitiated(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143846 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083847 !params.is_renderer_initiated, params.was_opener_suppressed,
Antonio Sartori9a82f6f32020-12-14 09:22:453848 params.initiator_frame_token.has_value()
3849 ? &(params.initiator_frame_token.value())
3850 : nullptr,
3851 params.initiator_process_id, extra_headers_crlf, frame_entry, entry,
jongdeok.kim5de823b32022-06-14 04:37:503852 params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213853 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Garrett Tanzer47852462022-07-20 18:16:413854 params.impression, params.is_pdf,
3855 is_embedder_initiated_fenced_frame_navigation);
Yao Xiaodc5ed102019-06-04 19:19:093856 navigation_request->set_from_download_cross_origin_redirect(
3857 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:553858 navigation_request->set_force_new_browsing_instance(
3859 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:093860 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:423861}
3862
3863std::unique_ptr<NavigationRequest>
3864NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:233865 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573866 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:233867 FrameNavigationEntry* frame_entry,
3868 ReloadType reload_type,
3869 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:433870 bool is_history_navigation_in_new_child_frame,
Yoav Weiss8c573952022-11-17 17:35:133871 bool is_browser_initiated,
3872 absl::optional<blink::scheduler::TaskAttributionId>
3873 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:343874 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:233875 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:433876 // We should never navigate to an existing initial NavigationEntry that is the
3877 // initial NavigationEntry for the initial empty document that hasn't been
3878 // overridden by the synchronous about:blank commit, to preserve previous
3879 // behavior where trying to reload when the main frame is on the initial empty
3880 // document won't result in a navigation.
3881 // See also https://crbug.com/1277414.
3882 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:323883
clamyea99ea12018-05-28 13:54:233884 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:013885 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573886 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:233887 // We may have been redirected when navigating to the current URL.
3888 // Use the URL the user originally intended to visit as signaled by the
3889 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:013890 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573891 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:233892 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:233893 }
3894
Ehsan Karamad44fc72112019-02-26 18:15:473895 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
3896 // Avoid starting any new navigations since this node is now preparing for
3897 // attaching an inner delegate.
3898 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203899 }
3900
Ian Vollick1c6dd3e2022-04-13 02:06:263901 if (!IsValidURLForNavigation(frame_tree_node->IsOutermostMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573902 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:233903 return nullptr;
3904 }
3905
clamyea99ea12018-05-28 13:54:233906 // This will be used to set the Navigation Timing API navigationStart
3907 // parameter for browser navigations in new tabs (intents, tabs opened through
3908 // "Open link in new tab"). If the navigation must wait on the current
3909 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3910 // will be updated when the BeforeUnload ack is received.
3911 base::TimeTicks navigation_start = base::TimeTicks::Now();
clamyea99ea12018-05-28 13:54:233912
danakjd83d706d2020-11-25 22:11:123913 // Look for a pending commit that is to another document in this
3914 // FrameTreeNode. If one exists, then the last committed URL will not be the
3915 // current URL by the time this navigation commits.
3916 bool has_pending_cross_document_commit =
3917 frame_tree_node->render_manager()
3918 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:493919 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:213920 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123921
Minggang Wangb9f3fa92021-07-01 15:30:313922 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:123923 /*old_url=*/frame_tree_node->current_url(),
3924 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:493925 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:493926 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:133927 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:493928 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:423929
3930 // A form submission may happen here if the navigation is a
3931 // back/forward/reload navigation that does a form resubmission.
3932 scoped_refptr<network::ResourceRequestBody> request_body;
3933 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:503934 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
3935 // entry. This way, it could be directly retrieved here. Right now, it is only
3936 // partially recovered when request.method == "POST" and request.body exists.
3937 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:423938 if (frame_entry->method() == "POST") {
3939 request_body = frame_entry->GetPostData(&post_content_type);
3940 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:303941 post_content_type = std::string(
3942 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:503943 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:423944 }
3945
3946 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:313947 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513948 entry->ConstructCommonNavigationParams(
3949 *frame_entry, request_body, dest_url,
3950 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:383951 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:533952 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513953 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:553954 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:423955
3956 // TODO(clamy): |intended_as_new_entry| below should always be false once
3957 // Reload no longer leads to this being called for a pending NavigationEntry
3958 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:313959 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:143960 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:403961 *frame_entry, common_params->url, common_params->method,
3962 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143963 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:533964 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:483965 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133966 frame_tree_node->AncestorOrSelfHasCSPEE(),
3967 soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:143968 commit_params->post_content_type = post_content_type;
Camille Lamy5193caa2018-10-12 11:59:423969
W. James MacLeanb7d6092682022-10-05 15:23:263970 if (common_params->url.IsAboutSrcdoc()) {
3971 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
3972 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:593973 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:263974 }
clamyea99ea12018-05-28 13:54:233975 return NavigationRequest::CreateBrowserInitiated(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143976 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:433977 is_browser_initiated, false /* was_opener_suppressed */,
Takashi Toyoshimae87b7be2021-01-22 11:51:083978 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:453979 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
jongdeok.kim5de823b32022-06-14 04:37:503980 entry->extra_headers(), frame_entry, entry, is_form_submission,
Daniel Hosseinianf0fbfb42021-09-08 02:20:473981 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
3982 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:233983}
3984
[email protected]d202a7c2012-01-04 07:53:473985void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:213986 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:273987 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:403988
Takashi Toyoshimaea534ef22021-07-21 03:27:593989 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:403990 // location bar will have up-to-date information about the security style
3991 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:133992 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:403993
Abhijeet Kandalkar3dc6e602022-11-09 05:08:373994 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:573995 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:463996
[email protected]b0f724c2013-09-05 04:21:133997 // TODO(avi): Remove. http://crbug.com/170921
3998 NotificationDetails notification_details =
3999 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154000 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4001 Source<NavigationController>(this),
4002 notification_details);
initial.commit09911bf2008-07-26 23:55:294003}
4004
initial.commit09911bf2008-07-26 23:55:294005// static
[email protected]d202a7c2012-01-04 07:53:474006size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234007 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154008 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214009 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234010}
4011
[email protected]d202a7c2012-01-04 07:53:474012void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224013 if (is_active && needs_reload_)
4014 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294015}
4016
[email protected]d202a7c2012-01-04 07:53:474017void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034018 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4019 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294020 if (!needs_reload_)
4021 return;
4022
Bo Liucdfa4b12018-11-06 00:21:444023 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4024 needs_reload_type_);
4025
initial.commit09911bf2008-07-26 23:55:294026 // Calling Reload() results in ignoring state, and not loading.
4027 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4028 // cached state.
avicc872d7242015-08-19 21:26:344029 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134030 NavigateToExistingPendingEntry(
4031 ReloadType::NONE,
4032 /*initiator_rfh=*/nullptr,
4033 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4034 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454035 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434036 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274037 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344038 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134039 NavigateToExistingPendingEntry(
4040 ReloadType::NONE,
4041 /*initiator_rfh=*/nullptr,
4042 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4043 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344044 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434045 // We should never navigate to an existing initial NavigationEntry that is
4046 // the initial NavigationEntry for the initial empty document that hasn't
4047 // been overridden by the synchronous about:blank commit, to preserve
4048 // legacy behavior where trying to reload when the main frame is on the
4049 // initial empty document won't result in a navigation. See also
4050 // https://crbug.com/1277414. If there is something to reload, the
4051 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4052 // it here.
avicc872d7242015-08-19 21:26:344053 needs_reload_ = false;
4054 }
initial.commit09911bf2008-07-26 23:55:294055}
4056
Kevin McNeeccca6172021-10-19 17:11:144057base::WeakPtr<NavigationHandle>
4058NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364059 RenderFrameHost* render_frame_host,
4060 const GURL& url,
4061 const std::string& error_page_html,
4062 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134063 RenderFrameHostImpl* rfhi =
4064 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584065
4066 // Only active documents can load post-commit error pages:
4067 // - If the document is in pending deletion, the browser already committed to
4068 // destroying this RenderFrameHost so ignore loading the error page.
4069 // - If the document is in back-forward cache, it's not allowed to navigate as
4070 // it should remain frozen. Ignore the request and evict the document from
4071 // back-forward cache.
4072 // - If the document is prerendering, it can navigate but when loading error
4073 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114074 if (rfhi->IsInactiveAndDisallowActivation(
4075 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144076 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114077 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584078
Rakina Zata Amni919b7922020-12-11 09:03:134079 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414080
Minggang Wangb9f3fa92021-07-01 15:30:314081 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434082 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594083 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4084 // the frame actually committed (e.g. iframe with "src" set to a
4085 // slow-responding URL). We should rewrite the URL to about:blank in this
4086 // case, as the renderer will only think a page is an error page if it has a
4087 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134088 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314089 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434090 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334091 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414092
arthursonzogni70ac7302020-05-28 08:49:054093 // Error pages have a fully permissive FramePolicy.
4094 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4095 // error pages.
4096 commit_params->frame_policy = blink::FramePolicy();
4097
John Delaney131ad362019-08-08 21:57:414098 std::unique_ptr<NavigationRequest> navigation_request =
4099 NavigationRequest::CreateBrowserInitiated(
4100 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084101 true /* browser_initiated */, false /* was_opener_suppressed */,
Lingqi Chi82efa95e2020-12-29 05:31:194102 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454103 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
John Delaneyf43556d2020-05-04 23:19:064104 "" /* extra_headers */, nullptr /* frame_entry */,
jongdeok.kim5de823b32022-06-14 04:37:504105 nullptr /* entry */, false /* is_form_submission */,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474106 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
4107 false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364108 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414109 navigation_request->set_net_error(error);
4110 node->CreatedNavigationRequest(std::move(navigation_request));
4111 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144112
4113 // Calling BeginNavigation may destroy the NavigationRequest.
4114 base::WeakPtr<NavigationRequest> created_navigation_request(
4115 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414116 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144117 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414118}
4119
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574120void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214121 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094122 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154123 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144124 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294125}
4126
[email protected]d202a7c2012-01-04 07:53:474127void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364128 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474129 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4130 // represent a no-committed-entry state.
4131 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364132 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474133 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4134 // if `entries_` contains pre-existing entries from the NavigationController
4135 // before restore, which would not be removed and will be at the front of the
4136 // entries list, causing the index to be off by the amount of pre-existing
4137 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294138 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294139}
[email protected]765b35502008-08-21 00:51:204140
arthursonzogni69a6a1b2019-09-17 09:23:004141void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004142 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4143}
4144
4145void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4146 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474147 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104148 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4149 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294150 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474151 return;
Michael Thiessenc5676d22019-09-25 22:32:104152 }
avi45a72532015-04-07 21:01:454153 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314154
4155 if (!delegate_)
4156 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374157 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484158}
4159
avi7c6f35e2015-05-08 17:52:384160int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4161 int nav_entry_id) const {
4162 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4163 if (entries_[i]->GetUniqueID() == nav_entry_id)
4164 return i;
4165 }
4166 return -1;
4167}
4168
[email protected]d202a7c2012-01-04 07:53:474169void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574170 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254171 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574172 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574173 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4174 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254175 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374176 // Normally, cloning a NavigationEntryImpl results in sharing
4177 // FrameNavigationEntries between the original and the clone. However, when
4178 // cloning from a different NavigationControllerImpl, we want to fork the
4179 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374180 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574181 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254182 }
Rakina Zata Amnie2d31312022-11-18 03:38:454183 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274184 DCHECK(pending_entry_index_ == -1 ||
4185 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254186}
[email protected]c5b88d82012-10-06 17:03:334187
4188void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184189 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334190 get_timestamp_callback_ = get_timestamp_callback;
4191}
[email protected]8ff00d72012-10-23 19:12:214192
Shivani Sharmaffb32b82019-04-09 16:58:474193// History manipulation intervention:
4194void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474195 bool replace_entry,
4196 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404197 bool is_renderer_initiated,
4198 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454199 // Note that for a subframe, previous_document_was_activated is true if the
4200 // gesture happened in any subframe (propagated to main frame) or in the main
4201 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474202 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274203 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474204 return;
4205 }
4206 if (last_committed_entry_index_ == -1)
4207 return;
4208
Shivani Sharmac4cc8922019-04-18 03:11:174209 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474210
Alexander Timine3ec4192020-04-20 16:39:404211 // Log UKM with the URL we are navigating away from.
4212 ukm::builders::HistoryManipulationIntervention(
4213 previous_page_load_ukm_source_id)
4214 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474215}
4216
Shivani Sharmac4cc8922019-04-18 03:11:174217void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4218 int reference_index,
4219 bool skippable) {
4220 auto* reference_entry = GetEntryAtIndex(reference_index);
4221 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4222
4223 int64_t document_sequence_number =
4224 reference_entry->root_node()->frame_entry->document_sequence_number();
4225 for (int index = 0; index < GetEntryCount(); index++) {
4226 auto* entry = GetEntryAtIndex(index);
4227 if (entry->root_node()->frame_entry->document_sequence_number() ==
4228 document_sequence_number) {
4229 entry->set_should_skip_on_back_forward_ui(skippable);
4230 }
4231 }
4232}
4233
arthursonzogni66f711c2019-10-08 14:40:364234std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4235NavigationControllerImpl::ReferencePendingEntry() {
4236 DCHECK(pending_entry_);
4237 auto pending_entry_ref =
4238 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4239 pending_entry_refs_.insert(pending_entry_ref.get());
4240 return pending_entry_ref;
4241}
4242
4243void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4244 // Ignore refs that don't correspond to the current pending entry.
4245 auto it = pending_entry_refs_.find(ref);
4246 if (it == pending_entry_refs_.end())
4247 return;
4248 pending_entry_refs_.erase(it);
4249
4250 if (!pending_entry_refs_.empty())
4251 return;
4252
4253 // The pending entry may be deleted before the last PendingEntryRef.
4254 if (!pending_entry_)
4255 return;
4256
4257 // We usually clear the pending entry when the matching NavigationRequest
4258 // fails, so that an arbitrary URL isn't left visible above a committed page.
4259 //
4260 // However, we do preserve the pending entry in some cases, such as on the
4261 // initial navigation of an unmodified blank tab. We also allow the delegate
4262 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4263 // user edit the URL and try again. This may be useful in cases that the
4264 // committed page cannot be attacker-controlled. In these cases, we still
4265 // allow the view to clear the pending entry and typed URL if the user
4266 // requests (e.g., hitting Escape with focus in the address bar).
4267 //
4268 // Do not leave the pending entry visible if it has an invalid URL, since this
4269 // might be formatted in an unexpected or unsafe way.
4270 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364271 bool should_preserve_entry =
4272 (pending_entry_ == GetVisibleEntry()) &&
4273 pending_entry_->GetURL().is_valid() &&
4274 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4275 if (should_preserve_entry)
4276 return;
4277
4278 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374279 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364280}
4281
Titouan Rigoudy6ec70402021-02-02 15:42:194282std::unique_ptr<PolicyContainerPolicies>
4283NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394284 RenderFrameHostImpl* rfh,
4285 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174286 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394287 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454288 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394289 FrameNavigationEntry* previous_frame_entry =
4290 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4291
4292 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4293 // ensure we always have a FrameNavigationEntry here.
4294 if (!previous_frame_entry)
4295 return nullptr;
4296
Titouan Rigoudy6ec70402021-02-02 15:42:194297 const PolicyContainerPolicies* previous_policies =
4298 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394299
Titouan Rigoudy6ec70402021-02-02 15:42:194300 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394301 return nullptr;
4302
4303 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234304 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394305 }
4306
Titouan Rigoudy72f892d2022-05-02 18:21:234307 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394308}
4309
Hayato Ito2c8c08d02021-06-23 03:38:434310void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504311 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434312 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4313 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4314 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504315
4316 auto callback = base::BindRepeating(
4317 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4318 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4319 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4320 }
4321 },
Hayato Ito2c8c08d02021-06-23 03:38:434322 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034323 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504324}
4325
4326void NavigationControllerImpl::DidAccessInitialMainDocument() {
4327 // We may have left a failed browser-initiated navigation in the address bar
4328 // to let the user edit it and try again. Clear it now that content might
4329 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034330 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504331 DiscardPendingEntry(false);
4332
4333 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374334 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504335}
4336
4337void NavigationControllerImpl::UpdateStateForFrame(
4338 RenderFrameHostImpl* rfhi,
4339 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564340 OPTIONAL_TRACE_EVENT1("content",
4341 "NavigationControllerImpl::UpdateStateForFrame",
4342 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504343 // The state update affects the last NavigationEntry associated with the given
4344 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4345 // in the case of an UpdateState from a frame being swapped out). We track
4346 // which entry this is in the RenderFrameHost's nav_entry_id.
4347 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4348 if (!entry)
4349 return;
4350
4351 FrameNavigationEntry* frame_entry =
4352 entry->GetFrameEntry(rfhi->frame_tree_node());
4353 if (!frame_entry)
4354 return;
4355
4356 // The SiteInstance might not match if we do a cross-process navigation with
4357 // replacement (e.g., auto-subframe), in which case the swap out of the old
4358 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4359 // has already been replaced and destroyed.
4360 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4361 return;
4362
4363 if (page_state == frame_entry->page_state())
4364 return; // Nothing to update.
4365
4366 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4367
4368 // The document_sequence_number and item_sequence_number recorded in the
4369 // FrameNavigationEntry should not differ from the one coming with the update,
4370 // since it must come from the same document. Do not update it if a difference
4371 // is detected, as this indicates that |frame_entry| is not the correct one.
4372 blink::ExplodedPageState exploded_state;
4373 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4374 return;
4375
4376 if (exploded_state.top.document_sequence_number !=
4377 frame_entry->document_sequence_number() ||
4378 exploded_state.top.item_sequence_number !=
4379 frame_entry->item_sequence_number()) {
4380 return;
4381 }
4382
4383 frame_entry->SetPageState(page_state);
4384 NotifyEntryChanged(entry);
4385}
4386
Domenic Denicolacd30f5f82022-03-16 21:48:014387std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4388NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574389 Direction direction,
4390 int entry_index,
4391 const url::Origin& pending_origin,
4392 FrameTreeNode* node,
4393 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304394 int64_t pending_item_sequence_number,
4395 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014396 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454397 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174398 // Don't process the initial entry.
4399 DCHECK_EQ(GetEntryCount(), 1);
4400 return entries;
4401 }
Nate Chapind1fe3612021-04-16 20:45:574402 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304403 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574404 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4405 i += offset) {
4406 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414407 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574408 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014409 // An entry should only appear in the navigation API entries if it is for
4410 // the same origin as the document being committed. Check the committed
4411 // origin, or if that is not available (during restore), check against the
4412 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414413 url::Origin frame_entry_origin =
4414 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4415 frame_entry->url(),
4416 frame_entry->initiator_origin().value_or(url::Origin())));
4417 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574418 break;
4419 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4420 continue;
4421 blink::ExplodedPageState exploded_page_state;
4422 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4423 &exploded_page_state)) {
4424 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304425
4426 // If the document represented by this FNE hid its full url from appearing
4427 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014428 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304429 // document).
4430 std::u16string url;
4431 if (pending_document_sequence_number ==
4432 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574433 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304434 url = frame_state.url_string.value_or(std::u16string());
4435 }
4436
Domenic Denicolacd30f5f82022-03-16 21:48:014437 blink::mojom::NavigationApiHistoryEntryPtr entry =
4438 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574439 frame_state.navigation_api_key.value_or(std::u16string()),
4440 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094441 frame_state.item_sequence_number,
4442 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304443 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174444
Nate Chapin63db0d12022-01-20 22:03:304445 DCHECK(entry->url.empty() ||
4446 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574447 entries.push_back(std::move(entry));
4448 previous_item_sequence_number = frame_entry->item_sequence_number();
4449 }
4450 }
4451 // If |entries| was constructed by iterating backwards from
4452 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4453 // earliest-at-the-front. Reverse it.
4454 if (direction == Direction::kBack)
4455 std::reverse(entries.begin(), entries.end());
4456 return entries;
4457}
4458
Domenic Denicolacd30f5f82022-03-16 21:48:014459blink::mojom::NavigationApiHistoryEntryArraysPtr
4460NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554461 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574462 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404463 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444464 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404465 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574466
Nate Chapind1fe3612021-04-16 20:45:574467 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554468 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574469
Nate Chapine82339d02022-05-03 23:48:254470 // NOTE: |entry_index| is the index where this entry will commit if no
4471 // modifications are made between now and DidCommitNavigation. This is used to
4472 // walk |entries_| and determine which entries should be exposed by the
4473 // navigation API. It is important to calculate this correctly, because blink
4474 // will cancel a same-document history commit if it's not present in the
4475 // entries blink knows about.
4476 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574477 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304478 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254479 bool will_create_new_entry = false;
4480 if (GetPendingEntryIndex() != -1) {
4481 entry_index = GetPendingEntryIndex();
4482 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4483 pending_item_sequence_number = frame_entry->item_sequence_number();
4484 pending_document_sequence_number =
4485 frame_entry->document_sequence_number();
4486 }
4487 } else if (request &&
4488 !NavigationTypeUtils::IsReload(
4489 request->common_params().navigation_type) &&
4490 !NavigationTypeUtils::IsHistory(
4491 request->common_params().navigation_type) &&
4492 !request->common_params().should_replace_current_entry &&
4493 !request->common_params()
4494 .is_history_navigation_in_new_child_frame) {
4495 will_create_new_entry = true;
4496 entry_index = GetLastCommittedEntryIndex() + 1;
4497 // Don't set pending_item_sequence_number or
4498 // pending_document_sequence_number in this case - a new unique isn/dsn will
4499 // be calculated in the renderer later.
4500 } else if (GetLastCommittedEntryIndex() != -1) {
4501 entry_index = GetLastCommittedEntryIndex();
4502 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574503 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304504 pending_document_sequence_number =
4505 frame_entry->document_sequence_number();
4506 }
Nate Chapind1fe3612021-04-16 20:45:574507 }
4508
Domenic Denicolacd30f5f82022-03-16 21:48:014509 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254510 if (entry_index == -1) {
4511 // TODO(rakina): Exit early when there is no last committed entry.
4512 // Remove when InitialNavigationEntry ships.
4513 return entry_arrays;
4514 }
4515
Domenic Denicolacd30f5f82022-03-16 21:48:014516 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574517 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374518 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574519
4520 // Don't populate forward entries if they will be truncated by a new entry.
4521 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014522 entry_arrays->forward_entries =
4523 PopulateSingleNavigationApiHistoryEntryVector(
4524 Direction::kForward, entry_index, pending_origin, node,
4525 site_instance.get(), pending_item_sequence_number,
4526 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574527 }
Nate Chapin4e657a472022-02-06 03:38:374528 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574529}
4530
Nate Chapinfbfe5af2021-06-10 17:22:084531NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574532NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084533 FrameNavigationEntry* current_entry,
4534 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574535 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084536 if (!target_entry || !target_entry->committed_origin())
4537 return HistoryNavigationAction::kStopLooking;
4538 if (current_entry->site_instance() != target_entry->site_instance())
4539 return HistoryNavigationAction::kStopLooking;
4540 if (!current_entry->committed_origin()->IsSameOriginWith(
4541 *target_entry->committed_origin())) {
4542 return HistoryNavigationAction::kStopLooking;
4543 }
4544
4545 // NOTE: We don't actually care between kSameDocument and
4546 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574547 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084548 return HistoryNavigationAction::kDifferentDocument;
4549 return HistoryNavigationAction::kKeepLooking;
4550}
4551
Domenic Denicolacc094fb2022-03-16 23:40:574552void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204553 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144554 absl::optional<blink::scheduler::TaskAttributionId>
4555 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574556 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204557 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084558 FrameNavigationEntry* current_entry =
4559 GetLastCommittedEntry()->GetFrameEntry(node);
4560 if (!current_entry)
4561 return;
4562
Yoav Weiss8c573952022-11-17 17:35:134563 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4564 // when `navigation.traverseTo()` is called.
4565
Nate Chapinfbfe5af2021-06-10 17:22:084566 // We want to find the nearest matching entry that is contiguously
4567 // same-instance and same-origin. Check back first, then forward.
4568 // TODO(japhet): Link spec here once it exists.
4569 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574570 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084571 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4572 if (result == HistoryNavigationAction::kStopLooking)
4573 break;
4574 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144575 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084576 return;
4577 }
4578 }
4579 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574580 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084581 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4582 if (result == HistoryNavigationAction::kStopLooking)
4583 break;
4584 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144585 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084586 return;
4587 }
4588 }
Nate Chapinbf682fa32022-09-26 22:41:204589
4590 // If we fall through to here, a matching NavigationEntry couldn't be found.
4591 // Notify the renderer that the navigation was cancelled.
4592 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4593 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084594}
4595
Domenic Denicolacc094fb2022-03-16 23:40:574596bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304597 network::mojom::ReferrerPolicy referrer_policy) {
4598 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4599 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4600}
4601
shivanigithubf405bf0d2021-11-05 17:58:334602bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4603 const FrameTreeNode* frame_tree_node) const {
4604 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4605 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544606 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034607 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334608 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544609}
4610
Julie Jeongeun Kim0e242242022-11-30 10:45:094611void NavigationControllerImpl::DidChangeReferrerPolicy(
4612 FrameTreeNode* node,
4613 network::mojom::ReferrerPolicy referrer_policy) {
4614 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4615 if (!entry)
4616 return;
4617
4618 // The FrameNavigationEntry may want to change whether to protect its url
4619 // in the navigation API when the referrer policy changes.
4620 entry->set_protect_url_in_navigation_api(
4621 ShouldProtectUrlInNavigationApi(referrer_policy));
4622}
4623
[email protected]8ff00d72012-10-23 19:12:214624} // namespace content