blob: c03bf4db481de83679dc8be1675d523355c73ada [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]eabfe1912014-05-12 10:07:2841#include "base/command_line.h"
Ayu Ishii2f825852022-03-08 19:47:3842#include "base/containers/adapters.h"
Lei Zhang302bc3fa2025-06-04 20:10:3443#include "base/debug/crash_logging.h"
Rakina Zata Amni627360d2022-02-24 00:53:4044#include "base/debug/dump_without_crashing.h"
Avi Drissmanadac21992023-01-11 23:46:3945#include "base/functional/bind.h"
initial.commit09911bf2008-07-26 23:55:2946#include "base/logging.h"
asvitkine30330812016-08-30 04:01:0847#include "base/metrics/histogram_macros.h"
Kevin McNee37a109792025-04-14 21:16:3848#include "base/not_fatal_until.h"
Charlie Reis23c26da2022-01-29 00:57:4749#include "base/numerics/safe_conversions.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3950#include "base/strings/escape.h"
[email protected]348fbaac2013-06-11 06:31:5151#include "base/strings/string_util.h"
Daniel Cheng17390fd2025-06-07 06:38:2652#include "base/strings/string_view_util.h"
[email protected]74ebfb12013-06-07 20:48:0053#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3754#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0055#include "base/trace_event/optional_trace_event.h"
ssid3e765612015-01-28 04:03:4256#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0857#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5958#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2859#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1860#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3961#include "content/browser/blob_storage/chrome_blob_storage_context.h"
William Liu055a3542023-04-02 17:21:1962#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3163#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4164#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0465#include "content/browser/dom_storage/session_storage_namespace_impl.h"
Nate Chapinc06cf80a2023-11-18 01:12:2566#include "content/browser/preloading/prerender/prerender_host.h"
Sharon Yang242ef822023-05-15 21:07:3267#include "content/browser/process_lock.h"
Mingyu Lei68f34412023-08-21 07:31:3768#include "content/browser/renderer_host/back_forward_cache_impl.h"
danakjc492bf82020-09-09 20:02:4469#include "content/browser/renderer_host/debug_urls.h"
70#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0071#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3372#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4473#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5774#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4475#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1976#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
77#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
Khushal Sagar94ea2dc2024-08-06 17:15:2678#include "content/browser/renderer_host/navigation_transitions/navigation_transition_config.h"
danakjc492bf82020-09-09 20:02:4479#include "content/browser/renderer_host/navigator.h"
Takashi Toyoshima4dad2c12023-11-13 10:04:4680#include "content/browser/renderer_host/page_delegate.h"
danakjc492bf82020-09-09 20:02:4481#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0082#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0783#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3284#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3385#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4286#include "content/common/content_constants_internal.h"
Rakina Zata Amni84a859df2024-06-07 15:56:3287#include "content/common/content_navigation_policy.h"
Nate Chapind1fe3612021-04-16 20:45:5788#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5189#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1190#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1991#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1192#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4693#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0094#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4795#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5896#include "content/public/browser/render_widget_host.h"
97#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1098#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3499#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:19100#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:38101#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:10102#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47103#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43104#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59105#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36106#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57107#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18108#include "services/metrics/public/cpp/ukm_builders.h"
109#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17110#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37111#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44112#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58113#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39114#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30115#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21116#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06117#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43118#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50119#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31120#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51121#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46122#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26123#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29124
[email protected]8ff00d72012-10-23 19:12:21125namespace content {
[email protected]e9ba4472008-09-14 15:42:43126namespace {
127
Charlie Reis655c8f02025-05-15 01:16:17128// Feature to skip a redundant NavigationRequest creation for bfcache
129// activations, per https://crbug.com/417251428.
Charlie Reis3696ab62025-05-28 07:02:30130// TODO(crbug.com/420275259): Diagnose crashes and enable by default.
Charlie Reis655c8f02025-05-15 01:16:17131BASE_FEATURE(kSkipExtraBfcacheNavigationRequest,
132 "SkipExtraBfcacheNavigationRequest",
Charlie Reis3696ab62025-05-28 07:02:30133 base::FEATURE_DISABLED_BY_DEFAULT);
Charlie Reis655c8f02025-05-15 01:16:17134
[email protected]e9ba4472008-09-14 15:42:43135// Invoked when entries have been pruned, or removed. For example, if the
136// current entries are [google, digg, yahoo], with the current entry google,
137// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47138void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50139 int index,
[email protected]c12bf1a12008-09-17 16:28:49140 int count) {
[email protected]8ff00d72012-10-23 19:12:21141 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50142 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49143 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14144 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43145}
146
[email protected]e9ba4472008-09-14 15:42:43147// Configure all the NavigationEntries in entries for restore. This resets
148// the transition type to reload and makes sure the content state isn't empty.
149void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57150 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48151 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47152 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43153 // Use a transition type of reload so that we don't incorrectly increase
154 // the typed count.
Lei Zhang96031532019-10-10 19:05:47155 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
156 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43157 }
158}
159
[email protected]bf70edce2012-06-20 22:32:22160// Determines whether or not we should be carrying over a user agent override
161// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57162bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22163 return last_entry && last_entry->GetIsOverridingUserAgent();
164}
165
Camille Lamy5193caa2018-10-12 11:59:42166// Determines whether to override user agent for a navigation.
167bool ShouldOverrideUserAgent(
168 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57169 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42170 switch (override_user_agent) {
171 case NavigationController::UA_OVERRIDE_INHERIT:
172 return ShouldKeepOverride(last_committed_entry);
173 case NavigationController::UA_OVERRIDE_TRUE:
174 return true;
175 case NavigationController::UA_OVERRIDE_FALSE:
176 return false;
Camille Lamy5193caa2018-10-12 11:59:42177 }
Peter Boströmfc7ddc182024-10-31 19:37:21178 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42179}
180
Rakina Zata Amni312822d72021-06-04 16:13:37181// Returns true if this navigation should be treated as a reload. For e.g.
Liang Zhao0351d762024-11-13 00:10:07182// clicking on a link which results in a navigation to the last committed URL
183// (but wasn't converted to do a replacement navigation in the renderer), etc.
184// This intentionally excludes navigating to the last committed URL via the
185// address bar, so that the current scroll position is not restored.
Fergal Daly766177d2020-07-07 07:54:04186// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
187// |base_url_for_data_url|, |transition_type| correspond to the new navigation
188// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
189// navigation that committed.
190bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
191 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57192 const GURL& virtual_url,
193 const GURL& base_url_for_data_url,
194 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57195 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37196 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57197 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37198 // Navigations intended to do a replacement shouldn't be converted to do a
199 // reload.
200 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28201 return false;
clamy0a656e42018-02-06 18:18:28202 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45203 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55204 return false;
205
arthursonzogni7a8243682017-12-14 16:41:42206 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28207 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42208 return false;
209
Liang Zhao0351d762024-11-13 00:10:07210 // Same URL navigations from the address bar should only be treated as reloads
211 // if PAGE_TRANSITION_RELOAD is set (not for PAGE_TRANSITION_TYPED or
212 // PAGE_TRANSITION_LINK). In non-address-bar cases, PAGE_TRANSITION_TYPED
213 // and PAGE_TRANSITION_LINK can be treated as reloads.
clamy0a656e42018-02-06 18:18:28214 bool transition_type_can_be_converted = false;
Liang Zhao0351d762024-11-13 00:10:07215 if (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
216 if (ui::PageTransitionCoreTypeIs(transition_type,
217 ui::PAGE_TRANSITION_RELOAD)) {
218 transition_type_can_be_converted = true;
219 }
220 } else {
221 if (ui::PageTransitionCoreTypeIs(transition_type,
222 ui::PAGE_TRANSITION_TYPED) ||
223 ui::PageTransitionCoreTypeIs(transition_type,
224 ui::PAGE_TRANSITION_LINK)) {
225 transition_type_can_be_converted = true;
226 }
ananta3bdd8ae2016-12-22 17:11:55227 }
clamy0a656e42018-02-06 18:18:28228 if (!transition_type_can_be_converted)
229 return false;
230
231 // This check is required for cases like view-source:, etc. Here the URL of
232 // the navigation entry would contain the url of the page, while the virtual
233 // URL contains the full URL including the view-source prefix.
234 if (virtual_url != last_committed_entry->GetVirtualURL())
235 return false;
236
Fergal Daly766177d2020-07-07 07:54:04237 // Check that the URLs match.
238 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
239 // If there's no frame entry then by definition the URLs don't match.
240 if (!frame_entry)
241 return false;
242
243 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28244 return false;
245
246 // This check is required for Android WebView loadDataWithBaseURL. Apps
247 // can pass in anything in the base URL and we need to ensure that these
248 // match before classifying it as a reload.
249 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
250 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
251 return false;
ananta3bdd8ae2016-12-22 17:11:55252 }
253
clamy0a656e42018-02-06 18:18:28254 // Skip entries with SSL errors.
255 if (last_committed_entry->ssl_error())
256 return false;
257
258 // Don't convert to a reload when the last navigation was a POST or the new
259 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04260 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28261 return false;
262
263 return true;
ananta3bdd8ae2016-12-22 17:11:55264}
265
Arthur Sonzognic686e8f2024-01-11 08:36:37266std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12267 const mojom::DidCommitProvisionalLoadParams& params,
268 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32269 // Error pages commit in an opaque origin, yet have the real URL that resulted
270 // in an error as the |params.url|. Since successful reload of an error page
271 // should commit in the correct origin, setting the opaque origin on the
272 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17273 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37274 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32275
Arthur Sonzognic686e8f2024-01-11 08:36:37276 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32277}
278
Alex Moshchuk99242832023-05-22 17:21:44279bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42280 const GURL& virtual_url,
281 const GURL& dest_url) {
282 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44283 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
284 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42285 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
286 << virtual_url.possibly_invalid_spec();
287 return false;
288 }
289
290 // Don't attempt to navigate to non-empty invalid URLs.
291 if (!dest_url.is_valid() && !dest_url.is_empty()) {
292 LOG(WARNING) << "Refusing to load invalid URL: "
293 << dest_url.possibly_invalid_spec();
294 return false;
295 }
296
297 // The renderer will reject IPC messages with URLs longer than
298 // this limit, so don't attempt to navigate with a longer URL.
299 if (dest_url.spec().size() > url::kMaxURLChars) {
300 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
301 << " characters.";
302 return false;
303 }
304
Aaron Colwell33109c592020-04-21 21:31:19305 // Reject renderer debug URLs because they should have been handled before
306 // we get to this point. This check handles renderer debug URLs
307 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
308 // provides defense-in-depth if a renderer debug URL manages to get here via
309 // some other path. We want to reject the navigation here so it doesn't
310 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30311 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19312 LOG(WARNING) << "Refusing to load renderer debug URL: "
313 << dest_url.possibly_invalid_spec();
314 return false;
315 }
316
Alex Moshchuk99242832023-05-22 17:21:44317 // Guests only support navigations to known-safe schemes. This check already
318 // exists in the extensions layer, where it also dispatches proper events to
319 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
320 // for defense-in-depth to ensure that no other places in the codebase
321 // accidentally navigate guests to schemes such as WebUI, which is not
322 // supported. See https://crbug.com/1444221.
323 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
324 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
325 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
326 !dest_url.SchemeIs(url::kAboutScheme)) {
327 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
328 << dest_url.possibly_invalid_spec();
329 return false;
330 }
331 }
332
Camille Lamy5193caa2018-10-12 11:59:42333 return true;
334}
335
Mikel Astizba9cf2fd2017-12-17 10:38:10336// See replaced_navigation_entry_data.h for details: this information is meant
337// to ensure |*output_entry| keeps track of its original URL (landing page in
338// case of server redirects) as it gets replaced (e.g. history.replaceState()),
339// without overwriting it later, for main frames.
340void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57341 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10342 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17343 if (output_entry->GetReplacedEntryData().has_value() ||
344 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10345 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17346 }
Mikel Astizba9cf2fd2017-12-17 10:38:10347
348 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57349 data.first_committed_url = replaced_entry->GetURL();
350 data.first_timestamp = replaced_entry->GetTimestamp();
351 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29352 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10353}
354
Minggang Wangb9f3fa92021-07-01 15:30:31355blink::mojom::NavigationType GetNavigationType(
356 const GURL& old_url,
357 const GURL& new_url,
358 ReloadType reload_type,
359 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52360 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31361 bool has_pending_cross_document_commit,
362 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49363 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13364 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49365 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23366 // Reload navigations
367 switch (reload_type) {
368 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31369 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23370 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31371 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23372 case ReloadType::NONE:
373 break; // Fall through to rest of function.
374 }
375
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08376 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31377 return entry->GetHasPostData()
378 ? blink::mojom::NavigationType::RESTORE_WITH_POST
379 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23380 }
381
danakjb952ef12021-01-14 19:58:49382 const bool can_be_same_document =
383 // A pending cross-document commit means this navigation will not occur in
384 // the current document, as that document would end up being replaced in
385 // the meantime.
386 !has_pending_cross_document_commit &&
387 // If the current document is an error page, we should always treat it as
388 // a different-document navigation so that we'll attempt to load the
389 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49390 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13391 // If the navigation is an embedder-initiated navigation of a fenced
392 // frame root (i.e. enters a fenced frame tree from outside),
393 // same-document navigations should be disabled because we don't want to
394 // allow information to be joined across multiple embedder-initiated
395 // fenced frame navigations (which may contain separate cross-site data).
396 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49397 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
398 // same-document navigations should be disabled because we want to force
399 // the creation of a new browsing context group.
400 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12401
clamyea99ea12018-05-28 13:54:23402 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52403 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12404 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31405 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
406 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23407 }
408 DCHECK(!is_same_document_history_load);
409
410 // A same-document fragment-navigation happens when the only part of the url
411 // that is modified is after the '#' character.
412 //
413 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12414 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23415 //
416 // Note: this check is only valid for navigations that are not history
417 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
418 // history navigation from 'A#foo' to 'A#bar' is not a same-document
419 // navigation, but a different-document one. This is why history navigation
420 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47421 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52422 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12423
424 // The one case where we do the wrong thing here and incorrectly choose
425 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
426 // the renderer is a frameset. All frameset navigations should be
427 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
428 // navigation would do the right thing, as it would send it to the browser and
429 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
430 // into this method). But since we can't tell that case here for browser-
431 // initiated navigations, we have to get the renderer involved. In that case
432 // the navigation would be restarted due to the renderer spending a reply of
433 // mojom::CommitResult::RestartCrossDocument.
434
435 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31436 ? blink::mojom::NavigationType::SAME_DOCUMENT
437 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23438}
439
Camille Lamy5193caa2018-10-12 11:59:42440// Adjusts the original input URL if needed, to get the URL to actually load and
441// the virtual URL, which may differ.
442void RewriteUrlForNavigation(const GURL& original_url,
443 BrowserContext* browser_context,
444 GURL* url_to_load,
445 GURL* virtual_url,
446 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42447 // Allow the browser URL handler to rewrite the URL. This will, for example,
448 // remove "view-source:" from the beginning of the URL to get the URL that
449 // will actually be loaded. This real URL won't be shown to the user, just
450 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31451 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42452 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
453 url_to_load, browser_context, reverse_on_redirect);
454}
455
456#if DCHECK_IS_ON()
457// Helper sanity check function used in debug mode.
458void ValidateRequestMatchesEntry(NavigationRequest* request,
459 NavigationEntryImpl* entry) {
460 if (request->frame_tree_node()->IsMainFrame()) {
461 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
462 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31463 ui::PageTransitionFromInt(request->common_params().transition),
464 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42465 }
Nasko Oskovc36327d2019-01-03 23:23:04466 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42467 entry->should_clear_history_list());
468 DCHECK_EQ(request->common_params().has_user_gesture,
469 entry->has_user_gesture());
470 DCHECK_EQ(request->common_params().base_url_for_data_url,
471 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04472 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42473 entry->GetCanLoadLocalResources());
474 DCHECK_EQ(request->common_params().started_from_context_menu,
475 entry->has_started_from_context_menu());
476
477 FrameNavigationEntry* frame_entry =
478 entry->GetFrameEntry(request->frame_tree_node());
479 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52480 // TODO(https://crbug.com/40467594): This case should be unreachable once
481 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42482 return;
483 }
484
Camille Lamy5193caa2018-10-12 11:59:42485 DCHECK_EQ(request->common_params().method, frame_entry->method());
486
Nasko Oskovc36327d2019-01-03 23:23:04487 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42488 if (redirect_size == frame_entry->redirect_chain().size()) {
489 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04490 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42491 frame_entry->redirect_chain()[i]);
492 }
493 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21494 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42495 }
496}
497#endif // DCHECK_IS_ON()
498
Dave Tapuska8bfd84c2019-03-26 20:47:16499// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20500// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16501bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20502 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16503 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20504 DCHECK(sandboxed_initiator_rfh);
505 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
506 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16507 for (auto& item : navigations) {
508 bool within_subtree = false;
509 // Check whether this NavigationRequest affects a frame within the
510 // sandboxed frame's subtree by walking up the tree looking for the
511 // sandboxed frame.
512 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03513 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20514 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16515 within_subtree = true;
516 break;
517 }
518 }
519 if (!within_subtree)
520 return false;
521 }
522 return true;
523}
524
William Liu122754942024-01-18 22:34:39525// Used for "Navigation.SessionHistoryCount" histogram.
526enum class HistoryNavTypeForHistogram {
527 // A same-doc or cross-doc navigation of the main frame. We can only have one
528 // main frame request per `NavigationController::GoToIndex()`.
529 kMainFrame = 0,
530 // `NavigationController::GoToIndex()` creates one main frame request and
531 // one or more subframe requests.
532 kMainFrameAndSubframe,
533 // `NavigationController::GoToIndex()` creates one or more subframe requests.
534 kSubframe,
535 // Used for histogram boundary.
536 kCount
537};
538
539void CountRequests(
540 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
541 int& mutable_main_frame_cnt,
542 int& mutable_subframe_cnt) {
543 for (const auto& req : requests) {
544 if (req->IsInPrimaryMainFrame()) {
545 // We can only have one main frame navigation at a time.
546 CHECK_EQ(mutable_main_frame_cnt, 0);
547 ++mutable_main_frame_cnt;
548 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
549 ++mutable_subframe_cnt;
550 }
551 }
552}
553
554// Record the number of different types of navigations as histograms. See
555// `HistoryNavTypeForHistogram` for the types.
556void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
557 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
558 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
559 // We must have one request.
560 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
561
562 int main_frame_cnt = 0;
563 int subframe_cnt = 0;
564 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
565 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
566
567 std::optional<HistoryNavTypeForHistogram> history_nav_type;
568 if (main_frame_cnt > 0) {
569 if (subframe_cnt == 0) {
570 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
571 } else {
572 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
573 }
574 } else if (subframe_cnt > 0) {
575 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
576 }
577 if (history_nav_type.has_value()) {
578 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
579 history_nav_type.value(),
580 HistoryNavTypeForHistogram::kCount);
581 }
582}
583
[email protected]e9ba4472008-09-14 15:42:43584} // namespace
585
arthursonzogni66f711c2019-10-08 14:40:36586// NavigationControllerImpl::PendingEntryRef------------------------------------
587
588NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
589 base::WeakPtr<NavigationControllerImpl> controller)
590 : controller_(controller) {}
591
592NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
593 if (!controller_) // Can be null with interstitials.
594 return;
595
596 controller_->PendingEntryRefDeleted(this);
597}
598
Charlie Reisd3e4fef2025-05-20 02:04:17599// NavigationControllerImpl::ScopedPendingEntryReentrancyGuard------------------
600
601NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
602 ScopedPendingEntryReentrancyGuard(
603 base::SafeRef<NavigationControllerImpl> controller)
604 : controller_(controller) {
605 // Navigations that involve pending entries do not support re-entrancy.
606 // Encountering this CHECK failure means the caller is attempting to start
607 // another navigation while a navigation to an existing pending entry is on
608 // the stack. In most cases, the new navigation should be done from a posted
609 // task instead. See http://crbug.com/40353566 for context.
610 CHECK(!controller->in_navigate_to_pending_entry_);
611
612 controller->in_navigate_to_pending_entry_ = true;
613 controller->CheckPotentialNavigationReentrancy();
614
615 // It must not be possible to delete the pending NavigationEntry while
616 // navigating to it. Grab a reference to delay potential deletion until
617 // this scoped object is deleted at the end of the relevant function call.
618 pending_entry_ref_ = controller->ReferencePendingEntry();
619}
620
621NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
622 ~ScopedPendingEntryReentrancyGuard() {
623 controller_->in_navigate_to_pending_entry_ = false;
624}
625
[email protected]d202a7c2012-01-04 07:53:47626// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29627
[email protected]23a918b2014-07-15 09:51:36628const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23629
[email protected]765b35502008-08-21 00:51:20630// static
[email protected]d202a7c2012-01-04 07:53:47631size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23632 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20633
[email protected]e6fec472013-05-14 05:29:02634// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20635// when testing.
636static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29637
[email protected]71fde352011-12-29 03:29:56638// static
dcheng9bfa5162016-04-09 01:00:57639std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
640 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10641 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37642 std::optional<url::Origin> initiator_origin,
643 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10644 ui::PageTransition transition,
645 bool is_renderer_initiated,
646 const std::string& extra_headers,
647 BrowserContext* browser_context,
648 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
649 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21650 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37651 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32652 is_renderer_initiated, extra_headers, browser_context,
653 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10654}
655
656// static
657std::unique_ptr<NavigationEntryImpl>
658NavigationControllerImpl::CreateNavigationEntry(
659 const GURL& url,
660 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37661 std::optional<url::Origin> initiator_origin,
662 std::optional<GURL> initiator_base_url,
663 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57664 ui::PageTransition transition,
665 bool is_renderer_initiated,
666 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09667 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17668 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
669 bool rewrite_virtual_urls) {
670 GURL url_to_load = url;
671 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56672 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17673 if (rewrite_virtual_urls) {
674 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
675 &reverse_on_redirect);
676 }
Lukasz Anforowicz641234d52019-11-07 21:07:10677 // Let the NTP override the navigation params and pretend that this is a
678 // browser-initiated, bookmark-like navigation.
679 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32680 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21681 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10682
Patrick Monettef507e982019-06-19 20:18:06683 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28684 nullptr, // The site instance for tabs is sent on navigation
685 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21686 url_to_load, referrer, initiator_origin, initiator_base_url,
687 std::u16string(), transition, is_renderer_initiated,
688 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17689 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42690 entry->SetVirtualURL(virtual_url);
691 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56692 entry->set_update_virtual_url_with_url(reverse_on_redirect);
693 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06694 return entry;
[email protected]71fde352011-12-29 03:29:56695}
696
[email protected]cdcb1dee2012-01-04 00:46:20697// static
698void NavigationController::DisablePromptOnRepost() {
699 g_check_for_repost = false;
700}
701
[email protected]c5b88d82012-10-06 17:03:33702base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
703 base::Time t) {
704 // If |t| is between the water marks, we're in a run of duplicates
705 // or just getting out of it, so increase the high-water mark to get
706 // a time that probably hasn't been used before and return it.
707 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35708 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33709 return high_water_mark_;
710 }
711
712 // Otherwise, we're clear of the last duplicate run, so reset the
713 // water marks.
714 low_water_mark_ = high_water_mark_ = t;
715 return t;
716}
717
ckitagawa0faa5e42020-06-17 17:30:54718NavigationControllerImpl::ScopedShowRepostDialogForTesting::
719 ScopedShowRepostDialogForTesting()
720 : was_disallowed_(g_check_for_repost) {
721 g_check_for_repost = true;
722}
723
724NavigationControllerImpl::ScopedShowRepostDialogForTesting::
725 ~ScopedShowRepostDialogForTesting() {
726 g_check_for_repost = was_disallowed_;
727}
728
Nate Chapin9eb16be72022-09-23 22:54:31729NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
730 base::SafeRef<NavigationControllerImpl> controller)
731 : controller_(controller) {
732 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
733 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
734 frame_tree_node_id_to_keys_.insert(
735 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
736 if (auto* frame_entry = frame_tree_node->current_frame_host()
737 ->last_committed_frame_entry()) {
738 frame_tree_node_id_to_doc_seq_nos_.insert(
739 {frame_tree_node->frame_tree_node_id(),
740 frame_entry->document_sequence_number()});
741 }
742 }
743 PopulateKeySet(Direction::kBack);
744 PopulateKeySet(Direction::kForward);
745}
746
747void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
748 Direction direction) {
749 // Keep track of which FrameTreeNodes may still have relevant API keys in
750 // additional FrameNavigationEntries.
751 std::set<FrameTreeNode*> nodes_to_process;
752 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
753 nodes_to_process.insert(node);
754 }
755
756 const int offset = direction == Direction::kForward ? 1 : -1;
757 const int start = direction == Direction::kForward
758 ? controller_->GetLastCommittedEntryIndex()
759 : controller_->GetLastCommittedEntryIndex() - 1;
760 for (int i = start;
761 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
762 i += offset) {
763 std::set<FrameTreeNode*> nodes_to_continue_processing;
764
765 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
766 entry->ForEachFrameEntry([this, &nodes_to_process,
767 &nodes_to_continue_processing,
768 &entry](FrameNavigationEntry* frame_entry) {
769 // Find the |node| that matches |frame_entry|, if any.
770 FrameTreeNode* node = nullptr;
771 if (frame_entry == entry->root_node()->frame_entry) {
772 node = controller_->frame_tree().root();
773 } else {
774 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
775 if (it == names_to_nodes_.end())
776 return;
777 node = it->second;
778 }
779
780 // Skip this node if a previous step determine there are no longer
781 // relevant navigation API keys in this direction.
782 if (nodes_to_process.find(node) == nodes_to_process.end())
783 return;
784
785 // Stop processing |node| if we reach a point where it's cross-origin.
786 // See also PopulateSingleNavigationApiHistoryEntryVector().
787 url::Origin frame_entry_origin =
788 frame_entry->committed_origin().value_or(url::Origin::Resolve(
789 frame_entry->url(),
790 frame_entry->initiator_origin().value_or(url::Origin())));
791 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
792 return;
793
794 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
795 frame_entry->navigation_api_key());
796 // Mark |node| as needing more processing for the next entry.
797 nodes_to_continue_processing.insert(node);
798
799 // Check whether |node| went cross-document. If so, its children are
800 // no longer the same conceptual iframe as the current one, and
801 // should no longer be processed. This check is intentionally done
802 // after processing the current |node|, which may still have relevant
803 // discarded API keys.
804 if (frame_entry->document_sequence_number() !=
805 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50806 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31807 nodes_to_process.erase(descendant);
808 }
809 });
810
811 nodes_to_process.swap(nodes_to_continue_processing);
812 }
813}
814
815NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
816 std::set<std::string> all_keys;
817 // Find all remaining navigation API keys after some entries have been
818 // removed.
819 for (auto& entry : controller_->entries_) {
820 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
821 all_keys.insert(frame_entry->navigation_api_key());
822 });
823 }
824
825 // Notify each frame in the renderer of any disposed navigation API keys.
826 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
827 std::vector<std::string> disposed_keys;
828 for (const auto& key : id_to_keys.second) {
829 if (all_keys.find(key) == all_keys.end())
830 disposed_keys.push_back(key);
831 }
832 if (disposed_keys.empty())
833 continue;
834
835 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
836 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
837 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
838 }
839}
840
[email protected]d202a7c2012-01-04 07:53:47841NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00842 BrowserContext* browser_context,
843 FrameTree& frame_tree,
844 NavigationControllerDelegate* delegate)
845 : frame_tree_(frame_tree),
846 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57847 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22848 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37849 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
850 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37851 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29852}
853
[email protected]d202a7c2012-01-04 07:53:47854NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00855 // The NavigationControllerImpl might be called inside its delegate
856 // destructor. Calling it is not valid anymore.
857 delegate_ = nullptr;
858 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29859}
860
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57861BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55862 return browser_context_;
863}
864
[email protected]d202a7c2012-01-04 07:53:47865void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30866 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36867 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57868 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47869 // Note that it's possible for `entries_` to contain multiple entries at this
870 // point, as Restore() might be called on a NavigationController that is
871 // already used (e.g. due to WebView's restoreState() API), not only for fresh
872 // NavigationControllers. These entries are not cleared to preserve legacy
873 // behavior and also because `pending_entry_` might point to one of the
874 // pre-existing entries. An exception for this is when `entries_` contains
875 // only the initial NavigationEntry, which must be removed.
876
877 // Do not proceed if selected_navigation will be out of bounds for the updated
878 // entries_ list, since it will be assigned to last_committed_entry_index_ and
879 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58880 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47881 // is empty, since there should be no work to do (rather than marking the
882 // existing entries as needing reload). Also consider returning early if the
883 // selected index is -1, which represents a no-committed-entry state.
884 if (selected_navigation < -1 ||
885 selected_navigation >=
886 base::checked_cast<int>(entries->size() + entries_.size())) {
887 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24888 }
Charlie Reis23c26da2022-01-29 00:57:47889
Rakina Zata Amni46087a12022-11-11 08:28:38890 // There will always be at least one entry (new NavigationControllers will
891 // have the initial NavigationEntry).
892 if (selected_navigation == -1)
893 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47894
Rakina Zata Amni46087a12022-11-11 08:28:38895 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
896 // If we are on the initial NavigationEntry, it must be the only entry in
897 // the list. Since it's impossible to do a history navigation to the
898 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
899 // `pending_entry` might be set for a new non-history navigation).
900 // Note that we should not clear `entries_` if `entries` is empty (when
901 // InitialNavigationEntry mode is enabled), since that would leave us
902 // without any NavigationEntry.
903 CHECK_EQ(1, GetEntryCount());
904 CHECK_EQ(-1, pending_entry_index_);
905 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47906 }
[email protected]ce3fa3c2009-04-20 19:55:57907
[email protected]ce3fa3c2009-04-20 19:55:57908 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44909 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03910 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47911 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43912 if (entry->GetURL().is_empty()) {
913 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01914 // persisting the initial NavigationEntry [which is no longer possible but
915 // some old persisted sessions might still contain it] or when the
916 // serializer failed to write the URL because it's too long). Trying to
917 // restore and navigate to an entry with an empty URL will result in
918 // crashes, so change the URL to about:blank. See also
919 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43920 entry->SetURL(GURL(url::kAboutBlankURL));
921 }
dcheng36b6aec92015-12-26 06:16:36922 entries_.push_back(
923 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47924 }
avif16f85a72015-11-13 18:25:03925
926 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
927 // cleared out safely.
928 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57929
930 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36931 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57932}
933
toyoshim6142d96f2016-12-19 09:07:25934void NavigationControllerImpl::Reload(ReloadType reload_type,
935 bool check_for_repost) {
Charlie Reisf4d51f402025-05-23 18:00:49936 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:03937 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
938 (int)reload_type);
939 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
940 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28941 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28942 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32943 int current_index = -1;
944
Carlos IL42b416592019-10-07 23:10:36945 if (entry_replaced_by_post_commit_error_) {
946 // If there is an entry that was replaced by a currently active post-commit
947 // error navigation, this can't be the initial navigation.
948 DCHECK(!IsInitialNavigation());
949 // If the current entry is a post commit error, we reload the entry it
950 // replaced instead. We leave the error entry in place until a commit
951 // replaces it, but the pending entry points to the original entry in the
952 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
953 // case that pending_entry_ != entries_[pending_entry_index_].
954 entry = entry_replaced_by_post_commit_error_.get();
955 current_index = GetCurrentEntryIndex();
956 } else if (IsInitialNavigation() && pending_entry_) {
957 // If we are reloading the initial navigation, just use the current
958 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32959 entry = pending_entry_;
960 // The pending entry might be in entries_ (e.g., after a Clone), so we
961 // should also update the current_index.
962 current_index = pending_entry_index_;
963 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00964 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32965 current_index = GetCurrentEntryIndex();
966 if (current_index != -1) {
creis3da03872015-02-20 21:12:32967 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32968 }
[email protected]979a4bc2013-04-24 01:27:15969 }
[email protected]241db352013-04-22 18:04:05970
[email protected]59167c22013-06-03 18:07:32971 // If we are no where, then we can't reload. TODO(darin): We should add a
972 // CanReload method.
973 if (!entry)
974 return;
975
Rakina Zata Amnif297a802022-01-18 03:53:43976 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
977 // We should never navigate to an existing initial NavigationEntry that is
978 // the initial NavigationEntry for the initial empty document that hasn't
979 // been overridden by the synchronous about:blank commit, to preserve
980 // legacy behavior where trying to reload when the main frame is on the
981 // initial empty document won't result in a navigation. See also
982 // https://crbug.com/1277414.
983 return;
984 }
985
Aran Gilman37d11632019-10-08 23:07:15986 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30987 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07988 // they really want to do this. If they do, the dialog will call us back
989 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57990 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02991
[email protected]106a0812010-03-18 00:15:12992 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57993 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47994 return;
initial.commit09911bf2008-07-26 23:55:29995 }
Lei Zhang96031532019-10-10 19:05:47996
Wang Huia25efabc2022-09-24 17:27:22997 // Set ReloadType for |entry|.
998 entry->set_reload_type(reload_type);
999
Lei Zhang96031532019-10-10 19:05:471000 if (!IsInitialNavigation())
1001 DiscardNonCommittedEntries();
1002
1003 pending_entry_ = entry;
1004 pending_entry_index_ = current_index;
1005 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
1006
Nate Chapin45f620582021-09-30 17:45:431007 // location.reload() goes through BeginNavigation, so all reloads triggered
1008 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:131009 NavigateToExistingPendingEntry(
1010 reload_type,
1011 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371012 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491013 /*navigation_api_key=*/nullptr, actual_navigation_start);
initial.commit09911bf2008-07-26 23:55:291014}
1015
[email protected]d202a7c2012-01-04 07:53:471016void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:481017 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121018}
1019
[email protected]d202a7c2012-01-04 07:53:471020void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:491021 // If the pending reload type has been cleared by another navigation
1022 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:481023 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:491024 return;
[email protected]106a0812010-03-18 00:15:121025 }
Wang Hui96ab1012022-10-11 02:05:491026 Reload(pending_reload_, false);
1027 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121028}
1029
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571030bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:091031 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:111032}
1033
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571034bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:381035 // Check that we're on the initial NavigationEntry and that this is not a
1036 // cloned tab.
1037 return IsInitialNavigation() && GetEntryCount() == 1 &&
1038 GetLastCommittedEntry()->IsInitialEntry() &&
1039 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401040}
1041
Aran Gilman37d11632019-10-08 23:07:151042NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1043 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581044 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031045 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581046}
1047
Adithya Srinivasan9b0c99c2021-08-10 15:19:451048NavigationEntryImpl*
1049NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1050 int nav_entry_id) const {
1051 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1052 if (entry)
1053 return entry;
1054 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521055 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451056 : nullptr;
1057}
1058
W. James MacLeanc07dc41b2022-07-25 18:52:161059void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571060 const url::Origin& origin) {
1061 for (int i = 0; i < GetEntryCount(); i++) {
1062 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161063 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571064 }
1065 if (entry_replaced_by_post_commit_error_) {
1066 // It's possible we could come back to this entry if the error
1067 // page/interstitial goes away.
1068 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161069 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571070 }
W. James MacLean1c40862c2020-04-27 21:05:571071}
1072
avi25764702015-06-23 15:43:371073void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571074 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001075 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371076 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271077 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201078}
1079
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571080NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471081 if (pending_entry_)
1082 return pending_entry_;
1083 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201084}
1085
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571086NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321087 // The pending entry is safe to return for new (non-history), browser-
1088 // initiated navigations. Most renderer-initiated navigations should not
1089 // show the pending entry, to prevent URL spoof attacks.
1090 //
1091 // We make an exception for renderer-initiated navigations in new tabs, as
1092 // long as no other page has tried to access the initial empty document in
1093 // the new tab. If another page modifies this blank page, a URL spoof is
1094 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321095 bool safe_to_show_pending =
1096 pending_entry_ &&
1097 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091098 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321099 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461100 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321101
1102 // Also allow showing the pending entry for history navigations in a new tab,
1103 // such as Ctrl+Back. In this case, no existing page is visible and no one
1104 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151105 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1106 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321107 safe_to_show_pending = true;
1108
1109 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191110 return pending_entry_;
1111 return GetLastCommittedEntry();
1112}
1113
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571114int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201115 if (pending_entry_index_ != -1)
1116 return pending_entry_index_;
1117 return last_committed_entry_index_;
1118}
1119
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571120NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381121 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031122 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201123}
1124
Elad Alon32044f532025-03-04 22:16:031125const NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry()
1126 const {
1127 CHECK_NE(last_committed_entry_index_, -1);
1128 return entries_[last_committed_entry_index_].get();
1129}
1130
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571131bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351132 const std::string& mime_type = frame_tree_->root()
1133 ->current_frame_host()
1134 ->GetPage()
1135 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531136 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1137 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271138 NavigationEntry* visible_entry = GetVisibleEntry();
1139 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391140 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161141}
1142
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571143int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271144 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451145 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271146 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551147 return last_committed_entry_index_;
1148}
1149
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571150int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451151 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291152 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551153 return static_cast<int>(entries_.size());
1154}
1155
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571156NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371157 if (index < 0 || index >= GetEntryCount())
1158 return nullptr;
1159
avif16f85a72015-11-13 18:25:031160 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251161}
1162
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571163NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471164 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201165}
1166
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571167int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461168 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031169}
1170
Arthur Sonzognic686e8f2024-01-11 08:36:371171std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031172 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591173 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1174 return index;
1175 }
Shivani Sharma298d12852019-01-22 20:04:031176 }
Arthur Sonzognic686e8f2024-01-11 08:36:371177 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591178}
1179
1180bool NavigationControllerImpl::CanGoBack() {
1181 return GetIndexForGoBack().has_value();
1182}
1183
Arthur Sonzognic686e8f2024-01-11 08:36:371184std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591185 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1186 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1187 return index;
1188 }
1189 }
Arthur Sonzognic686e8f2024-01-11 08:36:371190 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201191}
1192
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571193bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591194 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201195}
1196
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571197bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031198 int index = GetIndexForOffset(offset);
1199 return index >= 0 && index < GetEntryCount();
1200}
1201
Xiaohan Wang7f8052e02022-01-14 18:44:281202#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151203bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151204 if (offset == 0)
1205 return true;
1206 int increment = offset > 0 ? 1 : -1;
1207 int non_skippable_entries = 0;
1208 for (int index = GetIndexForOffset(increment);
1209 index >= 0 && index < GetEntryCount(); index += increment) {
1210 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1211 non_skippable_entries++;
1212
1213 if (non_skippable_entries == std::abs(offset))
1214 return true;
1215 }
1216 return false;
1217}
1218#endif
1219
David Bokanb8e0df02025-05-14 22:03:481220NavigationController::WeakNavigationHandleVector
1221NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371222 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061223
Kevin McNeeedc481c2023-04-27 22:30:581224 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211225
David Bokanb8e0df02025-05-14 22:03:481226 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201227}
1228
David Bokanb8e0df02025-05-14 22:03:481229NavigationController::WeakNavigationHandleVector
1230NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161231 // Note that at least one entry (the last one) will be non-skippable since
1232 // entries are marked skippable only when they add another entry because of
1233 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371234 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591235
Kevin McNeeedc481c2023-04-27 22:30:581236 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591237
David Bokanb8e0df02025-05-14 22:03:481238 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201239}
1240
David Bokanb8e0df02025-05-14 22:03:481241NavigationController::WeakNavigationHandleVector
1242NavigationControllerImpl::GoToIndex(int index) {
1243 std::vector<base::WeakPtr<NavigationRequest>> requests =
1244 GoToIndex(index, /*initiator_rfh=*/nullptr,
1245 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491246 /*navigation_api_key=*/nullptr,
1247 /*actual_navigation_start=*/base::TimeTicks::Now());
David Bokanb8e0df02025-05-14 22:03:481248 std::vector<base::WeakPtr<NavigationHandle>> handles;
1249 std::ranges::move(requests, std::back_inserter(handles));
1250 return handles;
Dave Tapuska8bfd84c2019-03-26 20:47:161251}
1252
William Liu62ae26c2024-08-08 14:28:161253std::vector<base::WeakPtr<NavigationRequest>>
1254NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201255 int index,
1256 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371257 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131258 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491259 const std::string* navigation_api_key,
1260 base::TimeTicks actual_navigation_start) {
sunjian30574a62017-03-21 21:39:441261 TRACE_EVENT0("browser,navigation,benchmark",
1262 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501263 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1264 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1265 entries_.size());
1266 // Indices should have have been validated by the caller.
1267 CHECK_GE(index, 0);
1268 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201269
Rakina Zata Amnif297a802022-01-18 03:53:431270 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1271 // We should never navigate to an existing initial NavigationEntry that is
1272 // the initial NavigationEntry for the initial empty document that hasn't
1273 // been overridden by the synchronous about:blank commit, to preserve
1274 // legacy behavior where trying to reload when the main frame is on the
1275 // initial empty document won't result in a navigation. See also
1276 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161277 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431278 }
1279
[email protected]cbab76d2008-10-13 22:42:471280 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201281
arthursonzogni5c4c202d2017-04-25 23:41:271282 DCHECK_EQ(nullptr, pending_entry_);
1283 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431284
arthursonzogni5c4c202d2017-04-25 23:41:271285 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201286 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271287 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1288 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Charlie Reisf4d51f402025-05-23 18:00:491289 return NavigateToExistingPendingEntry(
1290 ReloadType::NONE, initiator_rfh, soft_navigation_heuristics_task_id,
1291 navigation_api_key, actual_navigation_start);
[email protected]765b35502008-08-21 00:51:201292}
1293
[email protected]d202a7c2012-01-04 07:53:471294void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121295 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031296 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201297 return;
1298
[email protected]9ba14052012-06-22 23:50:031299 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201300}
1301
Nate Chapinbf682fa32022-09-26 22:41:201302void NavigationControllerImpl::GoToOffsetFromRenderer(
1303 int offset,
Yoav Weiss8c573952022-11-17 17:35:131304 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371305 std::optional<blink::scheduler::TaskAttributionId>
Charlie Reisf4d51f402025-05-23 18:00:491306 soft_navigation_heuristics_task_id,
1307 base::TimeTicks actual_navigation_start) {
Nate Chapinbb74c5a52023-07-21 23:13:351308 // Note: This is actually reached in unit tests.
1309 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431310 return;
1311
Nate Chapinbf682fa32022-09-26 22:41:201312 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131313 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491314 /*navigation_api_key=*/nullptr, actual_navigation_start);
Nate Chapin45f620582021-09-30 17:45:431315}
1316
William Liu62ae26c2024-08-08 14:28:161317std::vector<base::WeakPtr<NavigationRequest>>
1318NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271319 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1320 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491321 /*navigation_api_key=*/nullptr,
1322 /*actual_navigation_start=*/base::TimeTicks::Now());
William Liuec04e382024-05-23 18:03:271323}
1324
Xiaohan Wang7f8052e02022-01-14 18:44:281325#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151326void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1327 // Note: This is actually reached in unit tests.
1328 if (!CanGoToOffsetWithSkipping(offset))
1329 return;
1330
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421331 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151332 GoToIndex(GetIndexForOffset(offset));
1333 return;
1334 }
1335 int increment = offset > 0 ? 1 : -1;
1336 // Find the offset without counting skippable entries.
1337 int target_index = GetIndexForOffset(increment);
1338 int non_skippable_entries = 0;
1339 for (int index = target_index; index >= 0 && index < GetEntryCount();
1340 index += increment) {
1341 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1342 non_skippable_entries++;
1343
1344 if (non_skippable_entries == std::abs(offset)) {
1345 target_index = index;
1346 break;
1347 }
1348 }
1349
1350 GoToIndex(target_index);
1351}
1352#endif
1353
[email protected]41374f12013-07-24 02:49:281354bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151355 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281356 return false;
[email protected]6a13a6c2011-12-20 21:47:121357
[email protected]43032342011-03-21 14:10:311358 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281359 return true;
[email protected]cbab76d2008-10-13 22:42:471360}
1361
Michael Thiessen9b14d512019-09-23 21:19:471362void NavigationControllerImpl::PruneForwardEntries() {
1363 DiscardNonCommittedEntries();
1364 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471365 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471366 if (num_removed <= 0)
1367 return;
Nate Chapin9eb16be72022-09-23 22:54:311368 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471369 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1370 NotifyPrunedEntries(this, remove_start_index /* start index */,
1371 num_removed /* count */);
1372}
1373
Aran Gilman37d11632019-10-08 23:07:151374void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1375 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321376 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311377 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511378 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1379 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321380 }
1381}
1382
Harkiran Bolariaba823e42021-05-21 18:30:361383base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1384 const GURL& url,
1385 const Referrer& referrer,
1386 ui::PageTransition transition,
1387 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471388 LoadURLParams params(url);
1389 params.referrer = referrer;
1390 params.transition_type = transition;
1391 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361392 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471393}
1394
Harkiran Bolariaba823e42021-05-21 18:30:361395base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1396 const LoadURLParams& params) {
Charlie Reisf4d51f402025-05-23 18:00:491397 // For now, treat this as the actual navigation start time, even though a fair
1398 // amount of work is done in the browser process between the various ways to
1399 // start a navigation and reaching here (e.g., sending OpenURLParams through
1400 // the embedder and converting them to LoadURLParams). Note that this may be
1401 // used for some renderer-initiated navigations that go through
1402 // RenderFrameHostImpl::OpenURL as well.
1403 // TODO(crbug.com/385170155): Consider whether tracking this earlier work with
1404 // an earlier start time is worthwhile for metrics.
1405 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
1406
Lukasz Anforowicz435bcb582019-07-12 20:50:061407 if (params.is_renderer_initiated)
1408 DCHECK(params.initiator_origin.has_value());
1409
naskob8744d22014-08-28 17:07:431410 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151411 "NavigationControllerImpl::LoadURLWithParams", "url",
1412 params.url.possibly_invalid_spec());
Emmanuel Arias Soto9e159652025-05-16 07:53:551413
1414 if (IsDebugURL(params.url)) {
1415 // Browser-debug URLs won't go through NavigationThrottles so we have to
1416 // check them explicitly. See crbug.com/40605746.
1417 ContentBrowserClient* client = GetContentClient()->browser();
1418 if (client->ShouldBlockRendererDebugURL(
1419 params.url, browser_context_,
1420 GetTargetFrameTreeNodeForNavigation(params)
1421 ->current_frame_host())) {
1422 DiscardPendingEntry(false);
1423 return nullptr;
1424 }
1425 HandleDebugURL(params.url, params.transition_type,
1426 client->IsExplicitNavigation(params.transition_type));
[email protected]47752982014-07-29 08:01:431427 // If Telemetry is running, allow the URL load to proceed as if it's
1428 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491429 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181430 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361431 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181432 }
[email protected]47752982014-07-29 08:01:431433 }
[email protected]8bf1048012012-02-08 01:22:181434
[email protected]cf002332012-08-14 19:17:471435 // Checks based on params.load_type.
1436 switch (params.load_type) {
1437 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431438 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541439#if BUILDFLAG(IS_ANDROID)
1440 case LOAD_TYPE_PDF_ANDROID:
1441#endif
[email protected]cf002332012-08-14 19:17:471442 break;
1443 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261444 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211445 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471446 }
1447 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461448 }
[email protected]e47ae9472011-10-13 19:48:341449
[email protected]e47ae9472011-10-13 19:48:341450 // The user initiated a load, we don't need to reload anymore.
1451 needs_reload_ = false;
1452
Charlie Reisf4d51f402025-05-23 18:00:491453 return NavigateWithoutEntry(params, actual_navigation_start);
[email protected]132e281a2012-07-31 18:32:441454}
1455
Charlie Reis4c53a962023-06-21 23:17:531456void NavigationControllerImpl::LoadOriginalRequestURL() {
1457 // If the original request URL is not valid, matches the current URL, or
1458 // involves POST data, then simply reload. The POST check avoids issues with
1459 // sending data to the wrong page.
1460 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1461 const GURL& original_request_url =
1462 GetLastCommittedEntry()->GetOriginalRequestURL();
1463 if (!original_request_url.is_valid() ||
1464 original_request_url == last_committed_url ||
1465 GetLastCommittedEntry()->GetHasPostData()) {
1466 Reload(ReloadType::NORMAL, true);
1467 return;
1468 }
1469
1470 // Otherwise, attempt to load the original request URL without any of the
1471 // other data from the current NavigationEntry, replacing the current entry.
1472 // Loading the original URL is useful in cases such as modifying the user
1473 // agent.
1474 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1475 std::make_unique<NavigationController::LoadURLParams>(
1476 original_request_url);
1477 load_params->should_replace_current_entry = true;
1478 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1479 LoadURLWithParams(*load_params.get());
1480}
1481
Mohamed Abdelhalim833de902019-09-16 17:41:451482bool NavigationControllerImpl::PendingEntryMatchesRequest(
1483 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191484 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451485 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191486}
1487
[email protected]d202a7c2012-01-04 07:53:471488bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321489 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071490 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331491 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441492 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251493 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561494 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131495 NavigationRequest* navigation_request) {
1496 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331497
1498 // Note: validation checks and renderer kills due to invalid commit messages
1499 // must happen before getting here, in
1500 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1501 // effects of the navigation have already occurred.
1502
[email protected]cd2e15742013-03-08 04:08:311503 is_initial_navigation_ = false;
1504
Wang Hui96ab1012022-10-11 02:05:491505 // Any pending request to repost a form submission is no longer valid, since a
1506 // different NavigationEntry is committing.
1507 pending_reload_ = ReloadType::NONE;
1508
[email protected]0e8db942008-09-24 21:21:481509 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431510 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451511 if (entry_replaced_by_post_commit_error_) {
1512 // Same document navigation events with a post-commit error should already
1513 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1514 // reaching here.
1515 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331516
Xinghui Lub9e86a352024-05-17 16:29:421517 if (pending_entry_) {
1518 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1519 // `pending_entry_` isn't pointing to the last committed entry.
1520 // Instead, all reload approaches (e.g., in `Reload` and
1521 // `LoadIfNecessary`) should attempt to load the
1522 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1523 // entry itself.
1524 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1525 << "Incorrectly reloading the post commit error page entry.";
1526 }
Xinghui Lue4e50be2024-05-15 21:46:001527
Rakina Zata Amnie2d31312022-11-18 03:38:451528 // Any commit while a post-commit error page is showing should put the
1529 // original entry back, replacing the error page's entry. This includes
1530 // reloads, where the original entry was used as the pending entry and
1531 // should now be at the correct index at commit time.
1532 entries_[last_committed_entry_index_] =
1533 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481534 }
Rakina Zata Amnie2d31312022-11-18 03:38:451535 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1536 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001537 // Must honor user agent overrides in the |navigation_request|, such as
1538 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1539 // result, besides comparing |pending_entry_|'s user agent against
1540 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1541 // agent against LastCommittedEntry's.
1542 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541543 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1544 (PendingEntryMatchesRequest(navigation_request) &&
1545 pending_entry_->GetIsOverridingUserAgent() !=
1546 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001547 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451548 }
[email protected]ecd9d8702008-08-28 22:10:171549
Dave Tapuskaa2ab4f252021-07-08 21:31:281550 bool is_main_frame_navigation = !rfh->GetParent();
1551
Alexander Timind2f2e4f22019-04-02 20:04:531552 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1553 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281554 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141555 // BackForwardCacheMetrics to be associated with the new navigation's
1556 // NavigationEntry, by either creating a new object or reusing the previous
1557 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281558 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211559 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141560 back_forward_cache_metrics = BackForwardCacheMetrics::
1561 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281562 GetLastCommittedEntry(), is_main_frame_navigation,
1563 params.document_sequence_number);
1564 }
Yuzu Saijo29f96ca92022-12-08 04:54:121565
Alexander Timind2f2e4f22019-04-02 20:04:531566 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281567 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451568 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1569 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531570 }
1571 }
1572
Rakina Zata Amnifd8370b2022-11-14 13:32:251573 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1574 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091575 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251576 details->did_replace_entry =
1577 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091578
fdegans9caf66a2015-07-30 21:10:421579 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111580 // except for restored entries. This should be true even if the current commit
1581 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291582 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481583 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081584 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111585
1586 // Only make changes based on the pending entry if the NavigationRequest
1587 // matches it. Otherwise, the pending entry may be for a different request
1588 // (e.g., if a slow history navigation is pending while an auto-subframe
1589 // commit occurs).
1590 if (PendingEntryMatchesRequest(navigation_request)) {
1591 // It is no longer necessary to consider the pending entry as restored.
1592 if (pending_entry_->IsRestored()) {
1593 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1594 was_restored = true;
1595 }
[email protected]e9ba4472008-09-14 15:42:431596
Charlie Reisf8cde712022-10-20 16:25:091597 // If the SiteInstance has changed from the matching pending entry, this
1598 // must be treated as a new navigation with replacement. Set the replacement
1599 // bit here and ClassifyNavigation will identify this case and return
1600 // NEW_ENTRY.
1601 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1602 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1603 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251604 // TODO(nasko,creis,rakina): Move this to happen before committing the
1605 // navigation. This is a bit complicated because we don't currently
1606 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091607 details->did_replace_entry = true;
1608 }
Nasko Oskovaee2f862018-06-15 00:05:521609 }
[email protected]bcd904482012-02-01 01:54:221610
[email protected]e9ba4472008-09-14 15:42:431611 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101612 NavigationType navigation_type =
1613 ClassifyNavigation(rfh, params, navigation_request);
1614 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451615
Rakina Zata Amnie2d31312022-11-18 03:38:451616 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451617 // Ensure that this navigation does not add a navigation entry, since
1618 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1619 // beyond the last committed one. Therefore, `should_replace_current_entry`
1620 // should be set, which replaces the current entry, or this should be a
1621 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251622 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331623 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451624 }
1625
Rakina Zata Amnie2d31312022-11-18 03:38:451626 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551627 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241628 // This is a subframe navigation on the initial empty document, which used
1629 // to not have a NavigationEntry to attach to. Now it can attach to the
1630 // initial NavigationEntry, and we must ensure that its NavigationEntry
1631 // will keep the "initial NavigationEntry" status and won't append a new
1632 // NavigationEntry (it should always do replacement instead).
1633 // See also https://crbug.com/1277414.
1634 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551635 // Subframe navigation on initial NavigationEntry must not append a new
1636 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1637 // means every subframe navigation that happens while we're on the initial
1638 // NavigationEntry will always reuse the existing NavigationEntry and
1639 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101640 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1641 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551642 // This is a navigation that modifies the initial NavigationEntry, either
1643 // for a replacement or a reload. The initial NavigationEntry should
1644 // retain its "initial NavigationEntry" status in this case.
1645 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241646 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251647 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1648 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241649 // This is a synchronous about:blank navigation on the main frame, which
1650 // used to not create a NavigationEntry when we have no NavigationEntry on
1651 // FrameTree creation. We now have the initial NavigationEntry and are on
1652 // the initial NavigationEntry. To preserve old behavior, we should still
1653 // keep the "initial" status for the new NavigationEntry that we will
1654 // create for this navigation, so that subframe navigations under the
1655 // synchronously committed about:blank document will never append new
1656 // NavigationEntry, and instead will just reuse the initial
1657 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1658 // See also https://crbug.com/1277414.
1659 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551660 }
1661 }
1662 DCHECK(!details->should_stay_as_initial_entry ||
1663 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201664
eugenebutee08663a2017-04-27 17:43:121665 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441666 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121667
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071668 details->is_prerender_activation =
1669 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241670 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1671 ->GetOutermostMainFrame()
1672 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071673
Peter Boströmd7592132019-01-30 04:50:311674 // Make sure we do not discard the pending entry for a different ongoing
1675 // navigation when a same document commit comes in unexpectedly from the
1676 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1677 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581678 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061679 bool keep_pending_entry =
1680 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101681 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061682 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311683
Miyoung Shin3299cbf2022-11-22 01:41:101684 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061685 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491686 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051687 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561688 previous_document_had_history_intervention_activation,
1689 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431690 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061691 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491692 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1693 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001694 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431695 break;
[email protected]8ff00d72012-10-23 19:12:211696 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471697 RendererDidNavigateNewSubframe(
1698 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561699 previous_document_had_history_intervention_activation,
1700 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431701 break;
[email protected]8ff00d72012-10-23 19:12:211702 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391703 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251704 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001705 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081706 // We don't send a notification about auto-subframe PageState during
1707 // UpdateStateForFrame, since it looks like nothing has changed. Send
1708 // it here at commit time instead.
1709 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431710 return false;
creis59d5a47cb2016-08-24 23:57:191711 }
[email protected]e9ba4472008-09-14 15:42:431712 break;
Aran Gilman37d11632019-10-08 23:07:151713 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211714 NOTREACHED();
[email protected]765b35502008-08-21 00:51:201715 }
1716
[email protected]688aa65c62012-09-28 04:32:221717 // At this point, we know that the navigation has just completed, so
1718 // record the time.
1719 //
1720 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261721 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331722 base::Time timestamp =
1723 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1724 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131725 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221726
Peter Boströmd7592132019-01-30 04:50:311727 // If we aren't keeping the pending entry, there shouldn't be one at this
1728 // point. Clear it again in case any error cases above forgot to do so.
1729 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1730 // been cleared instead of protecting against it.
1731 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551732 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141733
[email protected]e9ba4472008-09-14 15:42:431734 // All committed entries should have nonempty content state so WebKit doesn't
1735 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471736 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321737 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221738 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441739 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141740
Alexander Timind2f2e4f22019-04-02 20:04:531741 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1742 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281743 if (back_forward_cache_metrics &&
1744 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531745 active_entry->set_back_forward_cache_metrics(
1746 std::move(back_forward_cache_metrics));
1747 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281748
1749 // `back_forward_cache_metrics()` may return null as we do not record
1750 // back-forward cache metrics for navigations in non-primary frame trees.
1751 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581752 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141753 // These are both only available from details at this point, so we capture
1754 // them here.
1755 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101756 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141757 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1758 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281759 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1760 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321761 IsBackForwardCacheEnabled() &&
1762 rfh->delegate()->IsBackForwardCacheSupported() &&
1763 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281764 }
naskoc7533512016-05-06 17:01:121765
Charles Reisc0507202017-09-21 00:40:021766 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1767 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1768 // A mismatch can occur if the renderer lies or due to a unique name collision
1769 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121770 FrameNavigationEntry* frame_entry =
1771 active_entry->GetFrameEntry(rfh->frame_tree_node());
Diana Qu1cc5eaf2025-06-21 00:04:271772 if (base::FeatureList::IsEnabled(
1773 features::kCheckSiteInstanceOnHistoryNavigation) &&
1774 frame_entry && frame_entry->site_instance()) {
Diana Qu2d6c85b2025-06-17 01:13:141775 int64_t dsn = navigation_request->frame_entry_document_sequence_number();
1776 if (dsn != -1 && dsn == frame_entry->document_sequence_number()) {
1777 // We CHECK that the SiteInstance matches the one stored in the session
1778 // history's FrameNavigationEntry, if the document sequence number (DSN)
1779 // also matches. This ensures the navigation is committing in the expected
1780 // SiteInstance.
1781 //
1782 // It's okay for the SiteInstance to differ if a cross-document redirect
1783 // occurred — in that case, the DSN in NavigationRequest should be cleared
1784 // (set to -1), and we skip the CHECK.
1785 CHECK(rfh->GetSiteInstance() == frame_entry->site_instance(),
1786 base::NotFatalUntil::M141)
1787 << "Session history navigation committed in a different SiteInstance "
1788 "than intended. "
1789 << "FrameNavigationEntry SiteInstance: "
1790 << frame_entry->site_instance()
1791 << ", Committed RFH SiteInstance: " << rfh->GetSiteInstance()
1792 << ", URL: " << params.url;
1793 }
1794 }
Charles Reisc0507202017-09-21 00:40:021795 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1796 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031797 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081798 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1799 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031800 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201801
1802 // Remember the bindings the renderer process has at this point, so that
1803 // we do not grant this entry additional bindings if we come back to it.
1804 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301805 }
[email protected]132e281a2012-07-31 18:32:441806
[email protected]97d8f0d2013-10-29 16:49:211807 // Once it is committed, we no longer need to track several pieces of state on
1808 // the entry.
naskoc7533512016-05-06 17:01:121809 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131810
[email protected]49bd30e62011-03-22 20:12:591811 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221812 // TODO(creis): This check won't pass for subframes until we create entries
1813 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001814 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421815 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591816
[email protected]e9ba4472008-09-14 15:42:431817 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001818 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001819 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311820 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531821
arthursonzogni7ddc6542021-04-09 09:16:501822 active_entry->SetIsOverridingUserAgent(
1823 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031824
[email protected]93f230e02011-06-01 14:40:001825 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291826
aelias100c9192017-01-13 00:01:431827 if (overriding_user_agent_changed)
1828 delegate_->UpdateOverridingUserAgent();
1829
creis03b48002015-11-04 00:54:561830 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1831 // one knows the latest NavigationEntry it is showing (whether it has
1832 // committed anything in this navigation or not). This allows things like
1833 // state and title updates from RenderFrames to apply to the latest relevant
1834 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381835 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031836 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381837 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431838
1839 if (navigation_request->IsPrerenderedPageActivation()) {
Charlie Reis99b2eba22025-01-31 19:18:571840 BroadcastHistoryIndexAndLength();
Alison Gale47d1537d2024-04-19 21:31:461841 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431842 // is activated. As a result, a "prerenderingchange" event listener sees the
1843 // history.length which is not updated yet. We should guarantee that
Charlie Reis99b2eba22025-01-31 19:18:571844 // history's length and index should be updated before a
Hayato Ito2c8c08d02021-06-23 03:38:431845 // "prerenderingchange" event listener runs. One possible approach is to use
1846 // the same IPC which "prerenderingchange" uses, and propagate history's
Charlie Reis99b2eba22025-01-31 19:18:571847 // length and index together with that.
Hayato Ito2c8c08d02021-06-23 03:38:431848 }
1849
[email protected]e9ba4472008-09-14 15:42:431850 return true;
initial.commit09911bf2008-07-26 23:55:291851}
1852
[email protected]8ff00d72012-10-23 19:12:211853NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321854 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101855 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241856 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591857 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511858 "ClassifyNavigation");
1859
avi7c6f35e2015-05-08 17:52:381860 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241861 // A new entry. We may or may not have a corresponding pending entry, and
1862 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001863 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491864 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061865 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381866 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241867 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511868 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381869 return NAVIGATION_TYPE_NEW_SUBFRAME;
1870 }
1871
Charlie Reisc0f17d2d2021-01-12 18:52:491872 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381873 DCHECK(!params.history_list_was_cleared);
1874
avi39c1edd32015-06-04 20:06:001875 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381876 // All manual subframes would be did_create_new_entry and handled above, so
1877 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081878 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1879 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381880 }
1881
Rakina Zata Amnif6950d552020-11-24 03:26:101882 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1883 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381884 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1885 // create a new page.
1886
Hayato Ito2ae49442021-07-02 02:59:251887 // This main frame navigation is not a history navigation (since
1888 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1889 // reload or a replacement navigation, which will modify the existing entry.
1890 //
Nasko Oskov332593c2018-08-16 17:21:341891 // TODO(nasko): With error page isolation, reloading an existing session
1892 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491893 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341894 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511895 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491896 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061897 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381898 }
1899
Charlie Reisf8cde712022-10-20 16:25:091900 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521901 // If the SiteInstance of the |pending_entry_| does not match the
1902 // SiteInstance that got committed, treat this as a new navigation with
1903 // replacement. This can happen if back/forward/reload encounters a server
1904 // redirect to a different site or an isolated error page gets successfully
1905 // reloaded into a different SiteInstance.
1906 if (pending_entry_->site_instance() &&
1907 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491908 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061909 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521910 }
creis77c9aa32015-09-25 19:59:421911
Nasko Oskovaee2f862018-06-15 00:05:521912 if (pending_entry_index_ == -1) {
1913 // In this case, we have a pending entry for a load of a new URL but Blink
1914 // didn't do a new navigation (params.did_create_new_entry). First check
1915 // to make sure Blink didn't treat a new cross-process navigation as
1916 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161917 // we must treat it as NEW rather than the converted reload case below,
1918 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451919 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161920 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061921 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521922 }
1923
1924 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161925 // We will create a pending entry, but NavigateWithoutEntry will convert
1926 // it to a reload since it's the same page and not create a new entry for
1927 // it. (The user doesn't want to have a new back/forward entry when they
1928 // do this.) Therefore we want to just ignore the pending entry and go
1929 // back to where we were (the "existing entry").
1930 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061931 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521932 }
avi7c6f35e2015-05-08 17:52:381933 }
1934
Rakina Zata Amni153d5702021-09-13 22:48:001935 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381936 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491937 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1938 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161939 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061940 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381941 }
1942
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121943 if (navigation_request->DidEncounterError() &&
1944 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101945 nav_entry_id == failed_pending_entry_id_) {
Charlie Reisb5f39cf2024-11-12 16:55:011946 // If the renderer was going to a pending entry that got cleared because of
1947 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511948 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491949 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061950 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381951 }
1952
Charlie Reisc0f17d2d2021-01-12 18:52:491953 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101954 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511955 trace_return.traced_value()->SetInteger("existing_entry_index",
1956 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381957 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441958 // The renderer has committed a navigation to an entry that no longer
1959 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491960 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061961 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381962 }
1963
avi7c6f35e2015-05-08 17:52:381964 // Since we weeded out "new" navigations above, we know this is an existing
1965 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491966 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061967 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381968}
1969
Rakina Zata Amni3460d382021-10-29 00:43:371970void NavigationControllerImpl::UpdateNavigationEntryDetails(
1971 NavigationEntryImpl* entry,
1972 RenderFrameHostImpl* rfh,
1973 const mojom::DidCommitProvisionalLoadParams& params,
1974 NavigationRequest* request,
1975 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001976 bool is_new_entry,
1977 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371978 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171979 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371980 entry->AddOrUpdateFrameEntry(
1981 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571982 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371983 rfh->GetSiteInstance(), nullptr, params.url,
1984 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171985 Referrer(*params.referrer),
1986 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371987 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171988 request ? request->GetRedirectChain() : redirects, params.page_state,
1989 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371990 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171991 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211992 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171993 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371994
1995 if (rfh->GetParent()) {
1996 // Only modify the NavigationEntry for main frame navigations.
1997 return;
1998 }
1999 if (entry->update_virtual_url_with_url())
2000 UpdateVirtualURLToURL(entry, params.url);
2001 // Don't use the page type from the pending entry. Some interstitial page
2002 // may have set the type to interstitial. Once we commit, however, the page
2003 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:172004 entry->set_page_type((request && request->DidEncounterError())
2005 ? PAGE_TYPE_ERROR
2006 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:432007 if (commit_details && commit_details->should_stay_as_initial_entry) {
2008 // Retain the "initial NavigationEntry" status.
2009 if (request->IsSameDocument()) {
2010 // If this is for a same-document navigation, the NavigationEntry must be
2011 // reused and should already be marked as the initial NavigationEntry.
2012 DCHECK(entry->IsInitialEntry());
2013 } else {
2014 // If this is for a cross-document navigation, it can be caused by a
2015 // renderer-initiated reload, or the synchronous about:blank commit. Mark
2016 // "for synchronous about:blank" in the latter case, and also when it is
2017 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
2018 // is not for a synchronous about:blank commit.
2019 NavigationEntryImpl::InitialNavigationEntryState new_state =
2020 NavigationEntryImpl::InitialNavigationEntryState::
2021 kInitialNotForSynchronousAboutBlank;
2022 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
2023 request->is_synchronous_renderer_commit()) {
2024 new_state = NavigationEntryImpl::InitialNavigationEntryState::
2025 kInitialForSynchronousAboutBlank;
2026 }
2027 entry->set_initial_navigation_entry_state(new_state);
2028 }
2029 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
2030 // Remove the "initial NavigationEntry" status.
2031 entry->set_initial_navigation_entry_state(
2032 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:002033 }
Rakina Zata Amniddf10502022-01-15 02:56:552034
Rakina Zata Amni3460d382021-10-29 00:43:372035 if (is_new_entry) {
2036 // Some properties of the NavigationEntry are only set when the entry is
2037 // new (we aren't reusing it).
2038 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:172039 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:402040 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:012041 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
2042 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:372043 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
2044 } else {
2045 // We are reusing the NavigationEntry. The site instance will normally be
2046 // the same except for a few cases:
2047 // 1) session restore, when no site instance will be assigned or
2048 // 2) redirect, when the site instance is reset.
2049 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
2050 entry->site_instance() == rfh->GetSiteInstance());
2051 }
2052}
2053
Rakina Zata Amniafd3c6582021-11-30 06:19:172054void NavigationControllerImpl::CreateInitialEntry() {
2055 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:032056 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:172057 auto params = mojom::DidCommitProvisionalLoadParams::New();
2058 // The initial NavigationEntry's URL is the empty URL. This preserves the old
2059 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
2060 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:402061 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:172062 params->http_status_code = 0;
2063 params->url_is_unreachable = false;
2064 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:172065 params->post_id = -1;
2066 params->embedding_token = base::UnguessableToken::Create();
2067 params->navigation_token = base::UnguessableToken::Create();
2068 params->did_create_new_entry = true;
2069 params->origin = rfh->GetLastCommittedOrigin();
2070 params->should_update_history = true;
2071 params->item_sequence_number = 0;
2072 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:152073 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:172074 params->transition = is_in_fenced_frame_tree
2075 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
2076 : ui::PAGE_TRANSITION_LINK;
2077 params->referrer = blink::mojom::Referrer::New();
2078
Rakina Zata Amniafd3c6582021-11-30 06:19:172079 auto new_entry = std::make_unique<NavigationEntryImpl>(
2080 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:382081 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:212082 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
2083 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
2084 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172085 UpdateNavigationEntryDetails(
2086 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:002087 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
2088 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172089
2090 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
2091 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:002092 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172093}
2094
Charlie Reisc0f17d2d2021-01-12 18:52:492095void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:322096 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072097 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362098 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442099 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562100 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002101 NavigationRequest* request,
2102 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572103 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372104 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452105 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372106 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522107 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2108 initiator_base_url = request->common_params().initiator_base_url;
2109 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062110
creisf49dfc92016-07-26 17:05:182111 // First check if this is an in-page navigation. If so, clone the current
2112 // entry instead of looking at the pending entry, because the pending entry
2113 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452114 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302115 FrameNavigationEntry* previous_frame_entry =
2116 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452117 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482118 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572119 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082120 rfh->GetSiteInstance(), nullptr, params.url,
2121 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212122 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092123 request->GetRedirectChain(), params.page_state, params.method,
2124 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392125 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302126 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572127 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302128 // FrameNavigationEntry.
2129 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572130 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032131
creisf49dfc92016-07-26 17:05:182132 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032133 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522134 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2135 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572136 // TODO(jam): we had one report of this with a URL that was redirecting to
2137 // only tildes. Until we understand that better, don't copy the cert in
2138 // this case.
2139 new_entry->GetSSL() = SSLStatus();
2140 }
creisf49dfc92016-07-26 17:05:182141
Patrick Monette50e8bd82019-06-13 22:40:452142 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2143 // that |frame_entry| should now have a reference count of exactly 2: one
2144 // due to the local variable |frame_entry|, and another due to |new_entry|
2145 // also retaining one. This should never fail, because it's the main frame.
2146 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182147 }
2148
Harkiran Bolaria59290d62021-03-17 01:53:012149 // If this is an activation navigation from a prerendered page, transfer the
2150 // new entry from an entry already created and stored in the
2151 // NavigationRequest. |new_entry| will not have been set prior to this as
2152 // |is_same_document| is mutually exclusive with
2153 // |IsPrerenderedPageActivation|.
2154 if (request->IsPrerenderedPageActivation()) {
2155 DCHECK(!is_same_document);
2156 DCHECK(!new_entry);
2157 new_entry = request->TakePrerenderNavigationEntry();
2158 DCHECK(new_entry);
2159 }
2160
Charlie Reisc0f17d2d2021-01-12 18:52:492161 // Only make a copy of the pending entry if it is appropriate for the new
2162 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452163 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042164 // 1. The SiteInstance hasn't been assigned to something else.
2165 // 2. The pending entry was intended as a new entry, rather than being a
2166 // history navigation that was interrupted by an unrelated,
2167 // renderer-initiated navigation.
2168 // TODO(csharrison): Investigate whether we can remove some of the coarser
2169 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452170 if (!new_entry && PendingEntryMatchesRequest(request) &&
2171 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342172 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432173 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352174 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432175
Camille Lamy62b826012019-02-26 09:15:472176 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452177 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182178 }
2179
Charlie Reisc0f17d2d2021-01-12 18:52:492180 // For cross-document commits with no matching pending entry, create a new
2181 // entry.
creisf49dfc92016-07-26 17:05:182182 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062183 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072184 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212185 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582186 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452187 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172188 nullptr, // blob_url_loader_factory
2189 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242190
2191 // Find out whether the new entry needs to update its virtual URL on URL
2192 // change and set up the entry accordingly. This is needed to correctly
2193 // update the virtual URL when replaceState is called after a pushState.
2194 GURL url = params.url;
2195 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492196 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412197 // update the virtual URL based on the new URL. For example, this is needed
2198 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2199 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372200 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2201 &url, browser_context_, &needs_update);
2202 new_entry->set_update_virtual_url_with_url(needs_update);
2203
Camille Lamy62b826012019-02-26 09:15:472204 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452205 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432206 }
2207
Alison Gale770f3fc2024-04-27 00:39:582208 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2209 // set for prerendered contents, if any. This is because
2210 // prerendering/activation technically won't be creating a new document.
2211 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2212 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012213 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372214 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2215 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002216 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082217
Harkiran Bolaria59290d62021-03-17 01:53:012218 // history.pushState() is classified as a navigation to a new page, but sets
2219 // is_same_document to true. In this case, we already have the title and
2220 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452221 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012222 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2223 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2224 }
[email protected]3a868f212014-08-09 10:41:192225 }
[email protected]ff64b3e2014-05-31 04:07:332226
[email protected]60d6cca2013-04-30 08:47:132227 DCHECK(!params.history_list_was_cleared || !replace_entry);
2228 // The browser requested to clear the session history when it initiated the
2229 // navigation. Now we know that the renderer has updated its state accordingly
2230 // and it is safe to also clear the browser side history.
2231 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552232 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132233 entries_.clear();
2234 last_committed_entry_index_ = -1;
2235 }
2236
Nasko Oskovaee2f862018-06-15 00:05:522237 // If this is a new navigation with replacement and there is a
2238 // pending_entry_ which matches the navigation reported by the renderer
2239 // process, then it should be the one replaced, so update the
2240 // last_committed_entry_index_ to use it.
2241 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092242 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522243 last_committed_entry_index_ = pending_entry_index_;
2244 }
2245
Alexander Timine3ec4192020-04-20 16:39:402246 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562247 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402248 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052249
Yuzu Saijoa725585f2022-11-28 04:14:032250 // If this is a history navigation and the old entry has an existing
2251 // back/forward cache metrics object, keep using the old one so that the
2252 // reasons logged from the last time the page navigated gets preserved.
2253 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2254 request)) {
2255 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2256 // because some tests do not have a pending entry.
2257 NavigationEntryImpl* entry =
2258 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2259 if (entry && entry->back_forward_cache_metrics()) {
2260 scoped_refptr<BackForwardCacheMetrics> metrics =
2261 entry->TakeBackForwardCacheMetrics();
2262 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2263 }
2264 }
2265
Andrew Verge754c70a2025-04-17 17:19:192266 bool was_post_commit_error =
2267 request->browser_initiated_error_navigation_type() ==
2268 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit;
2269
Carlos IL42b416592019-10-07 23:10:362270 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Andrew Verge754c70a2025-04-17 17:19:192271 was_post_commit_error, rfh->IsNestedWithinFencedFrame(),
2272 commit_details);
[email protected]e9ba4472008-09-14 15:42:432273}
2274
Charlie Reisc0f17d2d2021-01-12 18:52:492275void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322276 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072277 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362278 bool is_same_document,
jam48cea9082017-02-15 06:13:292279 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452280 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002281 bool keep_pending_entry,
2282 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562283 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2284 << "that a last committed entry exists.";
2285
[email protected]e9ba4472008-09-14 15:42:432286 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002287 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432288
Charlie Reis7e2cb6d2021-01-26 01:27:162289 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002290 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162291 // We're guaranteed to have a last committed entry if intended_as_new_entry
2292 // is true.
avicbdc4c12015-07-01 16:07:112293 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162294
2295 // If the NavigationRequest matches a new pending entry and is classified as
2296 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2297 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092298 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162299 // Note: The pending entry will usually have a real ReloadType here, but
2300 // it can still be ReloadType::NONE in cases that
2301 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2302
2303 // If we classified this correctly, the SiteInstance should not have
2304 // changed.
2305 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2306
2307 // For converted reloads, we assign the entry's unique ID to be that of
2308 // the new one. Since this is always the result of a user action, we want
2309 // to dismiss infobars, etc. like a regular user-initiated navigation.
2310 entry->set_unique_id(pending_entry_->GetUniqueID());
2311
2312 // The extra headers may have changed due to reloading with different
2313 // headers.
2314 entry->set_extra_headers(pending_entry_->extra_headers());
2315 }
2316 // Otherwise, this was intended as a new entry but the pending entry was
2317 // lost in the meantime and no new entry was created. We are stuck at the
2318 // last committed entry.
2319
2320 // Even if this is a converted reload from pressing enter in the omnibox,
2321 // the server could redirect, requiring an update to the SSL status. If this
2322 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452323 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162324 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472325 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452326 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162327 }
Rakina Zata Amnif6950d552020-11-24 03:26:102328 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112329 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102330 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b90ce2016-09-01 16:58:162331
eugenebut604866f2017-05-10 21:35:362332 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452333 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362334 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2335 // this was a restored same document navigation entry, then it won't have
2336 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2337 // navigated it.
jam48cea9082017-02-15 06:13:292338 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522339 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2340 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292341 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2342 was_restored) {
2343 entry->GetSSL() = last_entry->GetSSL();
2344 }
2345 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452346 // In rapid back/forward navigations |request| sometimes won't have a cert
2347 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192348 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452349 if (request->GetSSLInfo().has_value() &&
2350 request->GetSSLInfo()->is_valid()) {
2351 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522352 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2353 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192354 entry->GetSSL() = SSLStatus();
2355 }
jam48cea9082017-02-15 06:13:292356 }
avicbdc4c12015-07-01 16:07:112357 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272358 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572359 // navigations that are EXISTING_ENTRY are same-document navigations that
2360 // result in replacement (e.g. history.replaceState(), location.replace(),
2361 // forced replacements for trivial session history contexts). For these
2362 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112363 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102364
Alison Gale81f4f2c72024-04-22 19:33:312365 // TODO(crbug.com/40532777): Set page transition type to
2366 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2367 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2368 // well as to fix the inconsistency with what we report to observers
2369 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102370
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572371 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102372
eugenebut604866f2017-05-10 21:35:362373 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452374 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362375 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472376 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452377 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112378 }
2379 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432380
Rakina Zata Amni3460d382021-10-29 00:43:372381 UpdateNavigationEntryDetails(entry, rfh, params, request,
2382 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002383 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302384
[email protected]5ccd4dc2012-10-24 02:28:142385 // The redirected to page should not inherit the favicon from the previous
2386 // page.
eugenebut604866f2017-05-10 21:35:362387 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482388 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142389
Charlie Reis951f43372023-05-05 00:30:072390 // Update the last committed index to reflect the committed entry. Do this
2391 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2392 // delegate sees the correct committed index when notified of navigation
2393 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2394 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212395 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072396
Peter Boströmd7592132019-01-30 04:50:312397 // We should also usually discard the pending entry if it corresponds to a
2398 // different navigation, since that one is now likely canceled. In rare
2399 // cases, we leave the pending entry for another navigation in place when we
2400 // know it is still ongoing, to avoid a flicker in the omnibox (see
2401 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432402 //
2403 // Note that we need to use the "internal" version since we don't want to
2404 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312405 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002406 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432407}
2408
[email protected]d202a7c2012-01-04 07:53:472409void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322410 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072411 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362412 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472413 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562414 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002415 NavigationRequest* request,
2416 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262417 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2418 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552419 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2420 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112421
[email protected]e9ba4472008-09-14 15:42:432422 // Manual subframe navigations just get the current entry cloned so the user
2423 // can go back or forward to it. The actual subframe information will be
2424 // stored in the page state for each of those entries. This happens out of
2425 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092426 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2427 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382428
Mikel Astizba9cf2fd2017-12-17 10:38:102429 // The DCHECK below documents the fact that we don't know of any situation
2430 // where |replace_entry| is true for subframe navigations. This simplifies
2431 // reasoning about the replacement struct for subframes (see
2432 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2433 DCHECK(!replace_entry);
2434
Patrick Monette50e8bd82019-06-13 22:40:452435 // This FrameNavigationEntry might not end up being used in the
2436 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372437 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452438 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372439 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522440 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2441 initiator_base_url = request->common_params().initiator_base_url;
2442 }
Nate Chapin63db0d12022-01-20 22:03:302443 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2444 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212445 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302446 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572447 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302448 if (is_same_document) {
2449 FrameNavigationEntry* previous_frame_entry =
2450 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572451 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302452 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572453 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302454 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572455 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302456 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572457 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302458 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572459 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302460 policy_container_policies->referrer_policy);
2461 }
2462
Patrick Monette50e8bd82019-06-13 22:40:452463 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482464 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572465 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082466 rfh->GetSiteInstance(), nullptr, params.url,
2467 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212468 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2469 request->GetRedirectChain(), params.page_state, params.method,
2470 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572471 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032472
creisce0ef3572017-01-26 17:53:082473 std::unique_ptr<NavigationEntryImpl> new_entry =
2474 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452475 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032476 frame_tree_->root());
creise062d542015-08-25 02:01:552477
Alexander Timine3ec4192020-04-20 16:39:402478 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562479 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402480 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472481
creisce0ef3572017-01-26 17:53:082482 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452483 // to replace, which can happen due to a unique name change. See
2484 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2485 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382486
Dave Tapuska87696ae2021-11-18 18:48:312487 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152488 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432489}
2490
[email protected]d202a7c2012-01-04 07:53:472491bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322492 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072493 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392494 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252495 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002496 NavigationRequest* request,
2497 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292498 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2499 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2500
[email protected]e9ba4472008-09-14 15:42:432501 // We're guaranteed to have a previously committed entry, and we now need to
2502 // handle navigation inside of a subframe in it without creating a new entry.
2503 DCHECK(GetLastCommittedEntry());
2504
creis913c63ce2016-07-16 19:52:522505 // For newly created subframes, we don't need to send a commit notification.
2506 // This is only necessary for history navigations in subframes.
2507 bool send_commit_notification = false;
2508
Rakina Zata Amnif6950d552020-11-24 03:26:102509 // If |nav_entry_id| is non-zero and matches an existing entry, this
2510 // is a history navigation. Update the last committed index accordingly. If
2511 // we don't recognize the |nav_entry_id|, it might be a recently
2512 // pruned entry. We'll handle it below.
2513 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2514 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472515 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062516 // Make sure that a subframe commit isn't changing the main frame's
2517 // origin. Otherwise the renderer process may be confused, leading to a
2518 // URL spoof. We can't check the path since that may change
2519 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572520 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2521 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242522 // We should use checks similar to RenderFrameHostImpl's
2523 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2524 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572525 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2526 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2527 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2528 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522529 current_top_url.DeprecatedGetOriginAsURL() !=
2530 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442531 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512532 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062533 }
creis3cdc3b02015-05-29 23:00:472534
creis913c63ce2016-07-16 19:52:522535 // We only need to discard the pending entry in this history navigation
2536 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062537 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002538 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522539
2540 // History navigations should send a commit notification.
2541 send_commit_notification = true;
avi98405c22015-05-21 20:47:062542 }
[email protected]e9ba4472008-09-14 15:42:432543 }
[email protected]f233e4232013-02-23 00:55:142544
creisce0ef3572017-01-26 17:53:082545 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2546 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372547 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2548 // exists), or we may want to clobber it and create a new one. We update in
2549 // cases where the corresponding FrameNavigationEntry is conceptually similar
2550 // to the document described by the commit params: same-document
2551 // navigations, history traversal to an existing entry, and reloads (including
2552 // a "soft reload" where we navigate to the same url without flagging it as a
2553 // reload). But in the case of a different document that is not logically
2554 // related to the committed FrameNavigationEntry's document (cross-document,
2555 // not same url, not a reload, not a history traversal), we replace rather
2556 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252557 //
Nate Chapin9f169072021-06-09 19:32:372558 // In the case where we update, the FrameNavigationEntry will potentially be
2559 // shared across multiple NavigationEntries, and any updates will be reflected
2560 // in all of those NavigationEntries. In the replace case, any existing
2561 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252562 //
2563 // When navigating away from the initial empty document, we also update rather
2564 // than replace. Either update or replace will overwrite the initial empty
2565 // document state for |last_committed|, but if the FrameNavigationEntry for
2566 // the initial empty document is shared across multiple NavigationEntries (due
2567 // to a navigation in another frame), we want to make sure we overwrite the
2568 // initial empty document state everywhere this FrameNavigationEntry is used,
2569 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452570 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372571 FrameNavigationEntry* last_committed_frame_entry =
2572 last_committed->GetFrameEntry(rfh->frame_tree_node());
2573 NavigationEntryImpl::UpdatePolicy update_policy =
2574 NavigationEntryImpl::UpdatePolicy::kUpdate;
2575 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312576 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372577 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252578 last_committed_frame_entry->url() != params.url &&
2579 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372580 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2581 }
2582
Rakina Zata Amni3460d382021-10-29 00:43:372583 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002584 update_policy, false /* is_new_entry */,
2585 commit_details);
creis625a0c7d2015-03-24 23:17:122586
creis913c63ce2016-07-16 19:52:522587 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432588}
2589
[email protected]d202a7c2012-01-04 07:53:472590int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232591 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032592 for (size_t i = 0; i < entries_.size(); ++i) {
2593 if (entries_[i].get() == entry)
2594 return i;
2595 }
2596 return -1;
[email protected]765b35502008-08-21 00:51:202597}
2598
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572599void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242600 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572601 NavigationControllerImpl* source =
2602 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572603 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382604 DCHECK_EQ(1, GetEntryCount());
2605 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472606 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172607 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572608
Francois Dorayeaace782017-06-21 16:37:242609 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442610 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572611 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572612
Fergal Dalya1d569972021-03-16 03:24:532613 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302614 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532615 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2616 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302617 }
[email protected]4e6419c2010-01-15 04:50:342618
Lukasz Anforowicz0de0f452020-12-02 19:57:152619 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572620}
2621
[email protected]79368982013-11-13 01:11:012622bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022623 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162624 if (last_committed_entry_index_ == -1)
2625 return false;
[email protected]9350602e2013-02-26 23:27:442626
[email protected]474f8512013-05-31 22:31:162627 // We cannot prune if there is a pending entry at an existing entry index.
2628 // It may not commit, so we have to keep the last committed entry, and thus
2629 // there is no sensible place to keep the pending entry. It is ok to have
2630 // a new pending entry, which can optionally commit as a new navigation.
2631 if (pending_entry_index_ != -1)
2632 return false;
2633
[email protected]474f8512013-05-31 22:31:162634 return true;
2635}
2636
[email protected]79368982013-11-13 01:11:012637void NavigationControllerImpl::PruneAllButLastCommitted() {
2638 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162639
avi2b177592014-12-10 02:08:022640 DCHECK_EQ(0, last_committed_entry_index_);
2641 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442642
Charlie Reis99b2eba22025-01-31 19:18:572643 BroadcastHistoryIndexAndLength();
[email protected]9350602e2013-02-26 23:27:442644}
2645
[email protected]79368982013-11-13 01:11:012646void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162647 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012648 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262649
Nate Chapin9eb16be72022-09-23 22:54:312650 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2651
[email protected]474f8512013-05-31 22:31:162652 // Erase all entries but the last committed entry. There may still be a
2653 // new pending entry after this.
2654 entries_.erase(entries_.begin(),
2655 entries_.begin() + last_committed_entry_index_);
2656 entries_.erase(entries_.begin() + 1, entries_.end());
2657 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262658}
2659
Christian Dullweber1af31e62018-02-22 11:49:482660void NavigationControllerImpl::DeleteNavigationEntries(
2661 const DeletionPredicate& deletionPredicate) {
2662 // It is up to callers to check the invariants before calling this.
2663 CHECK(CanPruneAllButLastCommitted());
2664 std::vector<int> delete_indices;
2665 for (size_t i = 0; i < entries_.size(); i++) {
2666 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572667 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482668 delete_indices.push_back(i);
2669 }
2670 }
2671 if (delete_indices.empty())
2672 return;
2673
2674 if (delete_indices.size() == GetEntryCount() - 1U) {
2675 PruneAllButLastCommitted();
2676 } else {
2677 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382678 for (const auto& index : base::Reversed(delete_indices)) {
2679 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482680 }
Charlie Reis99b2eba22025-01-31 19:18:572681 BroadcastHistoryIndexAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482682 }
2683 delegate()->NotifyNavigationEntriesDeleted();
2684}
2685
Carlos Caballero35ce710c2019-09-19 10:59:452686BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2687 return back_forward_cache_;
2688}
2689
William Liu055a3542023-04-02 17:21:192690NavigationEntryScreenshotCache*
2691NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212692 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262693 if (!nav_entry_screenshot_cache_ &&
2694 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192695 nav_entry_screenshot_cache_ =
2696 std::make_unique<NavigationEntryScreenshotCache>(
2697 BrowserContextImpl::From(browser_context_)
2698 ->GetNavigationEntryScreenshotManager()
2699 ->GetSafeRef(),
2700 this);
2701 }
2702 return nav_entry_screenshot_cache_.get();
2703}
2704
clamy987a3752018-05-03 17:36:262705void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2706 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2707 // progress, since this will cause a use-after-free. (We only allow this
2708 // when the tab is being destroyed for shutdown, since it won't return to
2709 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032710 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
Minoru Chikamune13ab4de2025-05-14 21:54:072711 // If `was_failure` is true, it means that the pending entry was discarded by
2712 // a `PendingEntryRefDeleted` call within `OnRequestFailedInternal`, in
2713 // response to a navigation request failure. This case is not at risk for
2714 // re-entrancy when `can_be_in_navigate_to_pending_entry_` is true, because
2715 // that code also creates another `PendingEntryRef` that would prevent the
2716 // `DiscardPendingEntry` call if the PostTask were skipped. See
2717 // https://crbug.com/411855273.
2718 if (!was_failure && can_be_in_navigate_to_pending_entry_ &&
Minoru Chikamune646eba42025-04-14 01:25:032719 !frame_tree_->IsBeingDestroyed()) {
2720 CheckPotentialNavigationReentrancy();
2721 }
clamy987a3752018-05-03 17:36:262722
2723 if (was_failure && pending_entry_) {
2724 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2725 } else {
2726 failed_pending_entry_id_ = 0;
2727 }
2728
2729 if (pending_entry_) {
2730 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332731 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262732 pending_entry_index_ = -1;
2733 pending_entry_ = nullptr;
2734 }
arthursonzogni66f711c2019-10-08 14:40:362735
2736 // Ensure any refs to the current pending entry are ignored if they get
2737 // deleted, by clearing the set of known refs. All future pending entries will
2738 // only be affected by new refs.
2739 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262740}
2741
2742void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2743 if (pending_entry_)
2744 pending_entry_->set_ssl_error(error);
2745}
2746
Xiaohan Wang7f8052e02022-01-14 18:44:282747#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422748// static
2749bool NavigationControllerImpl::ValidateDataURLAsString(
2750 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2751 if (!data_url_as_string)
2752 return false;
2753
2754 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2755 return false;
2756
2757 // The number of characters that is enough for validating a data: URI.
2758 // From the GURL's POV, the only important part here is scheme, it doesn't
2759 // check the actual content. Thus we can take only the prefix of the url, to
2760 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562761 constexpr size_t kDataUriPrefixMaxLen = 64;
2762 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2763 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422764 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2765 return false;
2766
2767 return true;
2768}
2769#endif
2770
Shivani Sharma194877032019-03-07 17:52:472771void NavigationControllerImpl::NotifyUserActivation() {
2772 // When a user activation occurs, ensure that all adjacent entries for the
2773 // same document clear their skippable bit, so that the history manipulation
2774 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012775 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172776 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012777 // If the value of CanGoBack changes as a result of making some entries
2778 // non-skippable, then we must let the delegate know to update its UI state.
2779 // See https://crbug.com/1477784.
2780 if (!can_go_back && CanGoBack()) {
2781 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2782 }
Shivani Sharma194877032019-03-07 17:52:472783}
2784
clamy987a3752018-05-03 17:36:262785bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2786 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332787 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2788 blink::LocalFrameToken initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492789 int initiator_process_id,
2790 base::TimeTicks actual_navigation_start) {
clamy987a3752018-05-03 17:36:262791 NavigationEntryImpl* entry =
2792 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2793 if (!entry)
2794 return false;
2795
2796 FrameNavigationEntry* frame_entry =
2797 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2798 if (!frame_entry)
2799 return false;
2800
Camille Lamy5193caa2018-10-12 11:59:422801 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572802 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232803 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332804 true /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492805 initiator_process_id, actual_navigation_start);
clamyea99ea12018-05-28 13:54:232806
2807 if (!request)
2808 return false;
2809
arthursonzognif046d4a2019-12-12 19:08:102810 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412811
Rakina Zata Amni1c83b082023-02-08 01:09:002812 SCOPED_CRASH_KEY_STRING256(
2813 "Bug1400009", "req_url",
2814 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2815 SCOPED_CRASH_KEY_NUMBER(
2816 "Bug1400009", "nav_entry_si",
2817 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2818 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2819 frame_entry->site_instance()
2820 ? ((int)frame_entry->site_instance()->GetId())
2821 : -1);
2822 bool has_sig =
2823 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2824 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2825 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2826 has_sig ? (!!frame_tree_->GetRenderViewHost(
2827 frame_entry->site_instance()->group()))
2828 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052829 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2830 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232831
2832 return true;
clamy987a3752018-05-03 17:36:262833}
2834
Tsuyoshi Horo52fd08e2020-07-07 07:03:452835bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
Charlie Reisf4d51f402025-05-23 18:00:492836 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Tsuyoshi Horo52fd08e2020-07-07 07:03:452837 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2838 if (!entry)
2839 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432840
2841 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2842 // We should never navigate to an existing initial NavigationEntry that is
2843 // the initial NavigationEntry for the initial empty document that hasn't
2844 // been overridden by the synchronous about:blank commit, to preserve
2845 // legacy behavior where trying to reload when the main frame is on the
2846 // initial empty document won't result in a navigation. See also
2847 // https://crbug.com/1277414.
2848 return false;
2849 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452850 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2851 if (!frame_entry)
2852 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142853 ReloadType reload_type = ReloadType::NORMAL;
2854 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452855 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142856 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452857 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432858 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372859 std::nullopt /* initiator_frame_token */,
Charlie Reisf4d51f402025-05-23 18:00:492860 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
2861 actual_navigation_start);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452862 if (!request)
2863 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052864 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452865 return true;
2866}
2867
clamy987a3752018-05-03 17:36:262868void NavigationControllerImpl::NavigateFromFrameProxy(
2869 RenderFrameHostImpl* render_frame_host,
2870 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022871 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452872 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372873 const std::optional<url::Origin>& initiator_origin,
2874 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262875 bool is_renderer_initiated,
2876 SiteInstance* source_site_instance,
2877 const Referrer& referrer,
2878 ui::PageTransition page_transition,
2879 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252880 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262881 const std::string& method,
2882 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092883 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142884 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212885 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502886 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372887 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292888 blink::mojom::NavigationInitiatorActivationAndAdStatus
2889 initiator_activation_and_ad_status,
Charlie Reise1d9b8182025-04-02 04:32:122890 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:222891 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492892 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462893 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452894 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582895 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032896 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342897 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372898 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582899 if (is_renderer_initiated)
2900 DCHECK(initiator_origin.has_value());
2901
clamy987a3752018-05-03 17:36:262902 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582903
Rakina Zata Amni2322f4f82022-01-24 13:24:242904 // Don't allow an entry replacement if there is no entry to replace.
2905 // http://crbug.com/457149
2906 if (GetEntryCount() == 0)
2907 should_replace_current_entry = false;
2908
clamy987a3752018-05-03 17:36:262909 // Create a NavigationEntry for the transfer, without making it the pending
2910 // entry. Subframe transfers should have a clone of the last committed entry
2911 // with a FrameNavigationEntry for the target frame. Main frame transfers
2912 // should have a new NavigationEntry.
2913 // TODO(creis): Make this unnecessary by creating (and validating) the params
2914 // directly, passing them to the destination RenderFrameHost. See
2915 // https://crbug.com/536906.
2916 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262917 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262918 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452919 DCHECK(GetLastCommittedEntry());
2920 entry = GetLastCommittedEntry()->Clone();
2921 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172922 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2923 // Renderer-initiated navigation that target a remote frame are currently
2924 // classified as browser-initiated when this one has already navigated.
2925 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372926 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2927 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2928 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2929 // same-document navigation), they will still be present in the
2930 // committed NavigationEntry that will be referenced to construct the new
2931 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262932 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082933 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582934 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372935 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212936 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152937 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262938 } else {
2939 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172940 // If `node` is the outermost main frame, it rewrites a virtual url in order
2941 // to adjust the original input url if needed. For inner frames such as
2942 // fenced frames or subframes, they don't rewrite urls as the urls are not
2943 // input urls by users.
2944 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372945 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322946 if (source_site_instance && source_site_instance->HasProcess()) {
2947 source_process_site_url =
2948 source_site_instance->GetProcess()->GetProcessLock().site_url();
2949 }
clamy987a3752018-05-03 17:36:262950 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212951 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322952 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212953 extra_headers, browser_context_, blob_url_loader_factory,
2954 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262955 entry->root_node()->frame_entry->set_source_site_instance(
2956 static_cast<SiteInstanceImpl*>(source_site_instance));
2957 entry->root_node()->frame_entry->set_method(method);
2958 }
clamy987a3752018-05-03 17:36:262959
Camille Lamy5193caa2018-10-12 11:59:422960 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452961 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262962 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422963 override_user_agent = true;
clamy987a3752018-05-03 17:36:262964 }
2965 // TODO(creis): Set user gesture and intent received timestamp on Android.
2966
2967 // We may not have successfully added the FrameNavigationEntry to |entry|
2968 // above (per https://crbug.com/608402), in which case we create it from
2969 // scratch. This works because we do not depend on |frame_entry| being inside
2970 // |entry| during NavigateToEntry. This will go away when we shortcut this
2971 // further in https://crbug.com/536906.
2972 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2973 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452974 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082975 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582976 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372977 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212978 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152979 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572980 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262981 }
2982
Camille Lamy5193caa2018-10-12 11:59:422983 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022984 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452985 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292986 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212987 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422988 params.source_site_instance = source_site_instance;
2989 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2990 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032991 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422992 params.referrer = referrer;
2993 /* params.redirect_chain: skip */
2994 params.extra_headers = extra_headers;
2995 params.is_renderer_initiated = is_renderer_initiated;
2996 params.override_user_agent = UA_OVERRIDE_INHERIT;
2997 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542998 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422999 /* params.data_url_as_string: skip */
3000 params.post_data = post_body;
3001 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:583002 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:423003 /* params.frame_name: skip */
3004 // TODO(clamy): See if user gesture should be propagated to this function.
3005 params.has_user_gesture = false;
3006 params.should_clear_history_list = false;
3007 params.started_from_context_menu = false;
3008 /* params.navigation_ui_data: skip */
3009 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:223010 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:543011 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:213012 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:413013 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:503014 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:293015 params.initiator_activation_and_ad_status =
3016 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:033017 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:423018
3019 std::unique_ptr<NavigationRequest> request =
3020 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:033021 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143022 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:393023 ReloadType::NONE, entry.get(), frame_entry.get(),
Charlie Reise1d9b8182025-04-02 04:32:123024 actual_navigation_start_time, navigation_start_time,
3025 is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583026 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343027 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:233028
3029 if (!request)
3030 return;
3031
Garrett Tanzerbb8db412022-09-27 21:59:463032 // Force the navigation to take place in a new browsing instance.
3033 // This is used by _unfencedTop in fenced frames to ensure that navigations
3034 // leaving the fenced context create a new browsing instance.
3035 if (force_new_browsing_instance) {
3036 request->coop_status().ForceBrowsingInstanceSwap();
3037 }
3038
Arthur Hemery948742762019-09-18 10:06:243039 // At this stage we are proceeding with this navigation. If this was renderer
3040 // initiated with user gesture, we need to make sure we clear up potential
3041 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
3042 DiscardNonCommittedEntries();
3043
Lukasz Anforowicz9ee83c272020-12-01 20:14:053044 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:263045}
3046
[email protected]d1198fd2012-08-13 22:50:193047void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253048 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:213049 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:193050 if (!session_storage_namespace)
3051 return;
3052
3053 // We can't overwrite an existing SessionStorage without violating spec.
3054 // Attempts to do so may give a tab access to another tab's session storage
3055 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:153056 bool successful_insert =
3057 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:253058 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:053059 static_cast<SessionStorageNamespaceImpl*>(
3060 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:303061 .second;
3062 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:193063}
3064
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573065bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:453066 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:033067 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:463068}
3069
Aran Gilman37d11632019-10-08 23:07:153070SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253071 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:303072 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:253073 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:033074 DOMStorageContextWrapper* context_wrapper =
3075 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
3076
3077 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:253078 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:033079 if (it != session_storage_namespace_map_.end()) {
3080 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:153081 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
3082 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:473083
michaelnbacbcbd2016-02-09 00:32:033084 return it->second.get();
3085 }
3086
3087 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:103088 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
3089 SessionStorageNamespaceImpl::Create(context_wrapper);
3090 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
3091 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:253092 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:103093 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:303094
Daniel Murphy31bbb8b12018-02-07 21:44:103095 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:303096}
3097
3098SessionStorageNamespace*
3099NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:253100 return GetSessionStorageNamespace(
3101 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:303102}
3103
3104const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573105NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303106 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553107}
[email protected]d202a7c2012-01-04 07:53:473108
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573109bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563110 return needs_reload_;
3111}
[email protected]a26023822011-12-29 00:23:553112
[email protected]46bb5e9c2013-10-03 22:16:473113void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413114 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3115}
3116
3117void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473118 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413119 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543120
3121 if (last_committed_entry_index_ != -1) {
3122 entries_[last_committed_entry_index_]->SetTransitionType(
3123 ui::PAGE_TRANSITION_RELOAD);
3124 }
[email protected]46bb5e9c2013-10-03 22:16:473125}
3126
[email protected]d202a7c2012-01-04 07:53:473127void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573128 DCHECK_LT(index, GetEntryCount());
3129 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313130 DiscardNonCommittedEntries();
3131
Nate Chapin9eb16be72022-09-23 22:54:313132 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313133 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123134 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313135 last_committed_entry_index_--;
3136}
3137
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573138NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273139 // If there is no pending_entry_, there should be no pending_entry_index_.
3140 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3141
3142 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363143 // at that index. An exception is while a reload of a post commit error page
3144 // is ongoing; in that case pending entry will point to the entry replaced
3145 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273146 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363147 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3148 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273149
[email protected]022af742011-12-28 18:37:253150 return pending_entry_;
3151}
3152
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573153int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273154 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273155 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553156 return pending_entry_index_;
3157}
3158
avi25764702015-06-23 15:43:373159void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573160 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363161 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313162 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003163 bool in_fenced_frame_tree,
3164 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313165 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3166 // set because:
3167 // 1) They don't influence the history of the outer page.
3168 // 2) They are always replace only navigation (there is always only one entry
3169 // in their history stack).
3170 // 3) Are not top level navigations and appear similar to iframes.
3171 // Navigations of the fenced frame might create a new NavigationEntry, which
3172 // will call this function. Non fenced frame navigations will never have
3173 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3174 // InsertOrReplaceEntry.
3175 DCHECK_EQ(in_fenced_frame_tree,
3176 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3177 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203178
avi5cad4912015-06-19 05:25:443179 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3180 // need to keep continuity with the pending entry, so copy the pending entry's
3181 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3182 // then the renderer navigated on its own, independent of the pending entry,
3183 // so don't copy anything.
3184 if (pending_entry_ && pending_entry_index_ == -1)
3185 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203186
Rakina Zata Amnia4e27222021-12-22 01:05:003187 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203188
creisee17e932015-07-17 17:56:223189 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453190 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103191 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573192 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363193 // If the new entry is a post-commit error page, we store the current last
3194 // committed entry to the side so that we can put it back when navigating
3195 // away from the error.
3196 if (was_post_commit_error) {
3197 DCHECK(!entry_replaced_by_post_commit_error_);
3198 entry_replaced_by_post_commit_error_ =
3199 std::move(entries_[last_committed_entry_index_]);
3200 }
dcheng36b6aec92015-12-26 06:16:363201 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223202 return;
3203 }
[email protected]765b35502008-08-21 00:51:203204
creis37979a62015-08-04 19:48:183205 // We shouldn't see replace == true when there's no committed entries.
3206 DCHECK(!replace);
3207
Michael Thiessen9b14d512019-09-23 21:19:473208 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203209
Shivani Sharmad8c8d652019-02-13 17:27:573210 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203211
dcheng36b6aec92015-12-26 06:16:363212 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203213 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293214}
3215
Shivani Sharmad8c8d652019-02-13 17:27:573216void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163217 if (entries_.size() < max_entry_count())
3218 return;
3219
3220 DCHECK_EQ(max_entry_count(), entries_.size());
3221 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573222 CHECK_EQ(pending_entry_index_, -1);
3223
3224 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423225 // Retrieve the oldest skippable entry.
3226 for (; index < GetEntryCount(); index++) {
3227 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3228 break;
Shivani Sharmad8c8d652019-02-13 17:27:573229 }
3230
3231 // If there is no skippable entry or if it is the last committed entry then
3232 // fall back to pruning the oldest entry. It is not safe to prune the last
3233 // committed entry.
3234 if (index == GetEntryCount() || index == last_committed_entry_index_)
3235 index = 0;
3236
3237 bool should_succeed = RemoveEntryAtIndex(index);
3238 DCHECK_EQ(true, should_succeed);
3239
3240 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253241}
3242
William Liu62ae26c2024-08-08 14:28:163243std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273244NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163245 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203246 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373247 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133248 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493249 const std::string* navigation_api_key,
3250 base::TimeTicks actual_navigation_start) {
Alexander Timin3a92df72019-09-20 11:59:503251 TRACE_EVENT0("navigation",
3252 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273253 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023254 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363255 if (pending_entry_index_ != -1) {
3256 // The pending entry may not be in entries_ if a post-commit error page is
3257 // showing.
3258 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3259 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3260 }
Gyuyoung Kim107c2a02021-04-13 01:49:303261 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573262 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013263 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033264 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573265 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133266 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3267 // the same as the top level frame being navigated.
3268 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373269 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133270 }
Arthur Sonzogni620cec62018-12-13 13:08:573271
[email protected]83c2e232011-10-07 21:36:463272 // If we were navigating to a slow-to-commit page, and the user performs
3273 // a session history navigation to the last committed page, RenderViewHost
3274 // will force the throbber to start, but WebKit will essentially ignore the
3275 // navigation, and won't send a message to stop the throbber. To prevent this
3276 // from happening, we drop the navigation here and stop the slow-to-commit
3277 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023278 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083279 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273280 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033281 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123282
[email protected]83c2e232011-10-07 21:36:463283 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163284 return {};
[email protected]83c2e232011-10-07 21:36:463285 }
3286
Arthur Sonzognic686e8f2024-01-11 08:36:373287 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333288 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3289 if (initiator_rfh) {
3290 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543291 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333292 DCHECK(initiator_frame_token);
3293 }
3294
creisce0ef3572017-01-26 17:53:083295 // Compare FrameNavigationEntries to see which frames in the tree need to be
3296 // navigated.
clamy3cb9bea92018-07-10 12:42:023297 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3298 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333299 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3300 initiator_process_id, soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493301 actual_navigation_start, &same_document_loads,
3302 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303303
3304 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573305 // We were unable to match any frames to navigate. This can happen if a
3306 // history navigation targets a subframe that no longer exists
3307 // (https://crbug.com/705550). In this case, we need to update the current
3308 // history entry to the pending one but keep the main document loaded. We
3309 // also need to ensure that observers are informed about the updated
3310 // current history entry (e.g., for greying out back/forward buttons), and
Charlie Reis99b2eba22025-01-31 19:18:573311 // that renderer processes update their history indices. The easiest way
Alex Moshchuk3a4e77a2020-05-29 21:32:573312 // to do all that is to schedule a "redundant" same-document navigation in
3313 // the main frame.
3314 //
3315 // Note that we don't want to remove this history entry, as it might still
3316 // be valid later, since a frame that it's targeting may be recreated.
3317 //
3318 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3319 // need to repeat history navigations until finding the one that works.
3320 // Consider changing this behavior to keep looking for the first valid
3321 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023322 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423323 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573324 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573325 ReloadType::NONE /* reload_type */,
3326 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433327 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493328 initiator_frame_token, initiator_process_id,
3329 actual_navigation_start);
clamy3cb9bea92018-07-10 12:42:023330 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573331 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023332 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163333 return {};
clamy3cb9bea92018-07-10 12:42:023334 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573335 same_document_loads.push_back(std::move(navigation_request));
3336
3337 // Sanity check that we never take this branch for any kinds of reloads,
3338 // as those should've queued a different-document load in the main frame.
3339 DCHECK(!is_forced_reload);
3340 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303341 }
3342
Nate Chapinbf682fa32022-09-26 22:41:203343 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163344 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203345 if (initiator_rfh && initiator_rfh->IsSandboxed(
3346 network::mojom::WebSandboxFlags::kTopNavigation)) {
3347 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3348 initiator_rfh, same_document_loads) &&
3349 DoesSandboxNavigationStayWithinSubtree(
3350 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503351 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163352 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203353 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3354 initiator_rfh,
3355 navigates_inside_tree
3356 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3357 : blink::mojom::WebFeature::
3358 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523359
3360 // If the navigation occurred outside the tree discard it because
3361 // the sandboxed frame didn't have permission to navigate outside
3362 // its tree. If it is possible that the navigation is both inside and
3363 // outside the frame tree and we discard it entirely because we don't
3364 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143365 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203366 // If a |navigation_api_key| was provided, this navigation originated from
3367 // the navigation API. Notify the renderer that the navigation was
3368 // cancelled so the navigation API can fire an error event and reject the
3369 // relevant promise.
3370 if (navigation_api_key) {
3371 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3372 *navigation_api_key,
3373 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3374 }
Dave Tapuska855c1e12019-08-23 20:45:523375 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133376
3377 for (auto& unused_request : same_document_loads) {
3378 unused_request->set_navigation_discard_reason(
3379 NavigationDiscardReason::kNeverStarted);
3380 }
3381 for (auto& unused_request : different_document_loads) {
3382 unused_request->set_navigation_discard_reason(
3383 NavigationDiscardReason::kNeverStarted);
3384 }
William Liu62ae26c2024-08-08 14:28:163385 return {};
Dave Tapuska855c1e12019-08-23 20:45:523386 }
Dave Tapuska8bfd84c2019-03-26 20:47:163387 }
3388
Nate Chapin6c43c022023-02-13 23:32:423389 // If it is possible that this traverse may involve a same-document navigation
3390 // in the initiator and there is a Navigation API key involved, then we may
3391 // need to notify the initiator if it fails. (The early returns above either
3392 // do not involve these cases or already notify the initiator.)
3393 // The event only needs to fire for the initiator, and only if the initiator
3394 // itself is performing a same-document navigation (because the event will not
3395 // fire if it navigates cross-document).
3396 if (navigation_api_key) {
3397 for (auto& item : same_document_loads) {
3398 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3399 item->set_pending_navigation_api_key(*navigation_api_key);
3400 break;
3401 }
3402 }
3403 }
3404
Carlos Caballero539a421c2020-07-06 10:25:573405 // BackForwardCache:
3406 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563407 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573408 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
Charlie Reis3696ab62025-05-28 07:02:303409 // TODO(crbug.com/420275259): Diagnose failures and upgrade to a CHECK.
3410 DCHECK_EQ(reload_type, ReloadType::NONE);
Charlie Reis655c8f02025-05-15 01:16:173411 base::WeakPtr<NavigationRequest> request;
Rakina Zata Amni58681c62024-06-25 06:32:133412
Charlie Reis655c8f02025-05-15 01:16:173413 // Skip a redundant NavigationRequest creation, per
3414 // https://crbug.com/417251428.
3415 if (base::FeatureList::IsEnabled(kSkipExtraBfcacheNavigationRequest)) {
3416 // If the BackForwardCache can handle this request, it must be for a main
3417 // frame, cross-document, non-reload request. This means there is only one
3418 // item in `different_document_loads` and no `same_document_loads`.
3419 CHECK_EQ(different_document_loads.size(), 1u);
3420 CHECK(same_document_loads.empty());
3421 request = different_document_loads.at(0)->GetWeakPtr();
Charlie Reisd3e4fef2025-05-20 02:04:173422
3423 // Ensure that no re-entrant calls or discards of the pending entry occur
3424 // while calling `Navigator::Navigate` for a pending entry.
3425 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3426 weak_factory_.GetSafeRef());
3427
Charlie Reis655c8f02025-05-15 01:16:173428 root->navigator().Navigate(std::move(different_document_loads.at(0)),
3429 ReloadType::NONE);
Charlie Reisd3e4fef2025-05-20 02:04:173430
3431 // `reentrancy_guard` deleted here.
Charlie Reis655c8f02025-05-15 01:16:173432 } else {
3433 // The legacy approach creates a new NavigationRequest for the entry and
3434 // discards any previously created NavigationRequests, even though the new
3435 // request is identical to the sole existing request.
3436 // TODO(crbug.com/417251428): Remove this path once we measure the impact.
3437 auto navigation_request = CreateNavigationRequestFromEntry(
3438 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3439 ReloadType::NONE, false /* is_same_document_history_load */,
3440 false /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:493441 initiator_process_id, actual_navigation_start);
Charlie Reis655c8f02025-05-15 01:16:173442 request = navigation_request->GetWeakPtr();
3443 root->navigator().Navigate(std::move(navigation_request),
3444 ReloadType::NONE);
3445
3446 for (auto& unused_request : same_document_loads) {
3447 unused_request->set_navigation_discard_reason(
3448 NavigationDiscardReason::kNeverStarted);
3449 }
3450 for (auto& unused_request : different_document_loads) {
3451 unused_request->set_navigation_discard_reason(
3452 NavigationDiscardReason::kNeverStarted);
3453 }
Rakina Zata Amni58681c62024-06-25 06:32:133454 }
3455
Charlie Reis655c8f02025-05-15 01:16:173456 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_requests;
William Liu62ae26c2024-08-08 14:28:163457 if (request) {
Charlie Reis655c8f02025-05-15 01:16:173458 bf_cache_requests.push_back(std::move(request));
William Liu62ae26c2024-08-08 14:28:163459 }
Charlie Reis655c8f02025-05-15 01:16:173460 return bf_cache_requests;
Carlos Caballero539a421c2020-07-06 10:25:573461 }
3462
3463 // History navigation might try to reuse a specific BrowsingInstance, already
3464 // used by a page in the cache. To avoid having two different main frames that
3465 // live in the same BrowsingInstance, evict the all pages with this
3466 // BrowsingInstance from the cache.
3467 //
3468 // For example, take the following scenario:
3469 //
3470 // A1 = Some page on a.com
3471 // A2 = Some other page on a.com
3472 // B3 = An uncacheable page on b.com
3473 //
3474 // Then the following navigations occur:
3475 // A1->A2->B3->A1
3476 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3477 // take its place) and A1 will be created in the same BrowsingInstance (and
3478 // SiteInstance), as A2.
3479 //
3480 // If we didn't do anything, both A1 and A2 would remain alive in the same
3481 // BrowsingInstance/SiteInstance, which is unsupported by
3482 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3483 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483484 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3485 pending_entry_->site_instance()
3486 ? pending_entry_->site_instance()->GetId().value()
3487 : -1);
3488 SCOPED_CRASH_KEY_NUMBER(
3489 "rvh_double", "pending_entry_bi",
3490 pending_entry_->site_instance()
3491 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3492 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573493 if (pending_entry_->site_instance()) {
3494 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3495 pending_entry_->site_instance());
3496 }
3497
Rakina Zata Amnid605d462022-06-01 10:17:033498 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3499 pending_entry_ && pending_entry_->IsRestored());
3500 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3501 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3502 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3503 pending_entry_index_);
3504 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3505 last_committed_entry_index_);
3506 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3507 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3508 pending_entry_ && pending_entry_->IsInitialEntry());
3509 SCOPED_CRASH_KEY_BOOL(
3510 "nav_reentrancy", "pending_entry_initial2",
3511 pending_entry_ &&
3512 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3513 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3514 IsInitialNavigation());
3515 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3516 IsInitialBlankNavigation());
3517 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3518 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3519 (int)pending_reload_);
3520
Charlie Reisd3e4fef2025-05-20 02:04:173521 // Ensure that no re-entrant calls or discards of the pending entry occur
3522 // while calling `Navigator::Navigate` for a pending entry.
3523 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3524 weak_factory_.GetSafeRef());
creis4e2ecb72015-06-20 00:46:303525
Rakina Zata Amnid605d462022-06-01 10:17:033526 // If the navigation-reentrancy is caused by calling
3527 // NavigateToExistingPendingEntry twice, this will note the previous call's
3528 // pending entry's ID.
3529 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3530 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3531
Nate Chapin154b14b2023-02-17 18:28:163532 // If there is a main-frame same-document history navigation, we may defer
3533 // the subframe history navigations in order to give JS in the main frame the
3534 // opportunity to cancel the entire traverse via the navigate event. In that
3535 // case, we need to stash the main frame request's navigation token on the
3536 // subframes, so they can look up the main frame request and defer themselves
3537 // until it completes.
3538 if (!same_document_loads.empty() &&
3539 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3540 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3541 // The token will only be returned in cases where deferring the navigation
3542 // is necessary.
3543 if (auto main_frame_same_document_token =
3544 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3545 for (auto& item : same_document_loads) {
3546 if (item.get() != main_frame_request) {
3547 item->set_main_frame_same_document_history_token(
3548 main_frame_same_document_token);
3549 }
3550 }
3551 for (auto& item : different_document_loads) {
3552 item->set_main_frame_same_document_history_token(
3553 main_frame_same_document_token);
3554 }
3555 }
3556 }
3557
William Liu122754942024-01-18 22:34:393558 if (!initiator_rfh) {
3559 // A browser-initiated navigation won't have a `initiator_rfh`.
3560 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3561 different_document_loads, same_document_loads);
3562 }
3563
William Liu62ae26c2024-08-08 14:28:163564 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3565 all_requests.reserve(same_document_loads.size() +
3566 different_document_loads.size());
3567 bool seen_primary_main_frame_request = false;
3568
creis4e2ecb72015-06-20 00:46:303569 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023570 for (auto& item : same_document_loads) {
3571 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273572 // The request could be destroyed before `navigator().Navigate()` returns.
3573 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053574 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163575 if (request) {
3576 // Can only have one primary main frame request.
3577 CHECK(!seen_primary_main_frame_request ||
3578 !request->IsInPrimaryMainFrame());
3579 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3580 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273581 }
creis4e2ecb72015-06-20 00:46:303582 }
clamy3cb9bea92018-07-10 12:42:023583 for (auto& item : different_document_loads) {
3584 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273585 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053586 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163587 if (request) {
3588 // Can only have one primary main frame request.
3589 CHECK(!seen_primary_main_frame_request ||
3590 !request->IsInPrimaryMainFrame());
3591 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3592 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273593 }
creis4e2ecb72015-06-20 00:46:303594 }
clamy3cb9bea92018-07-10 12:42:023595
William Liu62ae26c2024-08-08 14:28:163596 return all_requests;
Charlie Reisd3e4fef2025-05-20 02:04:173597 // `reentrancy_guard` deleted here.
creis4e2ecb72015-06-20 00:46:303598}
3599
Alex Moshchuk3a4e77a2020-05-29 21:32:573600NavigationControllerImpl::HistoryNavigationAction
3601NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303602 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573603 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423604 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583605 // Only active and prerendered documents are allowed to navigate in their
3606 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423607 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013608 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583609 // - If the document is in pending deletion, the browser already committed
3610 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3611 // - If the document is in back-forward cache, it's not allowed to navigate
3612 // as it should remain frozen. Ignore the request and evict the document
3613 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423614 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583615 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423616 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113617 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3618 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423619 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113620 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423621 }
arthursonzogni03f76152019-02-12 10:35:203622
Alex Moshchuk3a4e77a2020-05-29 21:32:573623 // Reloads should result in a different-document load. Note that reloads may
3624 // also happen via the |needs_reload_| mechanism where the reload_type is
3625 // NONE, so detect this by comparing whether we're going to the same
3626 // entry that we're currently on. Similarly to above, only main frames
3627 // should reach this. Note that subframes support reloads, but that's done
3628 // via a different path that doesn't involve FindFramesToNavigate (see
3629 // RenderFrameHost::Reload()).
3630 if (reload_type != ReloadType::NONE ||
3631 pending_entry_index_ == last_committed_entry_index_) {
3632 DCHECK(frame->IsMainFrame());
3633 return HistoryNavigationAction::kDifferentDocument;
3634 }
3635
Alex Moshchuk47d1a4bd2020-06-01 22:15:343636 // If there is no new FrameNavigationEntry for the frame, ignore the
3637 // load. For example, this may happen when going back to an entry before a
3638 // frame was created. Suppose we commit a same-document navigation that also
3639 // results in adding a new subframe somewhere in the tree. If we go back,
3640 // the new subframe will be missing a FrameNavigationEntry in the previous
3641 // NavigationEntry, but we shouldn't delete or change what's loaded in
3642 // it.
3643 //
Alex Moshchuke65c39272020-06-03 17:55:373644 // Note that in this case, there is no need to keep looking for navigations
3645 // in subframes, which would be missing FrameNavigationEntries as well.
3646 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343647 // It's important to check this before checking |old_item| below, since both
3648 // might be null, and in that case we still shouldn't change what's loaded in
3649 // this frame. Note that scheduling any loads assumes that |new_item| is
3650 // non-null. See https://crbug.com/1088354.
3651 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3652 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373653 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343654
Charlie Reisa474fb62022-03-17 02:31:363655 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3656 // which history item it is currently on, since this may be different than the
3657 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3658 // (e.g., if a history navigation is targeting multiple frames and only some
3659 // have committed so far).
creis4e2ecb72015-06-20 00:46:303660 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363661 frame->current_frame_host()->last_committed_frame_entry();
3662 if (!old_item) {
3663 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3664 // fall back to the last committed NavigationEntry's record for this frame.
3665 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583666 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363667 // accurate FrameNavigationEntry and eliminate this case.
3668 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3669 }
3670 // If neither approach finds a FrameNavigationEntry, schedule a
3671 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583672 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573673 if (!old_item)
3674 return HistoryNavigationAction::kDifferentDocument;
3675
Alex Moshchuk3a4e77a2020-05-29 21:32:573676 // If the new item is not in the same SiteInstance, schedule a
3677 // different-document load. Newly restored items may not have a SiteInstance
3678 // yet, in which case it will be assigned on first commit.
3679 if (new_item->site_instance() &&
3680 new_item->site_instance() != old_item->site_instance())
3681 return HistoryNavigationAction::kDifferentDocument;
3682
Charlie Reis71e4ae32025-01-29 21:37:573683 // If the origins of the new and old items are both present but don't match,
3684 // schedule a different document load even if the document sequence numbers
3685 // somehow match.
3686 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3687 // committed origin on `new_item`, and update the Blink DSN computation to
3688 // avoid a cross-origin DSN match when possible.
3689 if (new_item->committed_origin().has_value() &&
3690 old_item->committed_origin().has_value() &&
3691 !new_item->committed_origin()->IsSameOriginWith(
3692 old_item->committed_origin().value())) {
3693 return HistoryNavigationAction::kDifferentDocument;
3694 }
3695
Alex Moshchuk3a4e77a2020-05-29 21:32:573696 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313697 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3698 // that we do this even if the history navigation would not be modifying this
3699 // frame were it live.
3700 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573701 return HistoryNavigationAction::kDifferentDocument;
3702
3703 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313704 // Starting a navigation after a crash early-promotes the speculative
3705 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3706 // committed yet, so we can not possibly perform a same-document history
3707 // navigation. The frame would need to be reloaded with a cross-document
3708 // navigation.
3709 if (!frame->current_frame_host()->has_committed_any_navigation())
3710 return HistoryNavigationAction::kDifferentDocument;
3711
creis54131692016-08-12 18:32:253712 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493713 // sequence number but different item sequence number.
3714 if (new_item->document_sequence_number() ==
3715 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573716 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493717 }
avib48cb312016-05-05 21:35:003718
Alex Moshchuk3a4e77a2020-05-29 21:32:573719 // Otherwise, if both item and document sequence numbers differ, this
3720 // should be a different document load.
3721 return HistoryNavigationAction::kDifferentDocument;
3722 }
3723
3724 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373725 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573726 DCHECK_EQ(new_item->document_sequence_number(),
3727 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373728 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573729}
3730
3731void NavigationControllerImpl::FindFramesToNavigate(
3732 FrameTreeNode* frame,
3733 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373734 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333735 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373736 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133737 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493738 base::TimeTicks actual_navigation_start,
Alex Moshchuk3a4e77a2020-05-29 21:32:573739 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3740 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3741 DCHECK(pending_entry_);
3742 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3743
3744 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3745
3746 if (action == HistoryNavigationAction::kSameDocument) {
3747 std::unique_ptr<NavigationRequest> navigation_request =
3748 CreateNavigationRequestFromEntry(
3749 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133750 /*is_same_document_history_load=*/true,
3751 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333752 initiator_frame_token, initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:493753 actual_navigation_start, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573754 if (navigation_request) {
3755 // Only add the request if was properly created. It's possible for the
3756 // creation to fail in certain cases, e.g. when the URL is invalid.
3757 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303758 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573759 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473760 std::unique_ptr<NavigationRequest> navigation_request =
3761 CreateNavigationRequestFromEntry(
3762 frame, pending_entry_, new_item, reload_type,
3763 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433764 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493765 initiator_frame_token, initiator_process_id,
3766 actual_navigation_start);
Lei Zhang96031532019-10-10 19:05:473767 if (navigation_request) {
3768 // Only add the request if was properly created. It's possible for the
3769 // creation to fail in certain cases, e.g. when the URL is invalid.
3770 different_document_loads->push_back(std::move(navigation_request));
3771 }
3772 // For a different document, the subframes will be destroyed, so there's
3773 // no need to consider them.
3774 return;
Alex Moshchuke65c39272020-06-03 17:55:373775 } else if (action == HistoryNavigationAction::kStopLooking) {
3776 return;
creis4e2ecb72015-06-20 00:46:303777 }
3778
Yoav Weiss8c573952022-11-17 17:35:133779 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3780 // we currently only support soft navigation heuristics for the top level
3781 // frame.
creis4e2ecb72015-06-20 00:46:303782 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333783 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3784 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373785 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:493786 actual_navigation_start, same_document_loads,
3787 different_document_loads);
creis4e2ecb72015-06-20 00:46:303788 }
3789}
3790
Harkiran Bolariaba823e42021-05-21 18:30:363791base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
Charlie Reisf4d51f402025-05-23 18:00:493792 const LoadURLParams& params,
3793 base::TimeTicks actual_navigation_start) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553794 FrameTreeNode* node = GetTargetFrameTreeNodeForNavigation(params);
clamy21718cc22018-06-13 13:34:243795
Camille Lamy5193caa2018-10-12 11:59:423796 // Compute overrides to the LoadURLParams for |override_user_agent|,
3797 // |should_replace_current_entry| and |has_user_gesture| that will be used
3798 // both in the creation of the NavigationEntry and the NavigationRequest.
3799 // Ideally, the LoadURLParams themselves would be updated, but since they are
3800 // passed as a const reference, this is not possible.
3801 // TODO(clamy): When we only create a NavigationRequest, move this to
3802 // CreateNavigationRequestFromLoadURLParams.
3803 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3804 GetLastCommittedEntry());
3805
Rakina Zata Amnie2d31312022-11-18 03:38:453806 // An entry replacement must happen if the current browsing context should
3807 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333808 bool should_replace_current_entry =
3809 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453810 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423811
clamy21718cc22018-06-13 13:34:243812 // Javascript URLs should not create NavigationEntries. All other navigations
3813 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243814 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373815 std::unique_ptr<NavigationEntryImpl> entry =
3816 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3817 should_replace_current_entry,
3818 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243819 DiscardPendingEntry(false);
3820 SetPendingEntry(std::move(entry));
3821 }
3822
Tim Judkins59548192023-05-17 17:51:203823 // Renderer-debug URLs are sent to the current renderer process immediately
3824 // for processing and don't need to create a NavigationRequest. Note: this
3825 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243826 // renderer-debug URLs.
3827 // Note: we intentionally leave the pending entry in place for renderer debug
3828 // URLs, unlike the cases below where we clear it if the navigation doesn't
3829 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303830 if (blink::IsRendererDebugURL(params.url)) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553831 // Renderer-debug URLs won't go through NavigationThrottles so we have to
3832 // check them explicitly. See crbug.com/40605746.
Aaron Colwelle1908d982020-06-26 22:08:153833 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203834 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483835 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363836 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483837 }
3838
clamy21718cc22018-06-13 13:34:243839 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363840 return nullptr;
clamy21718cc22018-06-13 13:34:243841 }
3842
Antonio Sartori78a749f2020-11-30 12:03:393843 DCHECK(pending_entry_);
3844
clamy21718cc22018-06-13 13:34:243845 // Convert navigations to the current URL to a reload.
3846 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3847 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3848 // DevTools sometimes issues navigations to main frames that they do not
3849 // expect to see treated as reload, and it only works because they pass a
3850 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3851 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543852 ReloadType reload_type = params.reload_type;
3853 if (reload_type == ReloadType::NONE &&
3854 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043855 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243856 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243857 params.load_type ==
3858 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543859 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243860 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473861 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393862
3863 // If this is a reload of an existing FrameNavigationEntry and we had a
3864 // policy container for it, then we should copy it into the pending entry,
3865 // so that it is copied to the navigation request in
3866 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453867 FrameNavigationEntry* previous_frame_entry =
3868 GetLastCommittedEntry()->GetFrameEntry(node);
3869 if (previous_frame_entry &&
3870 previous_frame_entry->policy_container_policies()) {
3871 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3872 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393873 }
3874 }
3875
3876 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173877 // document, then we should copy the document polices from RenderFrameHost's
3878 // PolicyContainerHost. The NavigationRequest will create a new
3879 // PolicyContainerHost with the document policies from the |pending_entry_|,
3880 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3881 // the navigation. This way, we ensure that we keep enforcing the right
3882 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453883 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393884 if (node->current_frame_host() &&
3885 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193886 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163887 node->current_frame_host()
3888 ->policy_container_host()
3889 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233890 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393891 }
clamy21718cc22018-06-13 13:34:243892 }
3893
3894 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263895 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243896
Tsuyoshi Horo167ca6432022-03-09 05:16:393897 // This will be used to set the Navigation Timing API navigationStart
3898 // parameter for browser navigations in new tabs (intents, tabs opened through
3899 // "Open link in new tab"). If the navigation must wait on the current
3900 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3901 // will be updated when the BeforeUnload ack is received.
3902 const auto navigation_start_time = base::TimeTicks::Now();
Tsuyoshi Horo167ca6432022-03-09 05:16:393903
Camille Lamy5193caa2018-10-12 11:59:423904 std::unique_ptr<NavigationRequest> request =
3905 CreateNavigationRequestFromLoadParams(
3906 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143907 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393908 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
Charlie Reisf4d51f402025-05-23 18:00:493909 actual_navigation_start, navigation_start_time);
clamy21718cc22018-06-13 13:34:243910
3911 // If the navigation couldn't start, return immediately and discard the
3912 // pending NavigationEntry.
3913 if (!request) {
3914 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363915 return nullptr;
clamy21718cc22018-06-13 13:34:243916 }
3917
Camille Lamy5193caa2018-10-12 11:59:423918#if DCHECK_IS_ON()
3919 // Safety check that NavigationRequest and NavigationEntry match.
3920 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3921#endif
3922
Charlie Reisd3e4fef2025-05-20 02:04:173923 // Ensure that no re-entrant calls or discards of the pending entry occur
3924 // while calling `Navigator::Navigate` for a pending entry.
3925 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3926 weak_factory_.GetSafeRef());
arthursonzogni66f711c2019-10-08 14:40:363927
Harkiran Bolariaba823e42021-05-21 18:30:363928 base::WeakPtr<NavigationHandle> created_navigation_handle(
3929 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053930 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243931
Harkiran Bolariaba823e42021-05-21 18:30:363932 return created_navigation_handle;
Charlie Reisd3e4fef2025-05-20 02:04:173933 // `reentrancy_guard` deleted here.
clamy21718cc22018-06-13 13:34:243934}
3935
Emmanuel Arias Soto9e159652025-05-16 07:53:553936FrameTreeNode* NavigationControllerImpl::GetTargetFrameTreeNodeForNavigation(
3937 const LoadURLParams& params) {
3938 FrameTreeNode* node = nullptr;
3939 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3940 node = params.frame_tree_node_id
3941 ? frame_tree_->FindByID(params.frame_tree_node_id)
3942 : frame_tree_->FindByName(params.frame_name);
3943 DCHECK(!node || &node->frame_tree() == &frame_tree());
3944 if (!node && params.frame_tree_node_id) {
3945 // If the specified FrameTreeNode exists in another FrameTree, the caller
3946 // is using the wrong NavigationController.
3947 CHECK(!FrameTreeNode::GloballyFindByID(params.frame_tree_node_id),
3948 base::NotFatalUntil::M140);
3949 }
3950 }
3951
3952 // If no FrameTreeNode was specified, navigate the main frame.
3953 if (!node) {
3954 node = frame_tree_->root();
3955 }
3956 return node;
3957}
3958
clamyea99ea12018-05-28 13:54:233959void NavigationControllerImpl::HandleRendererDebugURL(
3960 FrameTreeNode* frame_tree_node,
3961 const GURL& url) {
3962 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243963 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3964 // the renderer process is not live, unless it is the initial navigation
3965 // of the tab.
clamyea99ea12018-05-28 13:54:233966 if (!IsInitialNavigation()) {
3967 DiscardNonCommittedEntries();
3968 return;
3969 }
Fergal Dalyecd3b0202020-06-25 01:57:373970 // The current frame is always a main frame. If IsInitialNavigation() is
3971 // true then there have been no navigations and any frames of this tab must
3972 // be in the same renderer process. If that has crashed then the only frame
3973 // that can be revived is the main frame.
3974 frame_tree_node->render_manager()
3975 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233976 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223977
3978 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3979 // notification, so set is loading to true here to properly surface it when
3980 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313981 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223982 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223983 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223984 }
clamyea99ea12018-05-28 13:54:233985 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3986}
3987
clamy21718cc22018-06-13 13:34:243988std::unique_ptr<NavigationEntryImpl>
3989NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3990 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423991 const LoadURLParams& params,
3992 bool override_user_agent,
3993 bool should_replace_current_entry,
3994 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393995 // Browser initiated navigations might not have a blob_url_loader_factory set
3996 // in params even if the navigation is to a blob URL. If that happens, lookup
3997 // the correct url loader factory to use here.
3998 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483999 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:474000 // Resolve the blob URL in the storage partition associated with the target
4001 // frame. This is the storage partition the URL will be loaded in, and only
4002 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:394003 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:474004 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:394005 }
4006
clamy21718cc22018-06-13 13:34:244007 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:444008 // extra_headers in params are \n separated; navigation entries want \r\n.
4009 std::string extra_headers_crlf;
4010 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:244011
4012 // For subframes, create a pending entry with a corresponding frame entry.
4013 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:454014 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:244015 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:084016 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:244017 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:374018 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:214019 params.initiator_base_url, params.redirect_chain, blink::PageState(),
4020 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:394021 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:164022 // a conversion of a new navigation into a reload, we will set the right
4023 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:194024 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:244025 } else {
4026 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:174027 // If `node` is the outermost main frame, it rewrites a virtual url in order
4028 // to adjust the original input url if needed. For inner frames such as
4029 // fenced frames or subframes, they don't rewrite urls as the urls are not
4030 // input urls by users.
4031 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:324032 scoped_refptr<SiteInstance> source_site_instance =
4033 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:374034 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:324035 if (source_site_instance && source_site_instance->HasProcess()) {
4036 source_process_site_url =
4037 source_site_instance->GetProcess()->GetProcessLock().site_url();
4038 }
clamy21718cc22018-06-13 13:34:244039 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:064040 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:324041 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:214042 params.transition_type, params.is_renderer_initiated,
4043 extra_headers_crlf, browser_context_, blob_url_loader_factory,
4044 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:244045 entry->set_source_site_instance(
4046 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
4047 entry->SetRedirectChain(params.redirect_chain);
4048 }
4049
4050 // Set the FTN ID (only used in non-site-per-process, for tests).
4051 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:244052 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:424053 entry->SetIsOverridingUserAgent(override_user_agent);
4054 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:544055 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:244056
clamy21718cc22018-06-13 13:34:244057 switch (params.load_type) {
4058 case LOAD_TYPE_DEFAULT:
4059 break;
4060 case LOAD_TYPE_HTTP_POST:
4061 entry->SetHasPostData(true);
4062 entry->SetPostData(params.post_data);
4063 break;
4064 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:544065 // LoadDataWithBaseURL is a special case that needs to assign both a base
4066 // URL and a virtual URL, while loading the actual content from a data
4067 // URL.
clamy21718cc22018-06-13 13:34:244068 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:544069 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:284070#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:244071 entry->SetDataURLAsString(params.data_url_as_string);
4072#endif
4073 entry->SetCanLoadLocalResources(params.can_load_local_resources);
4074 break;
Shu Yang112ad492024-07-25 17:11:544075#if BUILDFLAG(IS_ANDROID)
4076 case LOAD_TYPE_PDF_ANDROID:
4077 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
4078 // internal URL is used for the navigation URL.
4079 entry->SetVirtualURL(params.virtual_url_for_special_cases);
4080 break;
4081#endif
clamy21718cc22018-06-13 13:34:244082 }
4083
4084 // TODO(clamy): NavigationEntry is meant for information that will be kept
4085 // after the navigation ended and therefore is not appropriate for
4086 // started_from_context_menu. Move started_from_context_menu to
4087 // NavigationUIData.
4088 entry->set_started_from_context_menu(params.started_from_context_menu);
4089
4090 return entry;
4091}
4092
clamyea99ea12018-05-28 13:54:234093std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:424094NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
4095 FrameTreeNode* node,
4096 const LoadURLParams& params,
4097 bool override_user_agent,
4098 bool should_replace_current_entry,
4099 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:144100 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:424101 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574102 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:394103 FrameNavigationEntry* frame_entry,
Charlie Reise1d9b8182025-04-02 04:32:124104 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:224105 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:494106 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:454107 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584108 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:344109 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:374110 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574111 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:524112
4113 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
4114 // subframes have FrameNavigationEntries associated with them. Until then,
4115 // there may be cases where a subframe navigation is missing `frame_entry`
4116 // (e.g., see https://crbug.com/358084015).
4117
Nasko Oskov3c2f9e252019-01-10 17:45:534118 // All renderer-initiated navigations must have an initiator_origin.
4119 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:514120
Camille Lamy5193caa2018-10-12 11:59:424121 GURL url_to_load;
4122 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:324123
Camille Lamy2baa8022018-10-19 16:43:174124 // For main frames, rewrite the URL if necessary and compute the virtual URL
4125 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:264126 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424127 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:174128 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424129 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:424130
Shu Yang112ad492024-07-25 17:11:544131 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
4132 // that need to define a virtual URL to display, which differs from the
4133 // navigation URL.
4134 if (params.load_type == LOAD_TYPE_DATA) {
4135 virtual_url = params.virtual_url_for_special_cases;
4136 }
4137#if BUILDFLAG(IS_ANDROID)
4138 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
4139 virtual_url = params.virtual_url_for_special_cases;
4140 }
4141#endif
Camille Lamy5193caa2018-10-12 11:59:424142
Camille Lamy2baa8022018-10-19 16:43:174143 if (virtual_url.is_empty())
4144 virtual_url = url_to_load;
4145
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574146 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:284147
Aran Gilman249eb122019-12-02 23:32:464148 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
4149 // behavior: it is possible for two calls to RewriteUrlForNavigation to
4150 // return different results, leading to a different URL in the
4151 // NavigationRequest and FrameEntry. This will be fixed once we remove the
4152 // pending NavigationEntry, as we'll only make one call to
4153 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:524154 if (frame_entry) {
4155 VLOG_IF(1, (url_to_load != frame_entry->url()))
4156 << "NavigationRequest and FrameEntry have different URLs: "
4157 << url_to_load << " vs " << frame_entry->url();
4158 }
Camille Lamyb9ed3c52018-11-19 15:34:284159
Camille Lamy2baa8022018-10-19 16:43:174160 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424161 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174162 // NavigationRequest.
4163 } else {
4164 url_to_load = params.url;
4165 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244166 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174167 }
Camille Lamy5193caa2018-10-12 11:59:424168
Ehsan Karamad44fc72112019-02-26 18:15:474169 if (node->render_manager()->is_attaching_inner_delegate()) {
4170 // Avoid starting any new navigations since this node is now preparing for
4171 // attaching an inner delegate.
4172 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204173 }
Camille Lamy5193caa2018-10-12 11:59:424174
Alex Moshchuk99242832023-05-22 17:21:444175 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424176 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444177 }
Camille Lamy5193caa2018-10-12 11:59:424178
danakjd83d706d2020-11-25 22:11:124179 // Look for a pending commit that is to another document in this
4180 // FrameTreeNode. If one exists, then the last committed URL will not be the
4181 // current URL by the time this navigation commits.
4182 bool has_pending_cross_document_commit =
4183 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214184 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124185
Minggang Wangb9f3fa92021-07-01 15:30:314186 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494187 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524188 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494189 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134190 /*is_same_document_history_load=*/false,
4191 is_embedder_initiated_fenced_frame_navigation,
4192 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424193
4194 // Create the NavigationParams based on |params|.
4195
Hiroki Nakagawa4ed61282021-06-18 05:37:234196 bool is_view_source_mode = entry->IsViewSourceMode();
4197 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294198
Antonio Sartori6984c742021-08-26 08:03:414199 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294200
Hiroki Nakagawa4ed61282021-06-18 05:37:234201 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294202 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254203 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294204
Charlie Reisf21cd182024-08-09 21:44:524205 std::string page_state_data =
4206 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4207
Minggang Wangb9f3fa92021-07-01 15:30:314208 blink::mojom::CommonNavigationParamsPtr common_params =
4209 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214210 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514211 blink::mojom::Referrer::New(params.referrer.url,
4212 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214213 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514214 should_replace_current_entry, params.base_url_for_data_url,
Charlie Reise1d9b8182025-04-02 04:32:124215 actual_navigation_start_time, navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514216 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144217 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414218 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274219 false /* has_text_fragment_token */,
4220 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4221 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514222 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054223 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424224
Minggang Wangb9f3fa92021-07-01 15:30:314225 blink::mojom::CommitNavigationParamsPtr commit_params =
4226 blink::mojom::CommitNavigationParams::New(
Diana Quae845bf2025-04-03 20:12:374227 url::Origin(),
Ari Chivukulac7533522024-05-14 21:52:344228 // The correct storage key will be computed before committing the
4229 // navigation.
4230 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324231 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504232 std::vector<net::RedirectInfo>(), params.post_content_type,
4233 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524234 params.can_load_local_resources, page_state_data,
4235 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134236 /*intended_as_new_entry=*/true,
Charlie Reis99b2eba22025-01-31 19:18:574237 /*pending_history_list_index=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144238 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4239 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134240 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314241 params.should_clear_history_list,
4242 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224243 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134244 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514245 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284246#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134247 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144248#endif
Yoav Weiss8c573952022-11-17 17:35:134249 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154250 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134251 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074252 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134253 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4254 /*origin_agent_cluster=*/false,
4255 /*origin_agent_cluster_left_as_default=*/true,
4256 /*enabled_client_hints=*/
4257 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264258 /*is_cross_site_cross_browsing_context_group=*/false,
4259 /*should_have_sticky_user_activation=*/false,
4260 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134261 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014262 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134263 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584264 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134265 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134266 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284267 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134268 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444269 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424270 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374271 /*view_transition_state=*/std::nullopt,
4272 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054273 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464274 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374275 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054276 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094277 /*load_with_storage_access=*/
4278 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374279 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374280 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484281 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314282 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164283 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174284 node->current_frame_host()->GetCachedPermissionStatuses(),
Charlie Reiscdb798342025-02-14 22:04:464285 /*should_skip_screentshot=*/false,
Alex Moshchukd0d759c22025-05-09 18:18:354286 /*force_new_document_sequence_number=*/false,
4287 /*navigation_metrics_token=*/base::UnguessableToken::Create());
Xiaohan Wang7f8052e02022-01-14 18:44:284288#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424289 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564290 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424291 }
4292#endif
4293
Lucas Furukawa Gadania9c45682019-07-31 22:05:144294 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074295 commit_params->navigation_timing->system_entropy_at_navigation_start =
4296 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4297 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424298
Camille Lamy5193caa2018-10-12 11:59:424299 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4300 std::string extra_headers_crlf;
4301 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094302
Alex Moshchuk9321e6a2022-12-07 21:58:314303 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144304 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084305 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094306 params.initiator_frame_token, params.initiator_process_id,
4307 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214308 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294309 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454310 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344311 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034312 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134313
4314 if (!navigation_request) {
4315 return nullptr;
4316 }
4317
Yao Xiaodc5ed102019-06-04 19:19:094318 navigation_request->set_from_download_cross_origin_redirect(
4319 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554320 navigation_request->set_force_new_browsing_instance(
4321 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514322 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434323 if (params.force_no_https_upgrade) {
4324 navigation_request->set_force_no_https_upgrade();
4325 }
Yao Xiaodc5ed102019-06-04 19:19:094326 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424327}
4328
4329std::unique_ptr<NavigationRequest>
4330NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234331 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574332 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234333 FrameNavigationEntry* frame_entry,
4334 ReloadType reload_type,
4335 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434336 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374337 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334338 int initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:494339 base::TimeTicks actual_navigation_start,
Arthur Sonzognic686e8f2024-01-11 08:36:374340 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134341 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344342 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234343 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434344 // We should never navigate to an existing initial NavigationEntry that is the
4345 // initial NavigationEntry for the initial empty document that hasn't been
4346 // overridden by the synchronous about:blank commit, to preserve previous
4347 // behavior where trying to reload when the main frame is on the initial empty
4348 // document won't result in a navigation.
4349 // See also https://crbug.com/1277414.
4350 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324351
clamyea99ea12018-05-28 13:54:234352 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234353
Ehsan Karamad44fc72112019-02-26 18:15:474354 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4355 // Avoid starting any new navigations since this node is now preparing for
4356 // attaching an inner delegate.
4357 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204358 }
4359
Alex Moshchuk99242832023-05-22 17:21:444360 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4361 dest_url)) {
clamyea99ea12018-05-28 13:54:234362 return nullptr;
4363 }
4364
clamyea99ea12018-05-28 13:54:234365 // This will be used to set the Navigation Timing API navigationStart
4366 // parameter for browser navigations in new tabs (intents, tabs opened through
4367 // "Open link in new tab"). If the navigation must wait on the current
4368 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4369 // will be updated when the BeforeUnload ack is received.
clamyea99ea12018-05-28 13:54:234370 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074371 const auto navigation_start_system_entropy =
4372 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4373 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234374
danakjd83d706d2020-11-25 22:11:124375 // Look for a pending commit that is to another document in this
4376 // FrameTreeNode. If one exists, then the last committed URL will not be the
4377 // current URL by the time this navigation commits.
4378 bool has_pending_cross_document_commit =
4379 frame_tree_node->render_manager()
4380 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494381 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214382 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124383
Minggang Wangb9f3fa92021-07-01 15:30:314384 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124385 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524386 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494387 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494388 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134389 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494390 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424391
4392 // A form submission may happen here if the navigation is a
4393 // back/forward/reload navigation that does a form resubmission.
4394 scoped_refptr<network::ResourceRequestBody> request_body;
4395 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394396 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504397 // entry. This way, it could be directly retrieved here. Right now, it is only
4398 // partially recovered when request.method == "POST" and request.body exists.
4399 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424400 if (frame_entry->method() == "POST") {
4401 request_body = frame_entry->GetPostData(&post_content_type);
4402 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304403 post_content_type = std::string(
4404 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504405 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424406 }
4407
4408 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314409 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514410 entry->ConstructCommonNavigationParams(
4411 *frame_entry, request_body, dest_url,
4412 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Charlie Reisf4d51f402025-05-23 18:00:494413 navigation_type, actual_navigation_start, navigation_start,
Charlie Reise1d9b8182025-04-02 04:32:124414 /*input_start=*/base::TimeTicks());
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514415 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554416 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424417
4418 // TODO(clamy): |intended_as_new_entry| below should always be false once
4419 // Reload no longer leads to this being called for a pending NavigationEntry
4420 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314421 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144422 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404423 *frame_entry, common_params->url, common_params->method,
4424 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144425 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534426 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484427 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134428 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074429 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144430 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074431 commit_params->navigation_timing->system_entropy_at_navigation_start =
4432 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4433 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164434 commit_params->initial_permission_statuses =
4435 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424436
W. James MacLeanb7d6092682022-10-05 15:23:264437 if (common_params->url.IsAboutSrcdoc()) {
4438 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4439 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594440 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264441 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334442 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314443 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144444 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434445 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334446 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4447 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374448 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294449 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4450 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474451 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234452}
4453
[email protected]d202a7c2012-01-04 07:53:474454void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214455 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274456 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404457
Takashi Toyoshimaea534ef22021-07-21 03:27:594458 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404459 // location bar will have up-to-date information about the security style
4460 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134461 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404462
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374463 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574464 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294465}
4466
initial.commit09911bf2008-07-26 23:55:294467// static
[email protected]d202a7c2012-01-04 07:53:474468size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234469 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154470 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214471 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234472}
4473
[email protected]d202a7c2012-01-04 07:53:474474void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224475 if (is_active && needs_reload_)
4476 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214477
4478 if (frame_tree_->is_primary();
4479 auto* cache = GetNavigationEntryScreenshotCache()) {
4480 cache->SetVisible(is_active);
4481 }
initial.commit09911bf2008-07-26 23:55:294482}
4483
[email protected]d202a7c2012-01-04 07:53:474484void NavigationControllerImpl::LoadIfNecessary() {
Charlie Reisf4d51f402025-05-23 18:00:494485 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:034486 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4487 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294488 if (!needs_reload_)
4489 return;
4490
Bo Liucdfa4b12018-11-06 00:21:444491 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4492 needs_reload_type_);
4493
initial.commit09911bf2008-07-26 23:55:294494 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004495 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294496 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004497 if (entry_replaced_by_post_commit_error_) {
4498 // If the current entry is a post commit error, we reload the entry it
4499 // replaced instead. We leave the error entry in place until a commit
4500 // replaces it, but the pending entry points to the original entry in the
4501 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4502 // case that pending_entry_ != entries_[pending_entry_index_].
4503 // Note that this handling is similar to
4504 // `NavigationControllerImpl::Reload()`.
4505 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4506 pending_entry_index_ = GetCurrentEntryIndex();
4507 NavigateToExistingPendingEntry(
4508 ReloadType::NONE,
4509 /*initiator_rfh=*/nullptr,
4510 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494511 /*navigation_api_key=*/nullptr, actual_navigation_start);
Xinghui Lue4e50be2024-05-15 21:46:004512 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134513 NavigateToExistingPendingEntry(
4514 ReloadType::NONE,
4515 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374516 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494517 /*navigation_api_key=*/nullptr, actual_navigation_start);
Rakina Zata Amnie2d31312022-11-18 03:38:454518 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434519 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274520 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344521 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134522 NavigateToExistingPendingEntry(
4523 ReloadType::NONE,
4524 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374525 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494526 /*navigation_api_key=*/nullptr, actual_navigation_start);
avicc872d7242015-08-19 21:26:344527 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434528 // We should never navigate to an existing initial NavigationEntry that is
4529 // the initial NavigationEntry for the initial empty document that hasn't
4530 // been overridden by the synchronous about:blank commit, to preserve
4531 // legacy behavior where trying to reload when the main frame is on the
4532 // initial empty document won't result in a navigation. See also
4533 // https://crbug.com/1277414. If there is something to reload, the
4534 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4535 // it here.
avicc872d7242015-08-19 21:26:344536 needs_reload_ = false;
4537 }
initial.commit09911bf2008-07-26 23:55:294538}
4539
Kevin McNeeccca6172021-10-19 17:11:144540base::WeakPtr<NavigationHandle>
4541NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364542 RenderFrameHost* render_frame_host,
4543 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364544 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134545 RenderFrameHostImpl* rfhi =
4546 static_cast<RenderFrameHostImpl*>(render_frame_host);
Andrew Verge754c70a2025-04-17 17:19:194547 std::unique_ptr<NavigationRequest> navigation_request =
4548 CreateNavigationRequestForErrorPage(rfhi, url, error_page_html,
4549 /*is_post_commit_error_page=*/true);
4550 if (!navigation_request) {
Kevin McNeeccca6172021-10-19 17:11:144551 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114552 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584553
Rakina Zata Amni919b7922020-12-11 09:03:134554 FrameTreeNode* node = rfhi->frame_tree_node();
Charlie Reis09952ee2022-12-08 16:35:074555 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414556 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144557
Andrew Verge754c70a2025-04-17 17:19:194558 // TODO(crbug.com/406729265): LoadPostCommitErrorPage() does not initiate a
4559 // navigation via Navigator::Navigate(). We should fix that, so that
4560 // post-commit error page navigations don't bypass other important checks in
4561 // this function.
Kevin McNeeccca6172021-10-19 17:11:144562 // Calling BeginNavigation may destroy the NavigationRequest.
4563 base::WeakPtr<NavigationRequest> created_navigation_request(
4564 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414565 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144566 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414567}
4568
Andrew Verge754c70a2025-04-17 17:19:194569void NavigationControllerImpl::NavigateFrameToErrorPage(
4570 RenderFrameHostImpl* render_frame_host_impl,
4571 const GURL& url,
4572 const std::string& error_page_html) {
Andrew Verge754c70a2025-04-17 17:19:194573 std::unique_ptr<NavigationRequest> navigation_request =
4574 CreateNavigationRequestForErrorPage(render_frame_host_impl, url,
4575 error_page_html,
4576 /*is_post_commit_error_page=*/false);
4577 if (!navigation_request) {
4578 return;
4579 }
4580
4581 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
4582 node->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
4583}
4584
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574585void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214586 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094587 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154588 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144589 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294590}
4591
[email protected]d202a7c2012-01-04 07:53:474592void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364593 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584594 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474595 // represent a no-committed-entry state.
4596 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364597 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584598 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474599 // if `entries_` contains pre-existing entries from the NavigationController
4600 // before restore, which would not be removed and will be at the front of the
4601 // entries list, causing the index to be off by the amount of pre-existing
4602 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294603 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294604}
[email protected]765b35502008-08-21 00:51:204605
arthursonzogni69a6a1b2019-09-17 09:23:004606void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004607 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4608}
4609
4610void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4611 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474612 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104613 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4614 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294615 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474616 return;
Michael Thiessenc5676d22019-09-25 22:32:104617 }
avi45a72532015-04-07 21:01:454618 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314619
4620 if (!delegate_)
4621 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374622 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484623}
4624
avi7c6f35e2015-05-08 17:52:384625int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4626 int nav_entry_id) const {
4627 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4628 if (entries_[i]->GetUniqueID() == nav_entry_id)
4629 return i;
4630 }
4631 return -1;
4632}
4633
[email protected]d202a7c2012-01-04 07:53:474634void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574635 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254636 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574637 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594638 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254639 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374640 // Normally, cloning a NavigationEntryImpl results in sharing
4641 // FrameNavigationEntries between the original and the clone. However, when
4642 // cloning from a different NavigationControllerImpl, we want to fork the
4643 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374644 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594645 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254646 }
Rakina Zata Amnie2d31312022-11-18 03:38:454647 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274648 DCHECK(pending_entry_index_ == -1 ||
4649 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254650}
[email protected]c5b88d82012-10-06 17:03:334651
4652void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184653 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334654 get_timestamp_callback_ = get_timestamp_callback;
4655}
[email protected]8ff00d72012-10-23 19:12:214656
Shivani Sharmaffb32b82019-04-09 16:58:474657// History manipulation intervention:
4658void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474659 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564660 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404661 bool is_renderer_initiated,
4662 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564663 // Note that for a subframe,
4664 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454665 // gesture happened in any subframe (propagated to main frame) or in the main
4666 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564667 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274668 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474669 return;
4670 }
4671 if (last_committed_entry_index_ == -1)
4672 return;
4673
Shivani Sharmac4cc8922019-04-18 03:11:174674 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474675
Alexander Timine3ec4192020-04-20 16:39:404676 // Log UKM with the URL we are navigating away from.
4677 ukm::builders::HistoryManipulationIntervention(
4678 previous_page_load_ukm_source_id)
4679 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474680}
4681
Shivani Sharmac4cc8922019-04-18 03:11:174682void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4683 int reference_index,
4684 bool skippable) {
4685 auto* reference_entry = GetEntryAtIndex(reference_index);
4686 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4687
4688 int64_t document_sequence_number =
4689 reference_entry->root_node()->frame_entry->document_sequence_number();
4690 for (int index = 0; index < GetEntryCount(); index++) {
4691 auto* entry = GetEntryAtIndex(index);
4692 if (entry->root_node()->frame_entry->document_sequence_number() ==
4693 document_sequence_number) {
4694 entry->set_should_skip_on_back_forward_ui(skippable);
4695 }
4696 }
4697}
4698
arthursonzogni66f711c2019-10-08 14:40:364699std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4700NavigationControllerImpl::ReferencePendingEntry() {
4701 DCHECK(pending_entry_);
4702 auto pending_entry_ref =
4703 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4704 pending_entry_refs_.insert(pending_entry_ref.get());
4705 return pending_entry_ref;
4706}
4707
4708void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4709 // Ignore refs that don't correspond to the current pending entry.
4710 auto it = pending_entry_refs_.find(ref);
4711 if (it == pending_entry_refs_.end())
4712 return;
4713 pending_entry_refs_.erase(it);
4714
4715 if (!pending_entry_refs_.empty())
4716 return;
4717
4718 // The pending entry may be deleted before the last PendingEntryRef.
4719 if (!pending_entry_)
4720 return;
4721
4722 // We usually clear the pending entry when the matching NavigationRequest
4723 // fails, so that an arbitrary URL isn't left visible above a committed page.
4724 //
4725 // However, we do preserve the pending entry in some cases, such as on the
4726 // initial navigation of an unmodified blank tab. We also allow the delegate
4727 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4728 // user edit the URL and try again. This may be useful in cases that the
4729 // committed page cannot be attacker-controlled. In these cases, we still
4730 // allow the view to clear the pending entry and typed URL if the user
4731 // requests (e.g., hitting Escape with focus in the address bar).
4732 //
4733 // Do not leave the pending entry visible if it has an invalid URL, since this
4734 // might be formatted in an unexpected or unsafe way.
4735 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364736 bool should_preserve_entry =
4737 (pending_entry_ == GetVisibleEntry()) &&
4738 pending_entry_->GetURL().is_valid() &&
4739 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4740 if (should_preserve_entry)
4741 return;
4742
4743 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374744 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364745}
4746
Titouan Rigoudy6ec70402021-02-02 15:42:194747std::unique_ptr<PolicyContainerPolicies>
4748NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394749 RenderFrameHostImpl* rfh,
4750 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214751 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174752 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214753 if (navigation_encountered_error) {
4754 // We should never reload the policy container of an error page from
4755 // history, see https://crbug.com/364773822.
4756 return nullptr;
4757 }
4758
Antonio Sartori78a749f2020-11-30 12:03:394759 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454760 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394761 FrameNavigationEntry* previous_frame_entry =
4762 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4763
Alison Gale770f3fc2024-04-27 00:39:584764 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394765 // ensure we always have a FrameNavigationEntry here.
4766 if (!previous_frame_entry)
4767 return nullptr;
4768
Titouan Rigoudy6ec70402021-02-02 15:42:194769 const PolicyContainerPolicies* previous_policies =
4770 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394771
Titouan Rigoudy6ec70402021-02-02 15:42:194772 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394773 return nullptr;
4774
4775 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234776 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394777 }
4778
Titouan Rigoudy72f892d2022-05-02 18:21:234779 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394780}
4781
Charlie Reis99b2eba22025-01-31 19:18:574782void NavigationControllerImpl::BroadcastHistoryIndexAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504783 OPTIONAL_TRACE_EVENT2(
Charlie Reis99b2eba22025-01-31 19:18:574784 "content", "NavigationControllerImpl::BroadcastHistoryIndexAndLength",
4785 "history_index", GetLastCommittedEntryIndex(), "history_length",
Hayato Ito2c8c08d02021-06-23 03:38:434786 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504787
Charlie Reis99b2eba22025-01-31 19:18:574788 int history_index = GetLastCommittedEntryIndex();
Kevin McNee7705fe82024-11-07 18:56:314789 int history_length = GetEntryCount();
Charlie Reis99b2eba22025-01-31 19:18:574790 auto callback = [history_index, history_length](RenderViewHostImpl* rvh) {
Kevin McNee7705fe82024-11-07 18:56:314791 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
Charlie Reis99b2eba22025-01-31 19:18:574792 broadcast->SetHistoryIndexAndLength(history_index, history_length);
Kevin McNee7705fe82024-11-07 18:56:314793 }
4794 };
Ali Hijazid87307d2022-11-07 20:15:034795 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504796}
4797
4798void NavigationControllerImpl::DidAccessInitialMainDocument() {
4799 // We may have left a failed browser-initiated navigation in the address bar
4800 // to let the user edit it and try again. Clear it now that content might
4801 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034802 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504803 DiscardPendingEntry(false);
4804
4805 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374806 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504807}
4808
4809void NavigationControllerImpl::UpdateStateForFrame(
4810 RenderFrameHostImpl* rfhi,
4811 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564812 OPTIONAL_TRACE_EVENT1("content",
4813 "NavigationControllerImpl::UpdateStateForFrame",
4814 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504815 // The state update affects the last NavigationEntry associated with the given
4816 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4817 // in the case of an UpdateState from a frame being swapped out). We track
4818 // which entry this is in the RenderFrameHost's nav_entry_id.
4819 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4820 if (!entry)
4821 return;
4822
4823 FrameNavigationEntry* frame_entry =
4824 entry->GetFrameEntry(rfhi->frame_tree_node());
4825 if (!frame_entry)
4826 return;
4827
4828 // The SiteInstance might not match if we do a cross-process navigation with
4829 // replacement (e.g., auto-subframe), in which case the swap out of the old
4830 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4831 // has already been replaced and destroyed.
4832 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4833 return;
4834
4835 if (page_state == frame_entry->page_state())
4836 return; // Nothing to update.
4837
4838 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4839
4840 // The document_sequence_number and item_sequence_number recorded in the
4841 // FrameNavigationEntry should not differ from the one coming with the update,
4842 // since it must come from the same document. Do not update it if a difference
4843 // is detected, as this indicates that |frame_entry| is not the correct one.
4844 blink::ExplodedPageState exploded_state;
4845 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4846 return;
4847
4848 if (exploded_state.top.document_sequence_number !=
4849 frame_entry->document_sequence_number() ||
4850 exploded_state.top.item_sequence_number !=
4851 frame_entry->item_sequence_number()) {
4852 return;
4853 }
4854
4855 frame_entry->SetPageState(page_state);
4856 NotifyEntryChanged(entry);
4857}
4858
Nate Chapina2c881f52023-11-07 17:02:094859namespace {
4860
4861// The caller is responsible for ensuring the entry is same-origin to the
4862// origin to be committed.
4863blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4864 FrameNavigationEntry* frame_entry,
4865 int64_t pending_document_sequence_number) {
4866 blink::ExplodedPageState exploded_state;
4867 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4868 &exploded_state)) {
4869 return nullptr;
4870 }
4871 blink::ExplodedFrameState frame_state = exploded_state.top;
4872
4873 // If the document represented by this FNE hid its full url from appearing in
4874 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4875 // in the navigation API as well (unless we're navigating to that document).
4876 std::u16string url;
4877 if (pending_document_sequence_number ==
4878 frame_entry->document_sequence_number() ||
4879 !frame_entry->protect_url_in_navigation_api()) {
4880 url = frame_state.url_string.value_or(std::u16string());
4881 }
4882
4883 return blink::mojom::NavigationApiHistoryEntry::New(
4884 frame_state.navigation_api_key.value_or(std::u16string()),
4885 frame_state.navigation_api_id.value_or(std::u16string()), url,
4886 frame_state.item_sequence_number, frame_state.document_sequence_number,
4887 frame_state.navigation_api_state);
4888}
4889
4890} // namespace
4891
Domenic Denicolacd30f5f82022-03-16 21:48:014892std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4893NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574894 Direction direction,
4895 int entry_index,
4896 const url::Origin& pending_origin,
4897 FrameTreeNode* node,
4898 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304899 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094900 int64_t pending_document_sequence_number,
4901 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014902 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454903 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174904 // Don't process the initial entry.
4905 DCHECK_EQ(GetEntryCount(), 1);
4906 return entries;
4907 }
Nate Chapind1fe3612021-04-16 20:45:574908 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304909 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574910 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4911 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094912 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574913 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414914 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574915 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014916 // An entry should only appear in the navigation API entries if it is for
4917 // the same origin as the document being committed. Check the committed
4918 // origin, or if that is not available (during restore), check against the
4919 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584920 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094921 // once we can be sure that entries with the same ISN will never be
4922 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414923 url::Origin frame_entry_origin =
4924 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4925 frame_entry->url(),
4926 frame_entry->initiator_origin().value_or(url::Origin())));
4927 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574928 break;
4929 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4930 continue;
Nate Chapina2c881f52023-11-07 17:02:094931 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4932 ToNavigationApiHistoryEntry(frame_entry,
4933 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304934 DCHECK(entry->url.empty() ||
4935 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574936 entries.push_back(std::move(entry));
4937 previous_item_sequence_number = frame_entry->item_sequence_number();
4938 }
4939 }
4940 // If |entries| was constructed by iterating backwards from
4941 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4942 // earliest-at-the-front. Reverse it.
4943 if (direction == Direction::kBack)
4944 std::reverse(entries.begin(), entries.end());
4945 return entries;
4946}
4947
Domenic Denicolacd30f5f82022-03-16 21:48:014948blink::mojom::NavigationApiHistoryEntryArraysPtr
4949NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554950 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574951 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404952 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444953 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404954 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574955
Nate Chapind1fe3612021-04-16 20:45:574956 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554957 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574958
Nate Chapine82339d02022-05-03 23:48:254959 // NOTE: |entry_index| is the index where this entry will commit if no
4960 // modifications are made between now and DidCommitNavigation. This is used to
4961 // walk |entries_| and determine which entries should be exposed by the
4962 // navigation API. It is important to calculate this correctly, because blink
4963 // will cancel a same-document history commit if it's not present in the
4964 // entries blink knows about.
4965 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574966 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304967 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254968 bool will_create_new_entry = false;
4969 if (GetPendingEntryIndex() != -1) {
4970 entry_index = GetPendingEntryIndex();
4971 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4972 pending_item_sequence_number = frame_entry->item_sequence_number();
4973 pending_document_sequence_number =
4974 frame_entry->document_sequence_number();
4975 }
4976 } else if (request &&
4977 !NavigationTypeUtils::IsReload(
4978 request->common_params().navigation_type) &&
4979 !NavigationTypeUtils::IsHistory(
4980 request->common_params().navigation_type) &&
4981 !request->common_params().should_replace_current_entry &&
4982 !request->common_params()
4983 .is_history_navigation_in_new_child_frame) {
4984 will_create_new_entry = true;
4985 entry_index = GetLastCommittedEntryIndex() + 1;
4986 // Don't set pending_item_sequence_number or
4987 // pending_document_sequence_number in this case - a new unique isn/dsn will
4988 // be calculated in the renderer later.
4989 } else if (GetLastCommittedEntryIndex() != -1) {
4990 entry_index = GetLastCommittedEntryIndex();
4991 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574992 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304993 pending_document_sequence_number =
4994 frame_entry->document_sequence_number();
4995 }
Nate Chapind1fe3612021-04-16 20:45:574996 }
4997
Domenic Denicolacd30f5f82022-03-16 21:48:014998 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254999 if (entry_index == -1) {
5000 // TODO(rakina): Exit early when there is no last committed entry.
5001 // Remove when InitialNavigationEntry ships.
5002 return entry_arrays;
5003 }
5004
Nate Chapina2c881f52023-11-07 17:02:095005 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:015006 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:575007 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:095008 pending_item_sequence_number, pending_document_sequence_number,
5009 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:575010
5011 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:095012 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:575013 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:015014 entry_arrays->forward_entries =
5015 PopulateSingleNavigationApiHistoryEntryVector(
5016 Direction::kForward, entry_index, pending_origin, node,
5017 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:095018 pending_document_sequence_number, forwardmost_index);
5019 }
5020
5021 // If the previous entry is within the block of contiguous entries being
5022 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:255023 FrameNavigationEntry* previous_entry = nullptr;
5024 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:055025 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
5026 .initiator_frame_tree_node_id();
5027 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:255028 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
5029 previous_entry = initiator_node->frame_tree()
5030 .controller()
5031 .GetLastCommittedEntry()
5032 ->GetFrameEntry(initiator_node);
5033 }
5034 } else if (GetLastCommittedEntryIndex() != -1 &&
5035 GetLastCommittedEntryIndex() >= backmost_index &&
5036 GetLastCommittedEntryIndex() <= forwardmost_index) {
5037 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
5038 }
5039 if (previous_entry) {
5040 url::Origin previous_entry_origin =
5041 previous_entry->committed_origin().value_or(url::Origin::Resolve(
5042 previous_entry->url(),
5043 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:585044 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:255045 // once we can be sure that entries with the same ISN will never be
5046 // cross-origin.
5047 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
5048 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
5049 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:095050 }
Nate Chapind1fe3612021-04-16 20:45:575051 }
Nate Chapinc06cf80a2023-11-18 01:12:255052
Nate Chapin4e657a472022-02-06 03:38:375053 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:575054}
5055
Nate Chapinfbfe5af2021-06-10 17:22:085056NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:575057NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085058 FrameNavigationEntry* current_entry,
5059 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:575060 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:085061 if (!target_entry || !target_entry->committed_origin())
5062 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:085063 if (!current_entry->committed_origin()->IsSameOriginWith(
5064 *target_entry->committed_origin())) {
5065 return HistoryNavigationAction::kStopLooking;
5066 }
5067
5068 // NOTE: We don't actually care between kSameDocument and
5069 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:575070 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:085071 return HistoryNavigationAction::kDifferentDocument;
5072 return HistoryNavigationAction::kKeepLooking;
5073}
5074
Domenic Denicolacc094fb2022-03-16 23:40:575075void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:205076 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:375077 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:145078 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:495079 const std::string& key,
5080 base::TimeTicks actual_navigation_start) {
Nate Chapinbf682fa32022-09-26 22:41:205081 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:085082 FrameNavigationEntry* current_entry =
5083 GetLastCommittedEntry()->GetFrameEntry(node);
Nate Chapin0dbc93af2025-03-28 17:02:525084 if (!current_entry || !current_entry->committed_origin()) {
Nate Chapinfbfe5af2021-06-10 17:22:085085 return;
Nate Chapin0dbc93af2025-03-28 17:02:525086 }
Nate Chapinfbfe5af2021-06-10 17:22:085087
Alison Gale47d1537d2024-04-19 21:31:465088 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:135089 // when `navigation.traverseTo()` is called.
5090
Nate Chapinfbfe5af2021-06-10 17:22:085091 // We want to find the nearest matching entry that is contiguously
5092 // same-instance and same-origin. Check back first, then forward.
5093 // TODO(japhet): Link spec here once it exists.
5094 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:575095 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085096 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5097 if (result == HistoryNavigationAction::kStopLooking)
5098 break;
5099 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495100 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5101 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085102 return;
5103 }
5104 }
5105 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:575106 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085107 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5108 if (result == HistoryNavigationAction::kStopLooking)
5109 break;
5110 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495111 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5112 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085113 return;
5114 }
5115 }
Nate Chapinbf682fa32022-09-26 22:41:205116
5117 // If we fall through to here, a matching NavigationEntry couldn't be found.
5118 // Notify the renderer that the navigation was cancelled.
5119 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
5120 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:085121}
5122
Domenic Denicolacc094fb2022-03-16 23:40:575123bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:305124 network::mojom::ReferrerPolicy referrer_policy) {
5125 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
5126 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
5127}
5128
shivanigithubf405bf0d2021-11-05 17:58:335129bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
5130 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:315131 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:335132 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:545133 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:465134 // The preview mode appears as prerendered page in renderers, and
5135 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:035136 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:515137 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:335138 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:545139}
5140
Julie Jeongeun Kim0e242242022-11-30 10:45:095141void NavigationControllerImpl::DidChangeReferrerPolicy(
5142 FrameTreeNode* node,
5143 network::mojom::ReferrerPolicy referrer_policy) {
5144 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
5145 if (!entry)
5146 return;
5147
5148 // The FrameNavigationEntry may want to change whether to protect its url
5149 // in the navigation API when the referrer policy changes.
5150 entry->set_protect_url_in_navigation_api(
5151 ShouldProtectUrlInNavigationApi(referrer_policy));
5152}
5153
Minoru Chikamune646eba42025-04-14 01:25:035154void NavigationControllerImpl::CheckPotentialNavigationReentrancy() {
Minoru Chikamune13ab4de2025-05-14 21:54:075155 if (can_be_in_navigate_to_pending_entry_) {
Minoru Chikamune646eba42025-04-14 01:25:035156 // This DumpWithoutCrashing is an investigation code for
5157 // https://crbug.com/396998476.
5158 base::debug::DumpWithoutCrashing();
5159 }
5160}
5161
Andrew Verge754c70a2025-04-17 17:19:195162std::unique_ptr<NavigationRequest>
5163NavigationControllerImpl::CreateNavigationRequestForErrorPage(
5164 RenderFrameHostImpl* render_frame_host_impl,
5165 const GURL& url,
5166 const std::string& error_page_html,
5167 bool is_post_commit_error_page) {
5168 // Only active documents can load error pages:
5169 // - If the document is in pending deletion, the browser already committed to
5170 // destroying this RenderFrameHost so ignore loading the error page.
5171 // - If the document is in back-forward cache, it's not allowed to navigate as
5172 // it should remain frozen. Ignore the request and evict the document from
5173 // back-forward cache.
5174 // - If the document is prerendering, it can navigate but when loading error
5175 // pages, cancel prerendering.
5176 if (render_frame_host_impl->IsInactiveAndDisallowActivation(
5177 is_post_commit_error_page
5178 ? DisallowActivationReasonId::kLoadPostCommitErrorPage
5179 : DisallowActivationReasonId::kBrowserInitiatedErrorPage)) {
5180 return nullptr;
5181 }
5182
5183 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
5184
5185 blink::mojom::CommonNavigationParamsPtr common_params =
5186 blink::CreateCommonNavigationParams();
5187 // |url| might be empty, such as when this method is called before
5188 // the frame actually committed (e.g. iframe with "src" set to a
5189 // slow-responding URL). We should rewrite the URL to about:blank in this
5190 // case, as the renderer will only think a page is an error page if it has a
5191 // non-empty unreachable URL.
5192 common_params->url = url.is_empty() ? GURL("about:blank") : url;
5193
5194 // Loading an error page via LoadPostCommitErrorPage() performs a temporary
5195 // replacement of the entire NavigationEntry and swaps it back in later.
5196 // All other error page types should permanently replace the current entry.
5197 if (!is_post_commit_error_page) {
5198 common_params->should_replace_current_entry = true;
5199 }
5200
5201 blink::mojom::CommitNavigationParamsPtr commit_params =
5202 blink::CreateCommitNavigationParams();
5203 commit_params->original_url = common_params->url;
5204
5205 commit_params->navigation_timing->system_entropy_at_navigation_start =
5206 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
5207 node, blink::mojom::SystemEntropy::kNormal);
5208
5209 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
5210 // error pages.
5211 commit_params->frame_policy = node->pending_frame_policy();
5212
5213 std::unique_ptr<NavigationRequest> navigation_request =
5214 NavigationRequest::CreateBrowserInitiated(
5215 node, std::move(common_params), std::move(commit_params),
5216 false /* was_opener_suppressed */, "" /* extra_headers */,
5217 nullptr /* frame_entry */, nullptr /* entry */,
5218 false /* is_form_submission */, nullptr /* navigation_ui_data */,
5219 std::nullopt /* impression */, false /* is_pdf */);
5220 if (is_post_commit_error_page) {
5221 navigation_request->set_browser_initiated_error_navigation_type(
5222 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit);
5223 } else {
5224 navigation_request->set_browser_initiated_error_navigation_type(
5225 NavigationRequest::BrowserInitiatedErrorNavigationType::kRegular);
5226 }
5227 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
5228 navigation_request->set_error_page_html(error_page_html);
5229 return navigation_request;
5230}
5231
[email protected]8ff00d72012-10-23 19:12:215232} // namespace content