blob: f0a577a3ad872cc4ae4b3b462b8f0aebfc02deaa [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"
asvitkine3033081a2016-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.
Xiaohan Wang2b2aabb2025-08-19 23:42:30131BASE_FEATURE(SkipExtraBfcacheNavigationRequest,
Charlie Reis3696ab62025-05-28 07:02:30132 base::FEATURE_DISABLED_BY_DEFAULT);
Charlie Reis655c8f02025-05-15 01:16:17133
Diana Qu21d0c922025-06-25 17:19:08134// Enables a CHECK in RendererDidNavigate to ensure that session
135// history navigations commit in the expected SiteInstance when the
136// document sequence number matches. Helps detect navigation process
137// mismatches and potential security issues.
Xiaohan Wang2b2aabb2025-08-19 23:42:30138BASE_FEATURE(CheckSiteInstanceOnHistoryNavigation,
Diana Qu21d0c922025-06-25 17:19:08139 base::FEATURE_ENABLED_BY_DEFAULT);
140
[email protected]e9ba4472008-09-14 15:42:43141// Invoked when entries have been pruned, or removed. For example, if the
142// current entries are [google, digg, yahoo], with the current entry google,
143// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47144void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50145 int index,
[email protected]c12bf1a12008-09-17 16:28:49146 int count) {
[email protected]8ff00d72012-10-23 19:12:21147 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50148 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49149 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14150 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43151}
152
[email protected]e9ba4472008-09-14 15:42:43153// Configure all the NavigationEntries in entries for restore. This resets
154// the transition type to reload and makes sure the content state isn't empty.
155void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57156 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48157 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47158 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43159 // Use a transition type of reload so that we don't incorrectly increase
160 // the typed count.
Lei Zhang96031532019-10-10 19:05:47161 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
162 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43163 }
164}
165
[email protected]bf70edce2012-06-20 22:32:22166// Determines whether or not we should be carrying over a user agent override
167// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57168bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22169 return last_entry && last_entry->GetIsOverridingUserAgent();
170}
171
Camille Lamy5193caa2018-10-12 11:59:42172// Determines whether to override user agent for a navigation.
173bool ShouldOverrideUserAgent(
174 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57175 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42176 switch (override_user_agent) {
177 case NavigationController::UA_OVERRIDE_INHERIT:
178 return ShouldKeepOverride(last_committed_entry);
179 case NavigationController::UA_OVERRIDE_TRUE:
180 return true;
181 case NavigationController::UA_OVERRIDE_FALSE:
182 return false;
Camille Lamy5193caa2018-10-12 11:59:42183 }
Peter Boströmfc7ddc182024-10-31 19:37:21184 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42185}
186
Rakina Zata Amni312822d72021-06-04 16:13:37187// Returns true if this navigation should be treated as a reload. For e.g.
Liang Zhao0351d762024-11-13 00:10:07188// clicking on a link which results in a navigation to the last committed URL
189// (but wasn't converted to do a replacement navigation in the renderer), etc.
190// This intentionally excludes navigating to the last committed URL via the
191// address bar, so that the current scroll position is not restored.
Fergal Daly766177d2020-07-07 07:54:04192// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
193// |base_url_for_data_url|, |transition_type| correspond to the new navigation
194// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
195// navigation that committed.
196bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
197 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57198 const GURL& virtual_url,
199 const GURL& base_url_for_data_url,
200 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57201 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37202 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57203 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37204 // Navigations intended to do a replacement shouldn't be converted to do a
205 // reload.
206 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28207 return false;
clamy0a656e42018-02-06 18:18:28208 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45209 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55210 return false;
211
arthursonzogni7a8243682017-12-14 16:41:42212 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28213 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42214 return false;
215
Liang Zhao0351d762024-11-13 00:10:07216 // Same URL navigations from the address bar should only be treated as reloads
217 // if PAGE_TRANSITION_RELOAD is set (not for PAGE_TRANSITION_TYPED or
218 // PAGE_TRANSITION_LINK). In non-address-bar cases, PAGE_TRANSITION_TYPED
219 // and PAGE_TRANSITION_LINK can be treated as reloads.
clamy0a656e42018-02-06 18:18:28220 bool transition_type_can_be_converted = false;
Liang Zhao0351d762024-11-13 00:10:07221 if (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
222 if (ui::PageTransitionCoreTypeIs(transition_type,
223 ui::PAGE_TRANSITION_RELOAD)) {
224 transition_type_can_be_converted = true;
225 }
226 } else {
227 if (ui::PageTransitionCoreTypeIs(transition_type,
228 ui::PAGE_TRANSITION_TYPED) ||
229 ui::PageTransitionCoreTypeIs(transition_type,
230 ui::PAGE_TRANSITION_LINK)) {
231 transition_type_can_be_converted = true;
232 }
ananta3bdd8ae2016-12-22 17:11:55233 }
clamy0a656e42018-02-06 18:18:28234 if (!transition_type_can_be_converted)
235 return false;
236
237 // This check is required for cases like view-source:, etc. Here the URL of
238 // the navigation entry would contain the url of the page, while the virtual
239 // URL contains the full URL including the view-source prefix.
240 if (virtual_url != last_committed_entry->GetVirtualURL())
241 return false;
242
Fergal Daly766177d2020-07-07 07:54:04243 // Check that the URLs match.
244 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
245 // If there's no frame entry then by definition the URLs don't match.
246 if (!frame_entry)
247 return false;
248
249 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28250 return false;
251
252 // This check is required for Android WebView loadDataWithBaseURL. Apps
253 // can pass in anything in the base URL and we need to ensure that these
254 // match before classifying it as a reload.
255 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
256 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
257 return false;
ananta3bdd8ae2016-12-22 17:11:55258 }
259
clamy0a656e42018-02-06 18:18:28260 // Skip entries with SSL errors.
261 if (last_committed_entry->ssl_error())
262 return false;
263
264 // Don't convert to a reload when the last navigation was a POST or the new
265 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04266 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28267 return false;
268
269 return true;
ananta3bdd8ae2016-12-22 17:11:55270}
271
Arthur Sonzognic686e8f2024-01-11 08:36:37272std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12273 const mojom::DidCommitProvisionalLoadParams& params,
274 NavigationRequest* request) {
Nasko Oskov039121012019-01-11 00:21:32275 // Error pages commit in an opaque origin, yet have the real URL that resulted
276 // in an error as the |params.url|. Since successful reload of an error page
277 // should commit in the correct origin, setting the opaque origin on the
278 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17279 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37280 return std::nullopt;
Nasko Oskov039121012019-01-11 00:21:32281
Arthur Sonzognic686e8f2024-01-11 08:36:37282 return std::make_optional(params.origin);
Nasko Oskov039121012019-01-11 00:21:32283}
284
Alex Moshchuk99242832023-05-22 17:21:44285bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42286 const GURL& virtual_url,
287 const GURL& dest_url) {
288 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44289 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
290 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42291 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
292 << virtual_url.possibly_invalid_spec();
293 return false;
294 }
295
296 // Don't attempt to navigate to non-empty invalid URLs.
297 if (!dest_url.is_valid() && !dest_url.is_empty()) {
298 LOG(WARNING) << "Refusing to load invalid URL: "
299 << dest_url.possibly_invalid_spec();
300 return false;
301 }
302
303 // The renderer will reject IPC messages with URLs longer than
304 // this limit, so don't attempt to navigate with a longer URL.
305 if (dest_url.spec().size() > url::kMaxURLChars) {
306 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
307 << " characters.";
308 return false;
309 }
310
Aaron Colwell33109c592020-04-21 21:31:19311 // Reject renderer debug URLs because they should have been handled before
312 // we get to this point. This check handles renderer debug URLs
313 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
314 // provides defense-in-depth if a renderer debug URL manages to get here via
315 // some other path. We want to reject the navigation here so it doesn't
316 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30317 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19318 LOG(WARNING) << "Refusing to load renderer debug URL: "
319 << dest_url.possibly_invalid_spec();
320 return false;
321 }
322
Alex Moshchuk99242832023-05-22 17:21:44323 // Guests only support navigations to known-safe schemes. This check already
324 // exists in the extensions layer, where it also dispatches proper events to
325 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
326 // for defense-in-depth to ensure that no other places in the codebase
327 // accidentally navigate guests to schemes such as WebUI, which is not
328 // supported. See https://crbug.com/1444221.
329 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
330 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
331 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
332 !dest_url.SchemeIs(url::kAboutScheme)) {
333 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
334 << dest_url.possibly_invalid_spec();
335 return false;
336 }
337 }
338
Camille Lamy5193caa2018-10-12 11:59:42339 return true;
340}
341
Mikel Astizba9cf2fd2017-12-17 10:38:10342// See replaced_navigation_entry_data.h for details: this information is meant
343// to ensure |*output_entry| keeps track of its original URL (landing page in
344// case of server redirects) as it gets replaced (e.g. history.replaceState()),
345// without overwriting it later, for main frames.
346void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57347 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10348 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17349 if (output_entry->GetReplacedEntryData().has_value() ||
350 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10351 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17352 }
Mikel Astizba9cf2fd2017-12-17 10:38:10353
354 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57355 data.first_committed_url = replaced_entry->GetURL();
356 data.first_timestamp = replaced_entry->GetTimestamp();
357 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29358 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10359}
360
Minggang Wangb9f3fa92021-07-01 15:30:31361blink::mojom::NavigationType GetNavigationType(
362 const GURL& old_url,
363 const GURL& new_url,
364 ReloadType reload_type,
365 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52366 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31367 bool has_pending_cross_document_commit,
368 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49369 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13370 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49371 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23372 // Reload navigations
373 switch (reload_type) {
374 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31375 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23376 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31377 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23378 case ReloadType::NONE:
379 break; // Fall through to rest of function.
380 }
381
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08382 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31383 return entry->GetHasPostData()
384 ? blink::mojom::NavigationType::RESTORE_WITH_POST
385 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23386 }
387
danakjb952ef12021-01-14 19:58:49388 const bool can_be_same_document =
389 // A pending cross-document commit means this navigation will not occur in
390 // the current document, as that document would end up being replaced in
391 // the meantime.
392 !has_pending_cross_document_commit &&
393 // If the current document is an error page, we should always treat it as
394 // a different-document navigation so that we'll attempt to load the
395 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49396 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13397 // If the navigation is an embedder-initiated navigation of a fenced
398 // frame root (i.e. enters a fenced frame tree from outside),
399 // same-document navigations should be disabled because we don't want to
400 // allow information to be joined across multiple embedder-initiated
401 // fenced frame navigations (which may contain separate cross-site data).
402 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49403 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
404 // same-document navigations should be disabled because we want to force
405 // the creation of a new browsing context group.
406 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12407
clamyea99ea12018-05-28 13:54:23408 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52409 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12410 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31411 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
412 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23413 }
414 DCHECK(!is_same_document_history_load);
415
416 // A same-document fragment-navigation happens when the only part of the url
417 // that is modified is after the '#' character.
418 //
419 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12420 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23421 //
422 // Note: this check is only valid for navigations that are not history
423 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
424 // history navigation from 'A#foo' to 'A#bar' is not a same-document
425 // navigation, but a different-document one. This is why history navigation
426 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47427 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52428 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12429
430 // The one case where we do the wrong thing here and incorrectly choose
431 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
432 // the renderer is a frameset. All frameset navigations should be
433 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
434 // navigation would do the right thing, as it would send it to the browser and
435 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
436 // into this method). But since we can't tell that case here for browser-
437 // initiated navigations, we have to get the renderer involved. In that case
438 // the navigation would be restarted due to the renderer spending a reply of
439 // mojom::CommitResult::RestartCrossDocument.
440
441 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31442 ? blink::mojom::NavigationType::SAME_DOCUMENT
443 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23444}
445
Camille Lamy5193caa2018-10-12 11:59:42446// Adjusts the original input URL if needed, to get the URL to actually load and
447// the virtual URL, which may differ.
448void RewriteUrlForNavigation(const GURL& original_url,
449 BrowserContext* browser_context,
450 GURL* url_to_load,
451 GURL* virtual_url,
452 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42453 // Allow the browser URL handler to rewrite the URL. This will, for example,
454 // remove "view-source:" from the beginning of the URL to get the URL that
455 // will actually be loaded. This real URL won't be shown to the user, just
456 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31457 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42458 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
459 url_to_load, browser_context, reverse_on_redirect);
460}
461
462#if DCHECK_IS_ON()
463// Helper sanity check function used in debug mode.
464void ValidateRequestMatchesEntry(NavigationRequest* request,
465 NavigationEntryImpl* entry) {
466 if (request->frame_tree_node()->IsMainFrame()) {
467 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
468 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31469 ui::PageTransitionFromInt(request->common_params().transition),
470 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42471 }
Nasko Oskovc36327d2019-01-03 23:23:04472 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42473 entry->should_clear_history_list());
474 DCHECK_EQ(request->common_params().has_user_gesture,
475 entry->has_user_gesture());
476 DCHECK_EQ(request->common_params().base_url_for_data_url,
477 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04478 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42479 entry->GetCanLoadLocalResources());
480 DCHECK_EQ(request->common_params().started_from_context_menu,
481 entry->has_started_from_context_menu());
482
483 FrameNavigationEntry* frame_entry =
484 entry->GetFrameEntry(request->frame_tree_node());
485 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52486 // TODO(https://crbug.com/40467594): This case should be unreachable once
487 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42488 return;
489 }
490
Camille Lamy5193caa2018-10-12 11:59:42491 DCHECK_EQ(request->common_params().method, frame_entry->method());
492
Nasko Oskovc36327d2019-01-03 23:23:04493 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42494 if (redirect_size == frame_entry->redirect_chain().size()) {
495 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04496 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42497 frame_entry->redirect_chain()[i]);
498 }
499 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21500 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42501 }
502}
503#endif // DCHECK_IS_ON()
504
Dave Tapuska8bfd84c2019-03-26 20:47:16505// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20506// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16507bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20508 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16509 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20510 DCHECK(sandboxed_initiator_rfh);
511 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
512 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16513 for (auto& item : navigations) {
514 bool within_subtree = false;
515 // Check whether this NavigationRequest affects a frame within the
516 // sandboxed frame's subtree by walking up the tree looking for the
517 // sandboxed frame.
518 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03519 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20520 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16521 within_subtree = true;
522 break;
523 }
524 }
525 if (!within_subtree)
526 return false;
527 }
528 return true;
529}
530
William Liu122754942024-01-18 22:34:39531// Used for "Navigation.SessionHistoryCount" histogram.
532enum class HistoryNavTypeForHistogram {
533 // A same-doc or cross-doc navigation of the main frame. We can only have one
534 // main frame request per `NavigationController::GoToIndex()`.
535 kMainFrame = 0,
536 // `NavigationController::GoToIndex()` creates one main frame request and
537 // one or more subframe requests.
538 kMainFrameAndSubframe,
539 // `NavigationController::GoToIndex()` creates one or more subframe requests.
540 kSubframe,
541 // Used for histogram boundary.
542 kCount
543};
544
545void CountRequests(
546 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
547 int& mutable_main_frame_cnt,
548 int& mutable_subframe_cnt) {
549 for (const auto& req : requests) {
550 if (req->IsInPrimaryMainFrame()) {
551 // We can only have one main frame navigation at a time.
552 CHECK_EQ(mutable_main_frame_cnt, 0);
553 ++mutable_main_frame_cnt;
554 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
555 ++mutable_subframe_cnt;
556 }
557 }
558}
559
560// Record the number of different types of navigations as histograms. See
561// `HistoryNavTypeForHistogram` for the types.
562void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
563 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
564 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
565 // We must have one request.
566 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
567
568 int main_frame_cnt = 0;
569 int subframe_cnt = 0;
570 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
571 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
572
573 std::optional<HistoryNavTypeForHistogram> history_nav_type;
574 if (main_frame_cnt > 0) {
575 if (subframe_cnt == 0) {
576 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
577 } else {
578 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
579 }
580 } else if (subframe_cnt > 0) {
581 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
582 }
583 if (history_nav_type.has_value()) {
584 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
585 history_nav_type.value(),
586 HistoryNavTypeForHistogram::kCount);
587 }
588}
589
[email protected]e9ba4472008-09-14 15:42:43590} // namespace
591
arthursonzogni66f711c2019-10-08 14:40:36592// NavigationControllerImpl::PendingEntryRef------------------------------------
593
594NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
595 base::WeakPtr<NavigationControllerImpl> controller)
596 : controller_(controller) {}
597
598NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
599 if (!controller_) // Can be null with interstitials.
600 return;
601
602 controller_->PendingEntryRefDeleted(this);
603}
604
Charlie Reisd3e4fef2025-05-20 02:04:17605// NavigationControllerImpl::ScopedPendingEntryReentrancyGuard------------------
606
607NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
608 ScopedPendingEntryReentrancyGuard(
609 base::SafeRef<NavigationControllerImpl> controller)
610 : controller_(controller) {
611 // Navigations that involve pending entries do not support re-entrancy.
612 // Encountering this CHECK failure means the caller is attempting to start
613 // another navigation while a navigation to an existing pending entry is on
614 // the stack. In most cases, the new navigation should be done from a posted
615 // task instead. See http://crbug.com/40353566 for context.
616 CHECK(!controller->in_navigate_to_pending_entry_);
617
618 controller->in_navigate_to_pending_entry_ = true;
619 controller->CheckPotentialNavigationReentrancy();
620
621 // It must not be possible to delete the pending NavigationEntry while
622 // navigating to it. Grab a reference to delay potential deletion until
623 // this scoped object is deleted at the end of the relevant function call.
624 pending_entry_ref_ = controller->ReferencePendingEntry();
625}
626
627NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
628 ~ScopedPendingEntryReentrancyGuard() {
629 controller_->in_navigate_to_pending_entry_ = false;
630}
631
[email protected]d202a7c2012-01-04 07:53:47632// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29633
[email protected]23a918b2014-07-15 09:51:36634const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23635
[email protected]765b35502008-08-21 00:51:20636// static
[email protected]d202a7c2012-01-04 07:53:47637size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23638 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20639
[email protected]e6fec472013-05-14 05:29:02640// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20641// when testing.
642static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29643
[email protected]71fde352011-12-29 03:29:56644// static
dcheng9bfa5162016-04-09 01:00:57645std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
646 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10647 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37648 std::optional<url::Origin> initiator_origin,
649 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10650 ui::PageTransition transition,
651 bool is_renderer_initiated,
652 const std::string& extra_headers,
653 BrowserContext* browser_context,
654 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
655 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21656 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37657 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32658 is_renderer_initiated, extra_headers, browser_context,
659 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10660}
661
662// static
663std::unique_ptr<NavigationEntryImpl>
664NavigationControllerImpl::CreateNavigationEntry(
665 const GURL& url,
666 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37667 std::optional<url::Origin> initiator_origin,
668 std::optional<GURL> initiator_base_url,
669 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57670 ui::PageTransition transition,
671 bool is_renderer_initiated,
672 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09673 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17674 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
675 bool rewrite_virtual_urls) {
676 GURL url_to_load = url;
677 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56678 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17679 if (rewrite_virtual_urls) {
680 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
681 &reverse_on_redirect);
682 }
Lukasz Anforowicz641234d52019-11-07 21:07:10683 // Let the NTP override the navigation params and pretend that this is a
684 // browser-initiated, bookmark-like navigation.
685 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32686 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21687 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10688
Patrick Monettef507e982019-06-19 20:18:06689 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28690 nullptr, // The site instance for tabs is sent on navigation
691 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21692 url_to_load, referrer, initiator_origin, initiator_base_url,
693 std::u16string(), transition, is_renderer_initiated,
694 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17695 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42696 entry->SetVirtualURL(virtual_url);
697 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56698 entry->set_update_virtual_url_with_url(reverse_on_redirect);
699 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06700 return entry;
[email protected]71fde352011-12-29 03:29:56701}
702
[email protected]cdcb1dee2012-01-04 00:46:20703// static
704void NavigationController::DisablePromptOnRepost() {
705 g_check_for_repost = false;
706}
707
[email protected]c5b88d82012-10-06 17:03:33708base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
709 base::Time t) {
710 // If |t| is between the water marks, we're in a run of duplicates
711 // or just getting out of it, so increase the high-water mark to get
712 // a time that probably hasn't been used before and return it.
713 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35714 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33715 return high_water_mark_;
716 }
717
718 // Otherwise, we're clear of the last duplicate run, so reset the
719 // water marks.
720 low_water_mark_ = high_water_mark_ = t;
721 return t;
722}
723
ckitagawa0faa5e42020-06-17 17:30:54724NavigationControllerImpl::ScopedShowRepostDialogForTesting::
725 ScopedShowRepostDialogForTesting()
726 : was_disallowed_(g_check_for_repost) {
727 g_check_for_repost = true;
728}
729
730NavigationControllerImpl::ScopedShowRepostDialogForTesting::
731 ~ScopedShowRepostDialogForTesting() {
732 g_check_for_repost = was_disallowed_;
733}
734
Nate Chapin9eb16be72022-09-23 22:54:31735NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
736 base::SafeRef<NavigationControllerImpl> controller)
737 : controller_(controller) {
738 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
739 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
740 frame_tree_node_id_to_keys_.insert(
741 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
742 if (auto* frame_entry = frame_tree_node->current_frame_host()
743 ->last_committed_frame_entry()) {
744 frame_tree_node_id_to_doc_seq_nos_.insert(
745 {frame_tree_node->frame_tree_node_id(),
746 frame_entry->document_sequence_number()});
747 }
748 }
749 PopulateKeySet(Direction::kBack);
750 PopulateKeySet(Direction::kForward);
751}
752
753void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
754 Direction direction) {
755 // Keep track of which FrameTreeNodes may still have relevant API keys in
756 // additional FrameNavigationEntries.
757 std::set<FrameTreeNode*> nodes_to_process;
758 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
759 nodes_to_process.insert(node);
760 }
761
762 const int offset = direction == Direction::kForward ? 1 : -1;
763 const int start = direction == Direction::kForward
764 ? controller_->GetLastCommittedEntryIndex()
765 : controller_->GetLastCommittedEntryIndex() - 1;
766 for (int i = start;
767 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
768 i += offset) {
769 std::set<FrameTreeNode*> nodes_to_continue_processing;
770
771 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
772 entry->ForEachFrameEntry([this, &nodes_to_process,
773 &nodes_to_continue_processing,
774 &entry](FrameNavigationEntry* frame_entry) {
775 // Find the |node| that matches |frame_entry|, if any.
776 FrameTreeNode* node = nullptr;
777 if (frame_entry == entry->root_node()->frame_entry) {
778 node = controller_->frame_tree().root();
779 } else {
780 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
781 if (it == names_to_nodes_.end())
782 return;
783 node = it->second;
784 }
785
786 // Skip this node if a previous step determine there are no longer
787 // relevant navigation API keys in this direction.
788 if (nodes_to_process.find(node) == nodes_to_process.end())
789 return;
790
791 // Stop processing |node| if we reach a point where it's cross-origin.
792 // See also PopulateSingleNavigationApiHistoryEntryVector().
793 url::Origin frame_entry_origin =
794 frame_entry->committed_origin().value_or(url::Origin::Resolve(
795 frame_entry->url(),
796 frame_entry->initiator_origin().value_or(url::Origin())));
797 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
798 return;
799
800 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
801 frame_entry->navigation_api_key());
802 // Mark |node| as needing more processing for the next entry.
803 nodes_to_continue_processing.insert(node);
804
805 // Check whether |node| went cross-document. If so, its children are
806 // no longer the same conceptual iframe as the current one, and
807 // should no longer be processed. This check is intentionally done
808 // after processing the current |node|, which may still have relevant
809 // discarded API keys.
810 if (frame_entry->document_sequence_number() !=
811 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50812 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31813 nodes_to_process.erase(descendant);
814 }
815 });
816
817 nodes_to_process.swap(nodes_to_continue_processing);
818 }
819}
820
821NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
822 std::set<std::string> all_keys;
823 // Find all remaining navigation API keys after some entries have been
824 // removed.
825 for (auto& entry : controller_->entries_) {
826 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
827 all_keys.insert(frame_entry->navigation_api_key());
828 });
829 }
830
831 // Notify each frame in the renderer of any disposed navigation API keys.
832 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
833 std::vector<std::string> disposed_keys;
834 for (const auto& key : id_to_keys.second) {
835 if (all_keys.find(key) == all_keys.end())
836 disposed_keys.push_back(key);
837 }
838 if (disposed_keys.empty())
839 continue;
840
841 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
842 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
843 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
844 }
845}
846
[email protected]d202a7c2012-01-04 07:53:47847NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00848 BrowserContext* browser_context,
849 FrameTree& frame_tree,
850 NavigationControllerDelegate* delegate)
851 : frame_tree_(frame_tree),
852 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57853 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22854 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37855 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
856 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37857 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29858}
859
[email protected]d202a7c2012-01-04 07:53:47860NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00861 // The NavigationControllerImpl might be called inside its delegate
862 // destructor. Calling it is not valid anymore.
863 delegate_ = nullptr;
864 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29865}
866
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57867BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55868 return browser_context_;
869}
870
[email protected]d202a7c2012-01-04 07:53:47871void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30872 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36873 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57874 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47875 // Note that it's possible for `entries_` to contain multiple entries at this
876 // point, as Restore() might be called on a NavigationController that is
877 // already used (e.g. due to WebView's restoreState() API), not only for fresh
878 // NavigationControllers. These entries are not cleared to preserve legacy
879 // behavior and also because `pending_entry_` might point to one of the
880 // pre-existing entries. An exception for this is when `entries_` contains
881 // only the initial NavigationEntry, which must be removed.
882
883 // Do not proceed if selected_navigation will be out of bounds for the updated
884 // entries_ list, since it will be assigned to last_committed_entry_index_ and
885 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58886 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47887 // is empty, since there should be no work to do (rather than marking the
888 // existing entries as needing reload). Also consider returning early if the
889 // selected index is -1, which represents a no-committed-entry state.
890 if (selected_navigation < -1 ||
891 selected_navigation >=
892 base::checked_cast<int>(entries->size() + entries_.size())) {
893 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24894 }
Charlie Reis23c26da2022-01-29 00:57:47895
Rakina Zata Amni46087a12022-11-11 08:28:38896 // There will always be at least one entry (new NavigationControllers will
897 // have the initial NavigationEntry).
898 if (selected_navigation == -1)
899 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47900
Rakina Zata Amni46087a12022-11-11 08:28:38901 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
902 // If we are on the initial NavigationEntry, it must be the only entry in
903 // the list. Since it's impossible to do a history navigation to the
904 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
905 // `pending_entry` might be set for a new non-history navigation).
906 // Note that we should not clear `entries_` if `entries` is empty (when
907 // InitialNavigationEntry mode is enabled), since that would leave us
908 // without any NavigationEntry.
909 CHECK_EQ(1, GetEntryCount());
910 CHECK_EQ(-1, pending_entry_index_);
911 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47912 }
[email protected]ce3fa3c2009-04-20 19:55:57913
[email protected]ce3fa3c2009-04-20 19:55:57914 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44915 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03916 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47917 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43918 if (entry->GetURL().is_empty()) {
919 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01920 // persisting the initial NavigationEntry [which is no longer possible but
921 // some old persisted sessions might still contain it] or when the
922 // serializer failed to write the URL because it's too long). Trying to
923 // restore and navigate to an entry with an empty URL will result in
924 // crashes, so change the URL to about:blank. See also
925 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43926 entry->SetURL(GURL(url::kAboutBlankURL));
927 }
dcheng36b6aec92015-12-26 06:16:36928 entries_.push_back(
929 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47930 }
avif16f85a72015-11-13 18:25:03931
932 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
933 // cleared out safely.
934 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57935
936 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36937 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57938}
939
toyoshim6142d96f2016-12-19 09:07:25940void NavigationControllerImpl::Reload(ReloadType reload_type,
941 bool check_for_repost) {
Charlie Reisf4d51f402025-05-23 18:00:49942 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:03943 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
944 (int)reload_type);
945 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
946 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28947 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28948 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32949 int current_index = -1;
950
Carlos IL42b416592019-10-07 23:10:36951 if (entry_replaced_by_post_commit_error_) {
952 // If there is an entry that was replaced by a currently active post-commit
953 // error navigation, this can't be the initial navigation.
954 DCHECK(!IsInitialNavigation());
955 // If the current entry is a post commit error, we reload the entry it
956 // replaced instead. We leave the error entry in place until a commit
957 // replaces it, but the pending entry points to the original entry in the
958 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
959 // case that pending_entry_ != entries_[pending_entry_index_].
960 entry = entry_replaced_by_post_commit_error_.get();
961 current_index = GetCurrentEntryIndex();
962 } else if (IsInitialNavigation() && pending_entry_) {
963 // If we are reloading the initial navigation, just use the current
964 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32965 entry = pending_entry_;
966 // The pending entry might be in entries_ (e.g., after a Clone), so we
967 // should also update the current_index.
968 current_index = pending_entry_index_;
969 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00970 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32971 current_index = GetCurrentEntryIndex();
972 if (current_index != -1) {
creis3da03872015-02-20 21:12:32973 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32974 }
[email protected]979a4bc2013-04-24 01:27:15975 }
[email protected]241db352013-04-22 18:04:05976
[email protected]59167c22013-06-03 18:07:32977 // If we are no where, then we can't reload. TODO(darin): We should add a
978 // CanReload method.
979 if (!entry)
980 return;
981
Rakina Zata Amnif297a802022-01-18 03:53:43982 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
983 // We should never navigate to an existing initial NavigationEntry that is
984 // the initial NavigationEntry for the initial empty document that hasn't
985 // been overridden by the synchronous about:blank commit, to preserve
986 // legacy behavior where trying to reload when the main frame is on the
987 // initial empty document won't result in a navigation. See also
988 // https://crbug.com/1277414.
989 return;
990 }
991
Aran Gilman37d11632019-10-08 23:07:15992 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30993 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07994 // they really want to do this. If they do, the dialog will call us back
995 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57996 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02997
[email protected]106a0812010-03-18 00:15:12998 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57999 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:471000 return;
initial.commit09911bf2008-07-26 23:55:291001 }
Lei Zhang96031532019-10-10 19:05:471002
Wang Huia25efabc2022-09-24 17:27:221003 // Set ReloadType for |entry|.
1004 entry->set_reload_type(reload_type);
1005
Lei Zhang96031532019-10-10 19:05:471006 if (!IsInitialNavigation())
1007 DiscardNonCommittedEntries();
1008
1009 pending_entry_ = entry;
1010 pending_entry_index_ = current_index;
1011 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
1012
Nate Chapin45f620582021-09-30 17:45:431013 // location.reload() goes through BeginNavigation, so all reloads triggered
1014 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:131015 NavigateToExistingPendingEntry(
1016 reload_type,
1017 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371018 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491019 /*navigation_api_key=*/nullptr, actual_navigation_start);
initial.commit09911bf2008-07-26 23:55:291020}
1021
[email protected]d202a7c2012-01-04 07:53:471022void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:481023 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121024}
1025
[email protected]d202a7c2012-01-04 07:53:471026void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:491027 // If the pending reload type has been cleared by another navigation
1028 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:481029 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:491030 return;
[email protected]106a0812010-03-18 00:15:121031 }
Wang Hui96ab1012022-10-11 02:05:491032 Reload(pending_reload_, false);
1033 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121034}
1035
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571036bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:091037 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:111038}
1039
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571040bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:381041 // Check that we're on the initial NavigationEntry and that this is not a
1042 // cloned tab.
1043 return IsInitialNavigation() && GetEntryCount() == 1 &&
1044 GetLastCommittedEntry()->IsInitialEntry() &&
1045 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401046}
1047
Aran Gilman37d11632019-10-08 23:07:151048NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1049 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581050 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031051 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581052}
1053
Adithya Srinivasan9b0c99c2021-08-10 15:19:451054NavigationEntryImpl*
1055NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1056 int nav_entry_id) const {
1057 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1058 if (entry)
1059 return entry;
1060 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521061 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451062 : nullptr;
1063}
1064
W. James MacLeanc07dc41b2022-07-25 18:52:161065void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571066 const url::Origin& origin) {
1067 for (int i = 0; i < GetEntryCount(); i++) {
1068 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161069 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571070 }
1071 if (entry_replaced_by_post_commit_error_) {
1072 // It's possible we could come back to this entry if the error
1073 // page/interstitial goes away.
1074 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161075 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571076 }
W. James MacLean1c40862c2020-04-27 21:05:571077}
1078
avi25764702015-06-23 15:43:371079void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571080 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001081 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371082 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271083 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201084}
1085
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571086NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471087 if (pending_entry_)
1088 return pending_entry_;
1089 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201090}
1091
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571092NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321093 // The pending entry is safe to return for new (non-history), browser-
1094 // initiated navigations. Most renderer-initiated navigations should not
1095 // show the pending entry, to prevent URL spoof attacks.
1096 //
1097 // We make an exception for renderer-initiated navigations in new tabs, as
1098 // long as no other page has tried to access the initial empty document in
1099 // the new tab. If another page modifies this blank page, a URL spoof is
1100 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321101 bool safe_to_show_pending =
1102 pending_entry_ &&
1103 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091104 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321105 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461106 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321107
1108 // Also allow showing the pending entry for history navigations in a new tab,
1109 // such as Ctrl+Back. In this case, no existing page is visible and no one
1110 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151111 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1112 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321113 safe_to_show_pending = true;
1114
1115 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191116 return pending_entry_;
1117 return GetLastCommittedEntry();
1118}
1119
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571120int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201121 if (pending_entry_index_ != -1)
1122 return pending_entry_index_;
1123 return last_committed_entry_index_;
1124}
1125
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571126NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381127 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031128 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201129}
1130
Elad Alon32044f532025-03-04 22:16:031131const NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry()
1132 const {
1133 CHECK_NE(last_committed_entry_index_, -1);
1134 return entries_[last_committed_entry_index_].get();
1135}
1136
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571137bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351138 const std::string& mime_type = frame_tree_->root()
1139 ->current_frame_host()
1140 ->GetPage()
1141 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531142 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1143 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271144 NavigationEntry* visible_entry = GetVisibleEntry();
1145 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391146 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161147}
1148
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571149int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271150 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451151 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271152 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551153 return last_committed_entry_index_;
1154}
1155
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571156int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451157 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291158 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551159 return static_cast<int>(entries_.size());
1160}
1161
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571162NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371163 if (index < 0 || index >= GetEntryCount())
1164 return nullptr;
1165
avif16f85a72015-11-13 18:25:031166 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251167}
1168
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571169NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471170 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201171}
1172
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571173int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461174 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031175}
1176
Arthur Sonzognic686e8f2024-01-11 08:36:371177std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031178 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591179 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1180 return index;
1181 }
Shivani Sharma298d12852019-01-22 20:04:031182 }
Arthur Sonzognic686e8f2024-01-11 08:36:371183 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591184}
1185
1186bool NavigationControllerImpl::CanGoBack() {
1187 return GetIndexForGoBack().has_value();
1188}
1189
Andrew Verge9a71fa22025-08-21 18:43:161190bool NavigationControllerImpl::ShouldEnableBackButton() {
1191 std::optional<int> back_index = GetIndexForGoBack();
1192
1193 if (back_index.has_value()) {
1194 return true;
1195 }
1196
1197 // If we don't have a valid index to go back to, but entries still exist
1198 // behind the current one, that means all of them are skippable. We should
1199 // still show the back button, so the user can long-press/hover to select a
1200 // skippable entry, but clicking the button will do nothing. This also avoids
1201 // changing the button's state if the user interacts with the page and thus
1202 // disables the history manipulation intervention.
1203 if (GetEntryAtOffset(-1)) {
1204 return true;
1205 }
1206
1207 return false;
1208}
1209
Arthur Sonzognic686e8f2024-01-11 08:36:371210std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591211 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1212 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1213 return index;
1214 }
1215 }
Arthur Sonzognic686e8f2024-01-11 08:36:371216 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201217}
1218
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571219bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591220 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201221}
1222
Andrew Verge9a71fa22025-08-21 18:43:161223bool NavigationControllerImpl::ShouldEnableForwardButton() {
1224 std::optional<int> forward_index = GetIndexForGoForward();
1225
1226 if (forward_index.has_value()) {
1227 return true;
1228 }
1229
1230 // If we don't have a valid index to go forward to, but entries still exist
1231 // in front of the current one, that means all of them are skippable. We
1232 // should still show the forward button, so the user can long-press/hover to
1233 // select a skippable entry, but clicking the button will do nothing. This
1234 // also avoids changing the button's state if the user interacts with the page
1235 // and thus disables the history manipulation intervention.
1236 if (GetEntryAtOffset(1)) {
1237 return true;
1238 }
1239
1240 return false;
1241}
1242
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571243bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031244 int index = GetIndexForOffset(offset);
1245 return index >= 0 && index < GetEntryCount();
1246}
1247
Xiaohan Wang7f8052e02022-01-14 18:44:281248#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151249bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151250 if (offset == 0)
1251 return true;
1252 int increment = offset > 0 ? 1 : -1;
1253 int non_skippable_entries = 0;
1254 for (int index = GetIndexForOffset(increment);
1255 index >= 0 && index < GetEntryCount(); index += increment) {
1256 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1257 non_skippable_entries++;
1258
1259 if (non_skippable_entries == std::abs(offset))
1260 return true;
1261 }
1262 return false;
1263}
1264#endif
1265
David Bokanb8e0df02025-05-14 22:03:481266NavigationController::WeakNavigationHandleVector
1267NavigationControllerImpl::GoBack() {
Andrew Verge9a71fa22025-08-21 18:43:161268 if (!CanGoBack()) {
1269 return NavigationController::WeakNavigationHandleVector();
1270 }
1271
Arthur Sonzognic686e8f2024-01-11 08:36:371272 const std::optional<int> target_index = GetIndexForGoBack();
Kevin McNeeedc481c2023-04-27 22:30:581273 CHECK(target_index.has_value());
David Bokanb8e0df02025-05-14 22:03:481274 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201275}
1276
David Bokanb8e0df02025-05-14 22:03:481277NavigationController::WeakNavigationHandleVector
1278NavigationControllerImpl::GoForward() {
Andrew Verge9a71fa22025-08-21 18:43:161279 if (!CanGoForward()) {
1280 return NavigationController::WeakNavigationHandleVector();
1281 }
1282
Shivani Sharma2d5b4b6b2019-01-08 16:07:161283 // Note that at least one entry (the last one) will be non-skippable since
1284 // entries are marked skippable only when they add another entry because of
1285 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371286 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNeeedc481c2023-04-27 22:30:581287 CHECK(target_index.has_value());
David Bokanb8e0df02025-05-14 22:03:481288 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201289}
1290
David Bokanb8e0df02025-05-14 22:03:481291NavigationController::WeakNavigationHandleVector
1292NavigationControllerImpl::GoToIndex(int index) {
1293 std::vector<base::WeakPtr<NavigationRequest>> requests =
1294 GoToIndex(index, /*initiator_rfh=*/nullptr,
1295 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491296 /*navigation_api_key=*/nullptr,
1297 /*actual_navigation_start=*/base::TimeTicks::Now());
David Bokanb8e0df02025-05-14 22:03:481298 std::vector<base::WeakPtr<NavigationHandle>> handles;
1299 std::ranges::move(requests, std::back_inserter(handles));
1300 return handles;
Dave Tapuska8bfd84c2019-03-26 20:47:161301}
1302
William Liu62ae26c2024-08-08 14:28:161303std::vector<base::WeakPtr<NavigationRequest>>
1304NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201305 int index,
1306 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371307 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131308 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491309 const std::string* navigation_api_key,
1310 base::TimeTicks actual_navigation_start) {
sunjian30574a62017-03-21 21:39:441311 TRACE_EVENT0("browser,navigation,benchmark",
1312 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501313 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1314 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1315 entries_.size());
1316 // Indices should have have been validated by the caller.
1317 CHECK_GE(index, 0);
1318 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201319
Rakina Zata Amnif297a802022-01-18 03:53:431320 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1321 // We should never navigate to an existing initial NavigationEntry that is
1322 // the initial NavigationEntry for the initial empty document that hasn't
1323 // been overridden by the synchronous about:blank commit, to preserve
1324 // legacy behavior where trying to reload when the main frame is on the
1325 // initial empty document won't result in a navigation. See also
1326 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161327 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431328 }
1329
[email protected]cbab76d2008-10-13 22:42:471330 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201331
arthursonzogni5c4c202d2017-04-25 23:41:271332 DCHECK_EQ(nullptr, pending_entry_);
1333 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431334
arthursonzogni5c4c202d2017-04-25 23:41:271335 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201336 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271337 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1338 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Charlie Reisf4d51f402025-05-23 18:00:491339 return NavigateToExistingPendingEntry(
1340 ReloadType::NONE, initiator_rfh, soft_navigation_heuristics_task_id,
1341 navigation_api_key, actual_navigation_start);
[email protected]765b35502008-08-21 00:51:201342}
1343
[email protected]d202a7c2012-01-04 07:53:471344void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121345 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031346 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201347 return;
1348
[email protected]9ba14052012-06-22 23:50:031349 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201350}
1351
Nate Chapinbf682fa32022-09-26 22:41:201352void NavigationControllerImpl::GoToOffsetFromRenderer(
1353 int offset,
Yoav Weiss8c573952022-11-17 17:35:131354 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371355 std::optional<blink::scheduler::TaskAttributionId>
Charlie Reisf4d51f402025-05-23 18:00:491356 soft_navigation_heuristics_task_id,
1357 base::TimeTicks actual_navigation_start) {
Nate Chapinbb74c5a52023-07-21 23:13:351358 // Note: This is actually reached in unit tests.
1359 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431360 return;
1361
Nate Chapinbf682fa32022-09-26 22:41:201362 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131363 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491364 /*navigation_api_key=*/nullptr, actual_navigation_start);
Nate Chapin45f620582021-09-30 17:45:431365}
1366
William Liu62ae26c2024-08-08 14:28:161367std::vector<base::WeakPtr<NavigationRequest>>
1368NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271369 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1370 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491371 /*navigation_api_key=*/nullptr,
1372 /*actual_navigation_start=*/base::TimeTicks::Now());
William Liuec04e382024-05-23 18:03:271373}
1374
Xiaohan Wang7f8052e02022-01-14 18:44:281375#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151376void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1377 // Note: This is actually reached in unit tests.
1378 if (!CanGoToOffsetWithSkipping(offset))
1379 return;
1380
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421381 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151382 GoToIndex(GetIndexForOffset(offset));
1383 return;
1384 }
1385 int increment = offset > 0 ? 1 : -1;
1386 // Find the offset without counting skippable entries.
1387 int target_index = GetIndexForOffset(increment);
1388 int non_skippable_entries = 0;
1389 for (int index = target_index; index >= 0 && index < GetEntryCount();
1390 index += increment) {
1391 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1392 non_skippable_entries++;
1393
1394 if (non_skippable_entries == std::abs(offset)) {
1395 target_index = index;
1396 break;
1397 }
1398 }
1399
1400 GoToIndex(target_index);
1401}
1402#endif
1403
[email protected]41374f12013-07-24 02:49:281404bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151405 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281406 return false;
[email protected]6a13a6c2011-12-20 21:47:121407
[email protected]43032342011-03-21 14:10:311408 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281409 return true;
[email protected]cbab76d2008-10-13 22:42:471410}
1411
Michael Thiessen9b14d512019-09-23 21:19:471412void NavigationControllerImpl::PruneForwardEntries() {
1413 DiscardNonCommittedEntries();
1414 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471415 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471416 if (num_removed <= 0)
1417 return;
Nate Chapin9eb16be72022-09-23 22:54:311418 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471419 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1420 NotifyPrunedEntries(this, remove_start_index /* start index */,
1421 num_removed /* count */);
1422}
1423
Aran Gilman37d11632019-10-08 23:07:151424void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1425 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321426 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311427 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511428 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1429 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321430 }
1431}
1432
Harkiran Bolariaba823e42021-05-21 18:30:361433base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1434 const GURL& url,
1435 const Referrer& referrer,
1436 ui::PageTransition transition,
1437 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471438 LoadURLParams params(url);
1439 params.referrer = referrer;
1440 params.transition_type = transition;
1441 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361442 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471443}
1444
Harkiran Bolariaba823e42021-05-21 18:30:361445base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1446 const LoadURLParams& params) {
Charlie Reisf4d51f402025-05-23 18:00:491447 // For now, treat this as the actual navigation start time, even though a fair
1448 // amount of work is done in the browser process between the various ways to
1449 // start a navigation and reaching here (e.g., sending OpenURLParams through
1450 // the embedder and converting them to LoadURLParams). Note that this may be
1451 // used for some renderer-initiated navigations that go through
1452 // RenderFrameHostImpl::OpenURL as well.
1453 // TODO(crbug.com/385170155): Consider whether tracking this earlier work with
1454 // an earlier start time is worthwhile for metrics.
1455 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
1456
Lukasz Anforowicz435bcb582019-07-12 20:50:061457 if (params.is_renderer_initiated)
1458 DCHECK(params.initiator_origin.has_value());
1459
naskob8744d22014-08-28 17:07:431460 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151461 "NavigationControllerImpl::LoadURLWithParams", "url",
1462 params.url.possibly_invalid_spec());
Emmanuel Arias Soto9e159652025-05-16 07:53:551463
1464 if (IsDebugURL(params.url)) {
1465 // Browser-debug URLs won't go through NavigationThrottles so we have to
1466 // check them explicitly. See crbug.com/40605746.
1467 ContentBrowserClient* client = GetContentClient()->browser();
1468 if (client->ShouldBlockRendererDebugURL(
1469 params.url, browser_context_,
1470 GetTargetFrameTreeNodeForNavigation(params)
1471 ->current_frame_host())) {
1472 DiscardPendingEntry(false);
1473 return nullptr;
1474 }
1475 HandleDebugURL(params.url, params.transition_type,
1476 client->IsExplicitNavigation(params.transition_type));
[email protected]47752982014-07-29 08:01:431477 // If Telemetry is running, allow the URL load to proceed as if it's
1478 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491479 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181480 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361481 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181482 }
[email protected]47752982014-07-29 08:01:431483 }
[email protected]8bf1048012012-02-08 01:22:181484
[email protected]cf002332012-08-14 19:17:471485 // Checks based on params.load_type.
1486 switch (params.load_type) {
1487 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431488 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541489#if BUILDFLAG(IS_ANDROID)
1490 case LOAD_TYPE_PDF_ANDROID:
1491#endif
[email protected]cf002332012-08-14 19:17:471492 break;
1493 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261494 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211495 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471496 }
1497 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461498 }
[email protected]e47ae9472011-10-13 19:48:341499
[email protected]e47ae9472011-10-13 19:48:341500 // The user initiated a load, we don't need to reload anymore.
1501 needs_reload_ = false;
1502
Charlie Reisf4d51f402025-05-23 18:00:491503 return NavigateWithoutEntry(params, actual_navigation_start);
[email protected]132e281a2012-07-31 18:32:441504}
1505
Charlie Reis4c53a962023-06-21 23:17:531506void NavigationControllerImpl::LoadOriginalRequestURL() {
1507 // If the original request URL is not valid, matches the current URL, or
1508 // involves POST data, then simply reload. The POST check avoids issues with
1509 // sending data to the wrong page.
1510 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1511 const GURL& original_request_url =
1512 GetLastCommittedEntry()->GetOriginalRequestURL();
1513 if (!original_request_url.is_valid() ||
1514 original_request_url == last_committed_url ||
1515 GetLastCommittedEntry()->GetHasPostData()) {
1516 Reload(ReloadType::NORMAL, true);
1517 return;
1518 }
1519
1520 // Otherwise, attempt to load the original request URL without any of the
1521 // other data from the current NavigationEntry, replacing the current entry.
1522 // Loading the original URL is useful in cases such as modifying the user
1523 // agent.
1524 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1525 std::make_unique<NavigationController::LoadURLParams>(
1526 original_request_url);
1527 load_params->should_replace_current_entry = true;
1528 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1529 LoadURLWithParams(*load_params.get());
1530}
1531
Mohamed Abdelhalim833de902019-09-16 17:41:451532bool NavigationControllerImpl::PendingEntryMatchesRequest(
1533 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191534 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451535 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191536}
1537
[email protected]d202a7c2012-01-04 07:53:471538bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321539 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071540 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331541 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441542 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251543 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561544 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131545 NavigationRequest* navigation_request) {
1546 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331547
1548 // Note: validation checks and renderer kills due to invalid commit messages
1549 // must happen before getting here, in
1550 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1551 // effects of the navigation have already occurred.
1552
[email protected]cd2e15742013-03-08 04:08:311553 is_initial_navigation_ = false;
1554
Wang Hui96ab1012022-10-11 02:05:491555 // Any pending request to repost a form submission is no longer valid, since a
1556 // different NavigationEntry is committing.
1557 pending_reload_ = ReloadType::NONE;
1558
[email protected]0e8db942008-09-24 21:21:481559 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431560 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451561 if (entry_replaced_by_post_commit_error_) {
1562 // Same document navigation events with a post-commit error should already
1563 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1564 // reaching here.
1565 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331566
Xinghui Lub9e86a352024-05-17 16:29:421567 if (pending_entry_) {
1568 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1569 // `pending_entry_` isn't pointing to the last committed entry.
1570 // Instead, all reload approaches (e.g., in `Reload` and
1571 // `LoadIfNecessary`) should attempt to load the
1572 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1573 // entry itself.
1574 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1575 << "Incorrectly reloading the post commit error page entry.";
1576 }
Xinghui Lue4e50be2024-05-15 21:46:001577
Rakina Zata Amnie2d31312022-11-18 03:38:451578 // Any commit while a post-commit error page is showing should put the
1579 // original entry back, replacing the error page's entry. This includes
1580 // reloads, where the original entry was used as the pending entry and
1581 // should now be at the correct index at commit time.
1582 entries_[last_committed_entry_index_] =
1583 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481584 }
Rakina Zata Amnie2d31312022-11-18 03:38:451585 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1586 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001587 // Must honor user agent overrides in the |navigation_request|, such as
1588 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1589 // result, besides comparing |pending_entry_|'s user agent against
1590 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1591 // agent against LastCommittedEntry's.
1592 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541593 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1594 (PendingEntryMatchesRequest(navigation_request) &&
1595 pending_entry_->GetIsOverridingUserAgent() !=
1596 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001597 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451598 }
[email protected]ecd9d8702008-08-28 22:10:171599
Dave Tapuskaa2ab4f252021-07-08 21:31:281600 bool is_main_frame_navigation = !rfh->GetParent();
1601
Dave Tapuskaa2ab4f252021-07-08 21:31:281602 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141603 // BackForwardCacheMetrics to be associated with the new navigation's
1604 // NavigationEntry, by either creating a new object or reusing the previous
1605 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281606 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211607 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141608 back_forward_cache_metrics = BackForwardCacheMetrics::
1609 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281610 GetLastCommittedEntry(), is_main_frame_navigation,
1611 params.document_sequence_number);
1612 }
Yuzu Saijo29f96ca92022-12-08 04:54:121613
Alexander Timind2f2e4f22019-04-02 20:04:531614 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281615 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451616 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1617 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531618 }
1619 }
1620
Rakina Zata Amnifd8370b2022-11-14 13:32:251621 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1622 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091623 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251624 details->did_replace_entry =
1625 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091626
fdegans9caf66a2015-07-30 21:10:421627 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111628 // except for restored entries. This should be true even if the current commit
1629 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291630 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481631 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081632 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111633
1634 // Only make changes based on the pending entry if the NavigationRequest
1635 // matches it. Otherwise, the pending entry may be for a different request
1636 // (e.g., if a slow history navigation is pending while an auto-subframe
1637 // commit occurs).
1638 if (PendingEntryMatchesRequest(navigation_request)) {
1639 // It is no longer necessary to consider the pending entry as restored.
1640 if (pending_entry_->IsRestored()) {
1641 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1642 was_restored = true;
1643 }
[email protected]e9ba4472008-09-14 15:42:431644
Charlie Reisf8cde712022-10-20 16:25:091645 // If the SiteInstance has changed from the matching pending entry, this
1646 // must be treated as a new navigation with replacement. Set the replacement
1647 // bit here and ClassifyNavigation will identify this case and return
1648 // NEW_ENTRY.
1649 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1650 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1651 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251652 // TODO(nasko,creis,rakina): Move this to happen before committing the
1653 // navigation. This is a bit complicated because we don't currently
1654 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091655 details->did_replace_entry = true;
1656 }
Nasko Oskovaee2f862018-06-15 00:05:521657 }
[email protected]bcd904482012-02-01 01:54:221658
[email protected]e9ba4472008-09-14 15:42:431659 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101660 NavigationType navigation_type =
1661 ClassifyNavigation(rfh, params, navigation_request);
1662 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451663
Rakina Zata Amnie2d31312022-11-18 03:38:451664 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451665 // Ensure that this navigation does not add a navigation entry, since
1666 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1667 // beyond the last committed one. Therefore, `should_replace_current_entry`
1668 // should be set, which replaces the current entry, or this should be a
1669 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251670 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331671 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451672 }
1673
Rakina Zata Amnie2d31312022-11-18 03:38:451674 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551675 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241676 // This is a subframe navigation on the initial empty document, which used
1677 // to not have a NavigationEntry to attach to. Now it can attach to the
1678 // initial NavigationEntry, and we must ensure that its NavigationEntry
1679 // will keep the "initial NavigationEntry" status and won't append a new
1680 // NavigationEntry (it should always do replacement instead).
1681 // See also https://crbug.com/1277414.
1682 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551683 // Subframe navigation on initial NavigationEntry must not append a new
1684 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1685 // means every subframe navigation that happens while we're on the initial
1686 // NavigationEntry will always reuse the existing NavigationEntry and
1687 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101688 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1689 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551690 // This is a navigation that modifies the initial NavigationEntry, either
1691 // for a replacement or a reload. The initial NavigationEntry should
1692 // retain its "initial NavigationEntry" status in this case.
1693 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241694 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251695 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1696 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241697 // This is a synchronous about:blank navigation on the main frame, which
1698 // used to not create a NavigationEntry when we have no NavigationEntry on
1699 // FrameTree creation. We now have the initial NavigationEntry and are on
1700 // the initial NavigationEntry. To preserve old behavior, we should still
1701 // keep the "initial" status for the new NavigationEntry that we will
1702 // create for this navigation, so that subframe navigations under the
1703 // synchronously committed about:blank document will never append new
1704 // NavigationEntry, and instead will just reuse the initial
1705 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1706 // See also https://crbug.com/1277414.
1707 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551708 }
1709 }
1710 DCHECK(!details->should_stay_as_initial_entry ||
1711 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201712
eugenebutee08663a2017-04-27 17:43:121713 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441714 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121715
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071716 details->is_prerender_activation =
1717 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241718 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1719 ->GetOutermostMainFrame()
1720 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071721
Peter Boströmd7592132019-01-30 04:50:311722 // Make sure we do not discard the pending entry for a different ongoing
1723 // navigation when a same document commit comes in unexpectedly from the
1724 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1725 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581726 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061727 bool keep_pending_entry =
1728 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101729 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061730 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311731
Miyoung Shin3299cbf2022-11-22 01:41:101732 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061733 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491734 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051735 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561736 previous_document_had_history_intervention_activation,
1737 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431738 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061739 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491740 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1741 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001742 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431743 break;
[email protected]8ff00d72012-10-23 19:12:211744 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471745 RendererDidNavigateNewSubframe(
1746 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561747 previous_document_had_history_intervention_activation,
1748 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431749 break;
[email protected]8ff00d72012-10-23 19:12:211750 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391751 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251752 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001753 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081754 // We don't send a notification about auto-subframe PageState during
1755 // UpdateStateForFrame, since it looks like nothing has changed. Send
1756 // it here at commit time instead.
1757 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431758 return false;
creis59d5a47cb2016-08-24 23:57:191759 }
[email protected]e9ba4472008-09-14 15:42:431760 break;
Aran Gilman37d11632019-10-08 23:07:151761 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211762 NOTREACHED();
[email protected]765b35502008-08-21 00:51:201763 }
1764
[email protected]688aa65c62012-09-28 04:32:221765 // At this point, we know that the navigation has just completed, so
1766 // record the time.
1767 //
1768 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261769 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331770 base::Time timestamp =
1771 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1772 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131773 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221774
Peter Boströmd7592132019-01-30 04:50:311775 // If we aren't keeping the pending entry, there shouldn't be one at this
1776 // point. Clear it again in case any error cases above forgot to do so.
1777 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1778 // been cleared instead of protecting against it.
1779 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551780 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141781
[email protected]e9ba4472008-09-14 15:42:431782 // All committed entries should have nonempty content state so WebKit doesn't
1783 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471784 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321785 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221786 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441787 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141788
Dave Tapuskaa2ab4f252021-07-08 21:31:281789 if (back_forward_cache_metrics &&
1790 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531791 active_entry->set_back_forward_cache_metrics(
1792 std::move(back_forward_cache_metrics));
1793 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281794
1795 // `back_forward_cache_metrics()` may return null as we do not record
1796 // back-forward cache metrics for navigations in non-primary frame trees.
1797 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581798 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141799 // These are both only available from details at this point, so we capture
1800 // them here.
1801 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101802 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141803 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1804 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281805 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1806 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321807 IsBackForwardCacheEnabled() &&
1808 rfh->delegate()->IsBackForwardCacheSupported() &&
1809 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281810 }
naskoc7533512016-05-06 17:01:121811
Charles Reisc0507202017-09-21 00:40:021812 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1813 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1814 // A mismatch can occur if the renderer lies or due to a unique name collision
1815 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121816 FrameNavigationEntry* frame_entry =
1817 active_entry->GetFrameEntry(rfh->frame_tree_node());
Diana Qu21d0c922025-06-25 17:19:081818 if (base::FeatureList::IsEnabled(kCheckSiteInstanceOnHistoryNavigation) &&
Diana Qu1cc5eaf2025-06-21 00:04:271819 frame_entry && frame_entry->site_instance()) {
Diana Qu2d6c85b2025-06-17 01:13:141820 int64_t dsn = navigation_request->frame_entry_document_sequence_number();
1821 if (dsn != -1 && dsn == frame_entry->document_sequence_number()) {
1822 // We CHECK that the SiteInstance matches the one stored in the session
1823 // history's FrameNavigationEntry, if the document sequence number (DSN)
1824 // also matches. This ensures the navigation is committing in the expected
1825 // SiteInstance.
1826 //
1827 // It's okay for the SiteInstance to differ if a cross-document redirect
1828 // occurred — in that case, the DSN in NavigationRequest should be cleared
1829 // (set to -1), and we skip the CHECK.
1830 CHECK(rfh->GetSiteInstance() == frame_entry->site_instance(),
1831 base::NotFatalUntil::M141)
1832 << "Session history navigation committed in a different SiteInstance "
1833 "than intended. "
1834 << "FrameNavigationEntry SiteInstance: "
1835 << frame_entry->site_instance()
1836 << ", Committed RFH SiteInstance: " << rfh->GetSiteInstance()
1837 << ", URL: " << params.url;
1838 }
1839 }
Charles Reisc0507202017-09-21 00:40:021840 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1841 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031842 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081843 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1844 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031845 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201846
1847 // Remember the bindings the renderer process has at this point, so that
1848 // we do not grant this entry additional bindings if we come back to it.
1849 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301850 }
[email protected]132e281a2012-07-31 18:32:441851
[email protected]97d8f0d2013-10-29 16:49:211852 // Once it is committed, we no longer need to track several pieces of state on
1853 // the entry.
naskoc7533512016-05-06 17:01:121854 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131855
[email protected]49bd30e62011-03-22 20:12:591856 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221857 // TODO(creis): This check won't pass for subframes until we create entries
1858 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001859 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421860 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591861
[email protected]e9ba4472008-09-14 15:42:431862 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001863 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001864 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311865 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531866
arthursonzogni7ddc6542021-04-09 09:16:501867 active_entry->SetIsOverridingUserAgent(
1868 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031869
[email protected]93f230e02011-06-01 14:40:001870 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291871
aelias100c9192017-01-13 00:01:431872 if (overriding_user_agent_changed)
1873 delegate_->UpdateOverridingUserAgent();
1874
creis03b48002015-11-04 00:54:561875 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1876 // one knows the latest NavigationEntry it is showing (whether it has
1877 // committed anything in this navigation or not). This allows things like
1878 // state and title updates from RenderFrames to apply to the latest relevant
1879 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381880 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031881 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381882 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431883
1884 if (navigation_request->IsPrerenderedPageActivation()) {
Charlie Reis99b2eba22025-01-31 19:18:571885 BroadcastHistoryIndexAndLength();
Alison Gale47d1537d2024-04-19 21:31:461886 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431887 // is activated. As a result, a "prerenderingchange" event listener sees the
1888 // history.length which is not updated yet. We should guarantee that
Charlie Reis99b2eba22025-01-31 19:18:571889 // history's length and index should be updated before a
Hayato Ito2c8c08d02021-06-23 03:38:431890 // "prerenderingchange" event listener runs. One possible approach is to use
1891 // the same IPC which "prerenderingchange" uses, and propagate history's
Charlie Reis99b2eba22025-01-31 19:18:571892 // length and index together with that.
Hayato Ito2c8c08d02021-06-23 03:38:431893 }
1894
[email protected]e9ba4472008-09-14 15:42:431895 return true;
initial.commit09911bf2008-07-26 23:55:291896}
1897
[email protected]8ff00d72012-10-23 19:12:211898NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321899 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101900 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241901 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591902 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511903 "ClassifyNavigation");
1904
avi7c6f35e2015-05-08 17:52:381905 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241906 // A new entry. We may or may not have a corresponding pending entry, and
1907 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001908 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491909 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061910 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381911 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241912 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511913 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381914 return NAVIGATION_TYPE_NEW_SUBFRAME;
1915 }
1916
Charlie Reisc0f17d2d2021-01-12 18:52:491917 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381918 DCHECK(!params.history_list_was_cleared);
1919
avi39c1edd32015-06-04 20:06:001920 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381921 // All manual subframes would be did_create_new_entry and handled above, so
1922 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081923 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1924 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381925 }
1926
Rakina Zata Amnif6950d552020-11-24 03:26:101927 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1928 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381929 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1930 // create a new page.
1931
Hayato Ito2ae49442021-07-02 02:59:251932 // This main frame navigation is not a history navigation (since
1933 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1934 // reload or a replacement navigation, which will modify the existing entry.
1935 //
Nasko Oskov332593c2018-08-16 17:21:341936 // TODO(nasko): With error page isolation, reloading an existing session
1937 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491938 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341939 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511940 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491941 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061942 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381943 }
1944
Charlie Reisf8cde712022-10-20 16:25:091945 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521946 // If the SiteInstance of the |pending_entry_| does not match the
1947 // SiteInstance that got committed, treat this as a new navigation with
1948 // replacement. This can happen if back/forward/reload encounters a server
1949 // redirect to a different site or an isolated error page gets successfully
1950 // reloaded into a different SiteInstance.
1951 if (pending_entry_->site_instance() &&
1952 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491953 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061954 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521955 }
creis77c9aa32015-09-25 19:59:421956
Nasko Oskovaee2f862018-06-15 00:05:521957 if (pending_entry_index_ == -1) {
1958 // In this case, we have a pending entry for a load of a new URL but Blink
1959 // didn't do a new navigation (params.did_create_new_entry). First check
1960 // to make sure Blink didn't treat a new cross-process navigation as
1961 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161962 // we must treat it as NEW rather than the converted reload case below,
1963 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451964 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161965 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061966 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521967 }
1968
1969 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161970 // We will create a pending entry, but NavigateWithoutEntry will convert
1971 // it to a reload since it's the same page and not create a new entry for
1972 // it. (The user doesn't want to have a new back/forward entry when they
1973 // do this.) Therefore we want to just ignore the pending entry and go
1974 // back to where we were (the "existing entry").
1975 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061976 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521977 }
avi7c6f35e2015-05-08 17:52:381978 }
1979
Rakina Zata Amni153d5702021-09-13 22:48:001980 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381981 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491982 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1983 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161984 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061985 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381986 }
1987
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121988 if (navigation_request->DidEncounterError() &&
1989 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101990 nav_entry_id == failed_pending_entry_id_) {
Charlie Reisb5f39cf2024-11-12 16:55:011991 // If the renderer was going to a pending entry that got cleared because of
1992 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511993 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491994 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061995 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381996 }
1997
Charlie Reisc0f17d2d2021-01-12 18:52:491998 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101999 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:512000 trace_return.traced_value()->SetInteger("existing_entry_index",
2001 existing_entry_index);
avi7c6f35e2015-05-08 17:52:382002 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:442003 // The renderer has committed a navigation to an entry that no longer
2004 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:492005 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:062006 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:382007 }
2008
avi7c6f35e2015-05-08 17:52:382009 // Since we weeded out "new" navigations above, we know this is an existing
2010 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:492011 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:062012 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:382013}
2014
Rakina Zata Amni3460d382021-10-29 00:43:372015void NavigationControllerImpl::UpdateNavigationEntryDetails(
2016 NavigationEntryImpl* entry,
2017 RenderFrameHostImpl* rfh,
2018 const mojom::DidCommitProvisionalLoadParams& params,
2019 NavigationRequest* request,
2020 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:002021 bool is_new_entry,
2022 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:372023 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:172024 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:372025 entry->AddOrUpdateFrameEntry(
2026 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572027 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:372028 rfh->GetSiteInstance(), nullptr, params.url,
2029 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:172030 Referrer(*params.referrer),
2031 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:372032 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:172033 request ? request->GetRedirectChain() : redirects, params.page_state,
2034 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:372035 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:172036 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:212037 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:172038 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:372039
2040 if (rfh->GetParent()) {
2041 // Only modify the NavigationEntry for main frame navigations.
2042 return;
2043 }
2044 if (entry->update_virtual_url_with_url())
2045 UpdateVirtualURLToURL(entry, params.url);
2046 // Don't use the page type from the pending entry. Some interstitial page
2047 // may have set the type to interstitial. Once we commit, however, the page
2048 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:172049 entry->set_page_type((request && request->DidEncounterError())
2050 ? PAGE_TYPE_ERROR
2051 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:432052 if (commit_details && commit_details->should_stay_as_initial_entry) {
2053 // Retain the "initial NavigationEntry" status.
2054 if (request->IsSameDocument()) {
2055 // If this is for a same-document navigation, the NavigationEntry must be
2056 // reused and should already be marked as the initial NavigationEntry.
2057 DCHECK(entry->IsInitialEntry());
2058 } else {
2059 // If this is for a cross-document navigation, it can be caused by a
2060 // renderer-initiated reload, or the synchronous about:blank commit. Mark
2061 // "for synchronous about:blank" in the latter case, and also when it is
2062 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
2063 // is not for a synchronous about:blank commit.
2064 NavigationEntryImpl::InitialNavigationEntryState new_state =
2065 NavigationEntryImpl::InitialNavigationEntryState::
2066 kInitialNotForSynchronousAboutBlank;
2067 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
2068 request->is_synchronous_renderer_commit()) {
2069 new_state = NavigationEntryImpl::InitialNavigationEntryState::
2070 kInitialForSynchronousAboutBlank;
2071 }
2072 entry->set_initial_navigation_entry_state(new_state);
2073 }
2074 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
2075 // Remove the "initial NavigationEntry" status.
2076 entry->set_initial_navigation_entry_state(
2077 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:002078 }
Rakina Zata Amniddf10502022-01-15 02:56:552079
Rakina Zata Amni3460d382021-10-29 00:43:372080 if (is_new_entry) {
2081 // Some properties of the NavigationEntry are only set when the entry is
2082 // new (we aren't reusing it).
2083 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:172084 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:402085 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:012086 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
2087 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:372088 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
2089 } else {
2090 // We are reusing the NavigationEntry. The site instance will normally be
2091 // the same except for a few cases:
2092 // 1) session restore, when no site instance will be assigned or
2093 // 2) redirect, when the site instance is reset.
2094 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
2095 entry->site_instance() == rfh->GetSiteInstance());
2096 }
2097}
2098
Rakina Zata Amniafd3c6582021-11-30 06:19:172099void NavigationControllerImpl::CreateInitialEntry() {
2100 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:032101 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:172102 auto params = mojom::DidCommitProvisionalLoadParams::New();
2103 // The initial NavigationEntry's URL is the empty URL. This preserves the old
2104 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
2105 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:402106 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:172107 params->http_status_code = 0;
2108 params->url_is_unreachable = false;
2109 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:172110 params->post_id = -1;
2111 params->embedding_token = base::UnguessableToken::Create();
2112 params->navigation_token = base::UnguessableToken::Create();
2113 params->did_create_new_entry = true;
2114 params->origin = rfh->GetLastCommittedOrigin();
2115 params->should_update_history = true;
2116 params->item_sequence_number = 0;
2117 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:152118 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:172119 params->transition = is_in_fenced_frame_tree
2120 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
2121 : ui::PAGE_TRANSITION_LINK;
2122 params->referrer = blink::mojom::Referrer::New();
2123
Rakina Zata Amniafd3c6582021-11-30 06:19:172124 auto new_entry = std::make_unique<NavigationEntryImpl>(
2125 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:382126 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:212127 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
2128 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
2129 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172130 UpdateNavigationEntryDetails(
2131 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:002132 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
2133 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172134
2135 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
2136 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:002137 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172138}
2139
Charlie Reisc0f17d2d2021-01-12 18:52:492140void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:322141 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072142 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362143 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442144 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562145 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002146 NavigationRequest* request,
2147 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572148 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372149 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452150 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372151 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522152 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2153 initiator_base_url = request->common_params().initiator_base_url;
2154 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062155
creisf49dfc92016-07-26 17:05:182156 // First check if this is an in-page navigation. If so, clone the current
2157 // entry instead of looking at the pending entry, because the pending entry
2158 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452159 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302160 FrameNavigationEntry* previous_frame_entry =
2161 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452162 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482163 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572164 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082165 rfh->GetSiteInstance(), nullptr, params.url,
2166 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212167 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092168 request->GetRedirectChain(), params.page_state, params.method,
2169 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392170 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302171 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572172 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302173 // FrameNavigationEntry.
2174 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572175 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032176
creisf49dfc92016-07-26 17:05:182177 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032178 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522179 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2180 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572181 // TODO(jam): we had one report of this with a URL that was redirecting to
2182 // only tildes. Until we understand that better, don't copy the cert in
2183 // this case.
2184 new_entry->GetSSL() = SSLStatus();
2185 }
creisf49dfc92016-07-26 17:05:182186
Patrick Monette50e8bd82019-06-13 22:40:452187 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2188 // that |frame_entry| should now have a reference count of exactly 2: one
2189 // due to the local variable |frame_entry|, and another due to |new_entry|
2190 // also retaining one. This should never fail, because it's the main frame.
2191 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182192 }
2193
Harkiran Bolaria59290d62021-03-17 01:53:012194 // If this is an activation navigation from a prerendered page, transfer the
2195 // new entry from an entry already created and stored in the
2196 // NavigationRequest. |new_entry| will not have been set prior to this as
2197 // |is_same_document| is mutually exclusive with
2198 // |IsPrerenderedPageActivation|.
2199 if (request->IsPrerenderedPageActivation()) {
2200 DCHECK(!is_same_document);
2201 DCHECK(!new_entry);
2202 new_entry = request->TakePrerenderNavigationEntry();
2203 DCHECK(new_entry);
2204 }
2205
Charlie Reisc0f17d2d2021-01-12 18:52:492206 // Only make a copy of the pending entry if it is appropriate for the new
2207 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452208 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042209 // 1. The SiteInstance hasn't been assigned to something else.
2210 // 2. The pending entry was intended as a new entry, rather than being a
2211 // history navigation that was interrupted by an unrelated,
2212 // renderer-initiated navigation.
2213 // TODO(csharrison): Investigate whether we can remove some of the coarser
2214 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452215 if (!new_entry && PendingEntryMatchesRequest(request) &&
2216 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342217 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432218 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352219 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432220
Camille Lamy62b826012019-02-26 09:15:472221 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452222 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182223 }
2224
Charlie Reisc0f17d2d2021-01-12 18:52:492225 // For cross-document commits with no matching pending entry, create a new
2226 // entry.
creisf49dfc92016-07-26 17:05:182227 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062228 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072229 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212230 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582231 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452232 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172233 nullptr, // blob_url_loader_factory
2234 false); // is_initial_entry
[email protected]f8f93eb22012-09-25 03:06:242235
2236 // Find out whether the new entry needs to update its virtual URL on URL
2237 // change and set up the entry accordingly. This is needed to correctly
2238 // update the virtual URL when replaceState is called after a pushState.
2239 GURL url = params.url;
2240 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492241 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412242 // update the virtual URL based on the new URL. For example, this is needed
2243 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2244 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372245 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2246 &url, browser_context_, &needs_update);
2247 new_entry->set_update_virtual_url_with_url(needs_update);
2248
Camille Lamy62b826012019-02-26 09:15:472249 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452250 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432251 }
2252
Alison Gale770f3fc2024-04-27 00:39:582253 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2254 // set for prerendered contents, if any. This is because
2255 // prerendering/activation technically won't be creating a new document.
2256 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2257 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012258 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372259 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2260 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002261 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082262
Harkiran Bolaria59290d62021-03-17 01:53:012263 // history.pushState() is classified as a navigation to a new page, but sets
2264 // is_same_document to true. In this case, we already have the title and
2265 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452266 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012267 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2268 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2269 }
[email protected]3a868f212014-08-09 10:41:192270 }
[email protected]ff64b3e2014-05-31 04:07:332271
[email protected]60d6cca2013-04-30 08:47:132272 DCHECK(!params.history_list_was_cleared || !replace_entry);
2273 // The browser requested to clear the session history when it initiated the
2274 // navigation. Now we know that the renderer has updated its state accordingly
2275 // and it is safe to also clear the browser side history.
2276 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552277 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132278 entries_.clear();
2279 last_committed_entry_index_ = -1;
2280 }
2281
Nasko Oskovaee2f862018-06-15 00:05:522282 // If this is a new navigation with replacement and there is a
2283 // pending_entry_ which matches the navigation reported by the renderer
2284 // process, then it should be the one replaced, so update the
2285 // last_committed_entry_index_ to use it.
2286 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092287 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522288 last_committed_entry_index_ = pending_entry_index_;
2289 }
2290
Alexander Timine3ec4192020-04-20 16:39:402291 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562292 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402293 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052294
Yuzu Saijoa725585f2022-11-28 04:14:032295 // If this is a history navigation and the old entry has an existing
2296 // back/forward cache metrics object, keep using the old one so that the
2297 // reasons logged from the last time the page navigated gets preserved.
2298 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2299 request)) {
2300 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2301 // because some tests do not have a pending entry.
2302 NavigationEntryImpl* entry =
2303 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2304 if (entry && entry->back_forward_cache_metrics()) {
2305 scoped_refptr<BackForwardCacheMetrics> metrics =
2306 entry->TakeBackForwardCacheMetrics();
2307 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2308 }
2309 }
2310
Andrew Verge754c70a2025-04-17 17:19:192311 bool was_post_commit_error =
2312 request->browser_initiated_error_navigation_type() ==
2313 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit;
2314
Carlos IL42b416592019-10-07 23:10:362315 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Andrew Verge754c70a2025-04-17 17:19:192316 was_post_commit_error, rfh->IsNestedWithinFencedFrame(),
2317 commit_details);
[email protected]e9ba4472008-09-14 15:42:432318}
2319
Charlie Reisc0f17d2d2021-01-12 18:52:492320void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322321 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072322 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362323 bool is_same_document,
jam48cea9082017-02-15 06:13:292324 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452325 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002326 bool keep_pending_entry,
2327 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562328 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2329 << "that a last committed entry exists.";
2330
[email protected]e9ba4472008-09-14 15:42:432331 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002332 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432333
Charlie Reis7e2cb6d2021-01-26 01:27:162334 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002335 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162336 // We're guaranteed to have a last committed entry if intended_as_new_entry
2337 // is true.
avicbdc4c12015-07-01 16:07:112338 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162339
2340 // If the NavigationRequest matches a new pending entry and is classified as
2341 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2342 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092343 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162344 // Note: The pending entry will usually have a real ReloadType here, but
2345 // it can still be ReloadType::NONE in cases that
2346 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2347
2348 // If we classified this correctly, the SiteInstance should not have
2349 // changed.
2350 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2351
2352 // For converted reloads, we assign the entry's unique ID to be that of
2353 // the new one. Since this is always the result of a user action, we want
2354 // to dismiss infobars, etc. like a regular user-initiated navigation.
2355 entry->set_unique_id(pending_entry_->GetUniqueID());
2356
2357 // The extra headers may have changed due to reloading with different
2358 // headers.
2359 entry->set_extra_headers(pending_entry_->extra_headers());
2360 }
2361 // Otherwise, this was intended as a new entry but the pending entry was
2362 // lost in the meantime and no new entry was created. We are stuck at the
2363 // last committed entry.
2364
2365 // Even if this is a converted reload from pressing enter in the omnibox,
2366 // the server could redirect, requiring an update to the SSL status. If this
2367 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452368 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162369 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472370 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452371 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162372 }
Rakina Zata Amnif6950d552020-11-24 03:26:102373 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112374 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102375 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b90ce2016-09-01 16:58:162376
eugenebut604866f2017-05-10 21:35:362377 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452378 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362379 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2380 // this was a restored same document navigation entry, then it won't have
2381 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2382 // navigated it.
jam48cea9082017-02-15 06:13:292383 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522384 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2385 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292386 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2387 was_restored) {
2388 entry->GetSSL() = last_entry->GetSSL();
2389 }
2390 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452391 // In rapid back/forward navigations |request| sometimes won't have a cert
2392 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192393 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452394 if (request->GetSSLInfo().has_value() &&
2395 request->GetSSLInfo()->is_valid()) {
2396 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522397 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2398 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192399 entry->GetSSL() = SSLStatus();
2400 }
jam48cea9082017-02-15 06:13:292401 }
avicbdc4c12015-07-01 16:07:112402 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272403 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572404 // navigations that are EXISTING_ENTRY are same-document navigations that
2405 // result in replacement (e.g. history.replaceState(), location.replace(),
2406 // forced replacements for trivial session history contexts). For these
2407 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112408 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102409
Alison Gale81f4f2c72024-04-22 19:33:312410 // TODO(crbug.com/40532777): Set page transition type to
2411 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2412 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2413 // well as to fix the inconsistency with what we report to observers
2414 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102415
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572416 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102417
eugenebut604866f2017-05-10 21:35:362418 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452419 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362420 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472421 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452422 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112423 }
2424 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432425
Rakina Zata Amni3460d382021-10-29 00:43:372426 UpdateNavigationEntryDetails(entry, rfh, params, request,
2427 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002428 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302429
[email protected]5ccd4dc2012-10-24 02:28:142430 // The redirected to page should not inherit the favicon from the previous
2431 // page.
eugenebut604866f2017-05-10 21:35:362432 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482433 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142434
Charlie Reis951f43372023-05-05 00:30:072435 // Update the last committed index to reflect the committed entry. Do this
2436 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2437 // delegate sees the correct committed index when notified of navigation
2438 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2439 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212440 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072441
Peter Boströmd7592132019-01-30 04:50:312442 // We should also usually discard the pending entry if it corresponds to a
2443 // different navigation, since that one is now likely canceled. In rare
2444 // cases, we leave the pending entry for another navigation in place when we
2445 // know it is still ongoing, to avoid a flicker in the omnibox (see
2446 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432447 //
2448 // Note that we need to use the "internal" version since we don't want to
2449 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312450 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002451 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432452}
2453
[email protected]d202a7c2012-01-04 07:53:472454void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322455 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072456 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362457 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472458 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562459 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002460 NavigationRequest* request,
2461 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262462 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2463 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552464 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2465 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112466
[email protected]e9ba4472008-09-14 15:42:432467 // Manual subframe navigations just get the current entry cloned so the user
2468 // can go back or forward to it. The actual subframe information will be
2469 // stored in the page state for each of those entries. This happens out of
2470 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092471 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2472 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382473
Mikel Astizba9cf2fd2017-12-17 10:38:102474 // The DCHECK below documents the fact that we don't know of any situation
2475 // where |replace_entry| is true for subframe navigations. This simplifies
2476 // reasoning about the replacement struct for subframes (see
2477 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2478 DCHECK(!replace_entry);
2479
Patrick Monette50e8bd82019-06-13 22:40:452480 // This FrameNavigationEntry might not end up being used in the
2481 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372482 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452483 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372484 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522485 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2486 initiator_base_url = request->common_params().initiator_base_url;
2487 }
Nate Chapin63db0d12022-01-20 22:03:302488 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2489 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212490 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302491 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572492 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302493 if (is_same_document) {
2494 FrameNavigationEntry* previous_frame_entry =
2495 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572496 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302497 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572498 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302499 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572500 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302501 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572502 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302503 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572504 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302505 policy_container_policies->referrer_policy);
2506 }
2507
Patrick Monette50e8bd82019-06-13 22:40:452508 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482509 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572510 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082511 rfh->GetSiteInstance(), nullptr, params.url,
2512 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212513 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2514 request->GetRedirectChain(), params.page_state, params.method,
2515 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572516 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032517
creisce0ef3572017-01-26 17:53:082518 std::unique_ptr<NavigationEntryImpl> new_entry =
2519 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452520 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032521 frame_tree_->root());
creise062d542015-08-25 02:01:552522
Alexander Timine3ec4192020-04-20 16:39:402523 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562524 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402525 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472526
creisce0ef3572017-01-26 17:53:082527 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452528 // to replace, which can happen due to a unique name change. See
2529 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2530 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382531
Dave Tapuska87696ae2021-11-18 18:48:312532 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152533 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432534}
2535
[email protected]d202a7c2012-01-04 07:53:472536bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322537 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072538 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392539 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252540 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002541 NavigationRequest* request,
2542 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292543 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2544 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2545
[email protected]e9ba4472008-09-14 15:42:432546 // We're guaranteed to have a previously committed entry, and we now need to
2547 // handle navigation inside of a subframe in it without creating a new entry.
2548 DCHECK(GetLastCommittedEntry());
2549
creis913c63ce2016-07-16 19:52:522550 // For newly created subframes, we don't need to send a commit notification.
2551 // This is only necessary for history navigations in subframes.
2552 bool send_commit_notification = false;
2553
Rakina Zata Amnif6950d552020-11-24 03:26:102554 // If |nav_entry_id| is non-zero and matches an existing entry, this
2555 // is a history navigation. Update the last committed index accordingly. If
2556 // we don't recognize the |nav_entry_id|, it might be a recently
2557 // pruned entry. We'll handle it below.
2558 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2559 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472560 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062561 // Make sure that a subframe commit isn't changing the main frame's
2562 // origin. Otherwise the renderer process may be confused, leading to a
2563 // URL spoof. We can't check the path since that may change
2564 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572565 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2566 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242567 // We should use checks similar to RenderFrameHostImpl's
2568 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2569 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572570 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2571 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2572 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2573 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522574 current_top_url.DeprecatedGetOriginAsURL() !=
2575 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442576 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512577 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062578 }
creis3cdc3b02015-05-29 23:00:472579
creis913c63ce2016-07-16 19:52:522580 // We only need to discard the pending entry in this history navigation
2581 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062582 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002583 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522584
2585 // History navigations should send a commit notification.
2586 send_commit_notification = true;
avi98405c22015-05-21 20:47:062587 }
[email protected]e9ba4472008-09-14 15:42:432588 }
[email protected]f233e4232013-02-23 00:55:142589
creisce0ef3572017-01-26 17:53:082590 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2591 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372592 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2593 // exists), or we may want to clobber it and create a new one. We update in
2594 // cases where the corresponding FrameNavigationEntry is conceptually similar
2595 // to the document described by the commit params: same-document
2596 // navigations, history traversal to an existing entry, and reloads (including
2597 // a "soft reload" where we navigate to the same url without flagging it as a
2598 // reload). But in the case of a different document that is not logically
2599 // related to the committed FrameNavigationEntry's document (cross-document,
2600 // not same url, not a reload, not a history traversal), we replace rather
2601 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252602 //
Nate Chapin9f169072021-06-09 19:32:372603 // In the case where we update, the FrameNavigationEntry will potentially be
2604 // shared across multiple NavigationEntries, and any updates will be reflected
2605 // in all of those NavigationEntries. In the replace case, any existing
2606 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252607 //
2608 // When navigating away from the initial empty document, we also update rather
2609 // than replace. Either update or replace will overwrite the initial empty
2610 // document state for |last_committed|, but if the FrameNavigationEntry for
2611 // the initial empty document is shared across multiple NavigationEntries (due
2612 // to a navigation in another frame), we want to make sure we overwrite the
2613 // initial empty document state everywhere this FrameNavigationEntry is used,
2614 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452615 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372616 FrameNavigationEntry* last_committed_frame_entry =
2617 last_committed->GetFrameEntry(rfh->frame_tree_node());
2618 NavigationEntryImpl::UpdatePolicy update_policy =
2619 NavigationEntryImpl::UpdatePolicy::kUpdate;
2620 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312621 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372622 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252623 last_committed_frame_entry->url() != params.url &&
2624 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372625 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2626 }
2627
Rakina Zata Amni3460d382021-10-29 00:43:372628 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002629 update_policy, false /* is_new_entry */,
2630 commit_details);
creis625a0c7d2015-03-24 23:17:122631
creis913c63ce2016-07-16 19:52:522632 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432633}
2634
[email protected]d202a7c2012-01-04 07:53:472635int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232636 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032637 for (size_t i = 0; i < entries_.size(); ++i) {
2638 if (entries_[i].get() == entry)
2639 return i;
2640 }
2641 return -1;
[email protected]765b35502008-08-21 00:51:202642}
2643
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572644void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242645 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572646 NavigationControllerImpl* source =
2647 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572648 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382649 DCHECK_EQ(1, GetEntryCount());
2650 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472651 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172652 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572653
Francois Dorayeaace782017-06-21 16:37:242654 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442655 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572656 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572657
Fergal Dalya1d569972021-03-16 03:24:532658 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302659 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532660 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2661 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302662 }
[email protected]4e6419c2010-01-15 04:50:342663
Lukasz Anforowicz0de0f452020-12-02 19:57:152664 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572665}
2666
[email protected]79368982013-11-13 01:11:012667bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022668 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162669 if (last_committed_entry_index_ == -1)
2670 return false;
[email protected]9350602e2013-02-26 23:27:442671
[email protected]474f8512013-05-31 22:31:162672 // We cannot prune if there is a pending entry at an existing entry index.
2673 // It may not commit, so we have to keep the last committed entry, and thus
2674 // there is no sensible place to keep the pending entry. It is ok to have
2675 // a new pending entry, which can optionally commit as a new navigation.
2676 if (pending_entry_index_ != -1)
2677 return false;
2678
[email protected]474f8512013-05-31 22:31:162679 return true;
2680}
2681
[email protected]79368982013-11-13 01:11:012682void NavigationControllerImpl::PruneAllButLastCommitted() {
2683 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162684
avi2b177592014-12-10 02:08:022685 DCHECK_EQ(0, last_committed_entry_index_);
2686 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442687
Charlie Reis99b2eba22025-01-31 19:18:572688 BroadcastHistoryIndexAndLength();
[email protected]9350602e2013-02-26 23:27:442689}
2690
[email protected]79368982013-11-13 01:11:012691void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162692 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012693 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262694
Nate Chapin9eb16be72022-09-23 22:54:312695 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2696
[email protected]474f8512013-05-31 22:31:162697 // Erase all entries but the last committed entry. There may still be a
2698 // new pending entry after this.
2699 entries_.erase(entries_.begin(),
2700 entries_.begin() + last_committed_entry_index_);
2701 entries_.erase(entries_.begin() + 1, entries_.end());
2702 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262703}
2704
Christian Dullweber1af31e62018-02-22 11:49:482705void NavigationControllerImpl::DeleteNavigationEntries(
2706 const DeletionPredicate& deletionPredicate) {
2707 // It is up to callers to check the invariants before calling this.
2708 CHECK(CanPruneAllButLastCommitted());
2709 std::vector<int> delete_indices;
2710 for (size_t i = 0; i < entries_.size(); i++) {
2711 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572712 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482713 delete_indices.push_back(i);
2714 }
2715 }
2716 if (delete_indices.empty())
2717 return;
2718
2719 if (delete_indices.size() == GetEntryCount() - 1U) {
2720 PruneAllButLastCommitted();
2721 } else {
2722 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382723 for (const auto& index : base::Reversed(delete_indices)) {
2724 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482725 }
Charlie Reis99b2eba22025-01-31 19:18:572726 BroadcastHistoryIndexAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482727 }
2728 delegate()->NotifyNavigationEntriesDeleted();
2729}
2730
Carlos Caballero35ce710c2019-09-19 10:59:452731BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2732 return back_forward_cache_;
2733}
2734
William Liu055a3542023-04-02 17:21:192735NavigationEntryScreenshotCache*
2736NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212737 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262738 if (!nav_entry_screenshot_cache_ &&
2739 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192740 nav_entry_screenshot_cache_ =
2741 std::make_unique<NavigationEntryScreenshotCache>(
2742 BrowserContextImpl::From(browser_context_)
2743 ->GetNavigationEntryScreenshotManager()
2744 ->GetSafeRef(),
2745 this);
2746 }
2747 return nav_entry_screenshot_cache_.get();
2748}
2749
clamy987a3752018-05-03 17:36:262750void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2751 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2752 // progress, since this will cause a use-after-free. (We only allow this
2753 // when the tab is being destroyed for shutdown, since it won't return to
2754 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032755 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
Minoru Chikamune13ab4de2025-05-14 21:54:072756 // If `was_failure` is true, it means that the pending entry was discarded by
2757 // a `PendingEntryRefDeleted` call within `OnRequestFailedInternal`, in
2758 // response to a navigation request failure. This case is not at risk for
2759 // re-entrancy when `can_be_in_navigate_to_pending_entry_` is true, because
2760 // that code also creates another `PendingEntryRef` that would prevent the
2761 // `DiscardPendingEntry` call if the PostTask were skipped. See
2762 // https://crbug.com/411855273.
2763 if (!was_failure && can_be_in_navigate_to_pending_entry_ &&
Minoru Chikamune646eba42025-04-14 01:25:032764 !frame_tree_->IsBeingDestroyed()) {
2765 CheckPotentialNavigationReentrancy();
2766 }
clamy987a3752018-05-03 17:36:262767
2768 if (was_failure && pending_entry_) {
2769 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2770 } else {
2771 failed_pending_entry_id_ = 0;
2772 }
2773
2774 if (pending_entry_) {
2775 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332776 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262777 pending_entry_index_ = -1;
2778 pending_entry_ = nullptr;
2779 }
arthursonzogni66f711c2019-10-08 14:40:362780
2781 // Ensure any refs to the current pending entry are ignored if they get
2782 // deleted, by clearing the set of known refs. All future pending entries will
2783 // only be affected by new refs.
2784 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262785}
2786
2787void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2788 if (pending_entry_)
2789 pending_entry_->set_ssl_error(error);
2790}
2791
Xiaohan Wang7f8052e02022-01-14 18:44:282792#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422793// static
2794bool NavigationControllerImpl::ValidateDataURLAsString(
2795 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2796 if (!data_url_as_string)
2797 return false;
2798
Avi Drissman0e962522025-08-01 17:42:232799 if (data_url_as_string->size() >
2800 kMaxLengthOfDataURLString.InBytesUnsigned()) {
Camille Lamy5193caa2018-10-12 11:59:422801 return false;
Avi Drissman0e962522025-08-01 17:42:232802 }
Camille Lamy5193caa2018-10-12 11:59:422803
2804 // The number of characters that is enough for validating a data: URI.
2805 // From the GURL's POV, the only important part here is scheme, it doesn't
2806 // check the actual content. Thus we can take only the prefix of the url, to
2807 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562808 constexpr size_t kDataUriPrefixMaxLen = 64;
2809 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2810 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422811 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2812 return false;
2813
2814 return true;
2815}
2816#endif
2817
Shivani Sharma194877032019-03-07 17:52:472818void NavigationControllerImpl::NotifyUserActivation() {
2819 // When a user activation occurs, ensure that all adjacent entries for the
2820 // same document clear their skippable bit, so that the history manipulation
2821 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012822 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172823 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012824 // If the value of CanGoBack changes as a result of making some entries
2825 // non-skippable, then we must let the delegate know to update its UI state.
2826 // See https://crbug.com/1477784.
2827 if (!can_go_back && CanGoBack()) {
2828 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2829 }
Shivani Sharma194877032019-03-07 17:52:472830}
2831
clamy987a3752018-05-03 17:36:262832bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2833 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332834 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2835 blink::LocalFrameToken initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492836 int initiator_process_id,
2837 base::TimeTicks actual_navigation_start) {
clamy987a3752018-05-03 17:36:262838 NavigationEntryImpl* entry =
2839 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2840 if (!entry)
2841 return false;
2842
2843 FrameNavigationEntry* frame_entry =
2844 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2845 if (!frame_entry)
2846 return false;
2847
Camille Lamy5193caa2018-10-12 11:59:422848 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572849 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232850 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332851 true /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492852 initiator_process_id, actual_navigation_start);
clamyea99ea12018-05-28 13:54:232853
2854 if (!request)
2855 return false;
2856
arthursonzognif046d4a2019-12-12 19:08:102857 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412858
Rakina Zata Amni1c83b082023-02-08 01:09:002859 SCOPED_CRASH_KEY_STRING256(
2860 "Bug1400009", "req_url",
2861 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2862 SCOPED_CRASH_KEY_NUMBER(
2863 "Bug1400009", "nav_entry_si",
2864 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2865 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2866 frame_entry->site_instance()
2867 ? ((int)frame_entry->site_instance()->GetId())
2868 : -1);
2869 bool has_sig =
2870 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2871 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2872 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2873 has_sig ? (!!frame_tree_->GetRenderViewHost(
2874 frame_entry->site_instance()->group()))
2875 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052876 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2877 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232878
2879 return true;
clamy987a3752018-05-03 17:36:262880}
2881
Tsuyoshi Horo52fd08e2020-07-07 07:03:452882bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
Charlie Reisf4d51f402025-05-23 18:00:492883 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Tsuyoshi Horo52fd08e2020-07-07 07:03:452884 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2885 if (!entry)
2886 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432887
2888 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2889 // We should never navigate to an existing initial NavigationEntry that is
2890 // the initial NavigationEntry for the initial empty document that hasn't
2891 // been overridden by the synchronous about:blank commit, to preserve
2892 // legacy behavior where trying to reload when the main frame is on the
2893 // initial empty document won't result in a navigation. See also
2894 // https://crbug.com/1277414.
2895 return false;
2896 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452897 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2898 if (!frame_entry)
2899 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142900 ReloadType reload_type = ReloadType::NORMAL;
2901 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452902 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142903 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452904 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432905 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372906 std::nullopt /* initiator_frame_token */,
Charlie Reisf4d51f402025-05-23 18:00:492907 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
2908 actual_navigation_start);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452909 if (!request)
2910 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052911 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452912 return true;
2913}
2914
clamy987a3752018-05-03 17:36:262915void NavigationControllerImpl::NavigateFromFrameProxy(
2916 RenderFrameHostImpl* render_frame_host,
2917 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022918 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452919 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372920 const std::optional<url::Origin>& initiator_origin,
2921 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262922 bool is_renderer_initiated,
2923 SiteInstance* source_site_instance,
2924 const Referrer& referrer,
2925 ui::PageTransition page_transition,
2926 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252927 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262928 const std::string& method,
2929 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092930 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142931 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212932 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502933 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372934 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292935 blink::mojom::NavigationInitiatorActivationAndAdStatus
2936 initiator_activation_and_ad_status,
Charlie Reise1d9b8182025-04-02 04:32:122937 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:222938 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492939 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462940 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452941 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582942 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032943 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342944 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372945 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582946 if (is_renderer_initiated)
2947 DCHECK(initiator_origin.has_value());
2948
clamy987a3752018-05-03 17:36:262949 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582950
Rakina Zata Amni2322f4f82022-01-24 13:24:242951 // Don't allow an entry replacement if there is no entry to replace.
2952 // http://crbug.com/457149
2953 if (GetEntryCount() == 0)
2954 should_replace_current_entry = false;
2955
clamy987a3752018-05-03 17:36:262956 // Create a NavigationEntry for the transfer, without making it the pending
2957 // entry. Subframe transfers should have a clone of the last committed entry
2958 // with a FrameNavigationEntry for the target frame. Main frame transfers
2959 // should have a new NavigationEntry.
2960 // TODO(creis): Make this unnecessary by creating (and validating) the params
2961 // directly, passing them to the destination RenderFrameHost. See
2962 // https://crbug.com/536906.
2963 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262964 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262965 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452966 DCHECK(GetLastCommittedEntry());
2967 entry = GetLastCommittedEntry()->Clone();
2968 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172969 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2970 // Renderer-initiated navigation that target a remote frame are currently
2971 // classified as browser-initiated when this one has already navigated.
2972 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372973 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2974 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2975 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2976 // same-document navigation), they will still be present in the
2977 // committed NavigationEntry that will be referenced to construct the new
2978 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262979 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082980 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582981 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372982 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212983 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152984 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262985 } else {
2986 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172987 // If `node` is the outermost main frame, it rewrites a virtual url in order
2988 // to adjust the original input url if needed. For inner frames such as
2989 // fenced frames or subframes, they don't rewrite urls as the urls are not
2990 // input urls by users.
2991 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372992 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322993 if (source_site_instance && source_site_instance->HasProcess()) {
2994 source_process_site_url =
2995 source_site_instance->GetProcess()->GetProcessLock().site_url();
2996 }
clamy987a3752018-05-03 17:36:262997 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212998 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322999 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:213000 extra_headers, browser_context_, blob_url_loader_factory,
3001 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:263002 entry->root_node()->frame_entry->set_source_site_instance(
3003 static_cast<SiteInstanceImpl*>(source_site_instance));
3004 entry->root_node()->frame_entry->set_method(method);
3005 }
clamy987a3752018-05-03 17:36:263006
Camille Lamy5193caa2018-10-12 11:59:423007 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:453008 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:263009 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:423010 override_user_agent = true;
clamy987a3752018-05-03 17:36:263011 }
3012 // TODO(creis): Set user gesture and intent received timestamp on Android.
3013
3014 // We may not have successfully added the FrameNavigationEntry to |entry|
3015 // above (per https://crbug.com/608402), in which case we create it from
3016 // scratch. This works because we do not depend on |frame_entry| being inside
3017 // |entry| during NavigateToEntry. This will go away when we shortcut this
3018 // further in https://crbug.com/536906.
3019 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
3020 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:453021 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:083022 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:583023 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:373024 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213025 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:153026 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:573027 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:263028 }
3029
Camille Lamy5193caa2018-10-12 11:59:423030 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:023031 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:453032 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:293033 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:213034 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:423035 params.source_site_instance = source_site_instance;
3036 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
3037 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:033038 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:423039 params.referrer = referrer;
3040 /* params.redirect_chain: skip */
3041 params.extra_headers = extra_headers;
3042 params.is_renderer_initiated = is_renderer_initiated;
3043 params.override_user_agent = UA_OVERRIDE_INHERIT;
3044 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:543045 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:423046 /* params.data_url_as_string: skip */
3047 params.post_data = post_body;
3048 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:583049 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:423050 /* params.frame_name: skip */
3051 // TODO(clamy): See if user gesture should be propagated to this function.
3052 params.has_user_gesture = false;
3053 params.should_clear_history_list = false;
3054 params.started_from_context_menu = false;
3055 /* params.navigation_ui_data: skip */
3056 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:223057 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:543058 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:213059 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:413060 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:503061 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:293062 params.initiator_activation_and_ad_status =
3063 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:033064 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:423065
3066 std::unique_ptr<NavigationRequest> request =
3067 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:033068 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143069 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:393070 ReloadType::NONE, entry.get(), frame_entry.get(),
Charlie Reise1d9b8182025-04-02 04:32:123071 actual_navigation_start_time, navigation_start_time,
3072 is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583073 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343074 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:233075
3076 if (!request)
3077 return;
3078
Garrett Tanzerbb8db412022-09-27 21:59:463079 // Force the navigation to take place in a new browsing instance.
3080 // This is used by _unfencedTop in fenced frames to ensure that navigations
3081 // leaving the fenced context create a new browsing instance.
3082 if (force_new_browsing_instance) {
3083 request->coop_status().ForceBrowsingInstanceSwap();
3084 }
3085
Arthur Hemery948742762019-09-18 10:06:243086 // At this stage we are proceeding with this navigation. If this was renderer
3087 // initiated with user gesture, we need to make sure we clear up potential
3088 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
3089 DiscardNonCommittedEntries();
3090
Lukasz Anforowicz9ee83c272020-12-01 20:14:053091 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:263092}
3093
[email protected]d1198fd2012-08-13 22:50:193094void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253095 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:213096 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:193097 if (!session_storage_namespace)
3098 return;
3099
3100 // We can't overwrite an existing SessionStorage without violating spec.
3101 // Attempts to do so may give a tab access to another tab's session storage
3102 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:153103 bool successful_insert =
3104 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:253105 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:053106 static_cast<SessionStorageNamespaceImpl*>(
3107 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:303108 .second;
3109 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:193110}
3111
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573112bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:453113 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:033114 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:463115}
3116
Aran Gilman37d11632019-10-08 23:07:153117SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253118 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:303119 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:253120 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:033121 DOMStorageContextWrapper* context_wrapper =
3122 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
3123
3124 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:253125 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:033126 if (it != session_storage_namespace_map_.end()) {
3127 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:153128 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
3129 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:473130
michaelnbacbcbd2016-02-09 00:32:033131 return it->second.get();
3132 }
3133
3134 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:103135 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
3136 SessionStorageNamespaceImpl::Create(context_wrapper);
3137 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
3138 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:253139 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:103140 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:303141
Daniel Murphy31bbb8b12018-02-07 21:44:103142 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:303143}
3144
3145SessionStorageNamespace*
3146NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:253147 return GetSessionStorageNamespace(
3148 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:303149}
3150
3151const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573152NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303153 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553154}
[email protected]d202a7c2012-01-04 07:53:473155
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573156bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563157 return needs_reload_;
3158}
[email protected]a26023822011-12-29 00:23:553159
[email protected]46bb5e9c2013-10-03 22:16:473160void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413161 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3162}
3163
3164void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473165 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413166 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543167
3168 if (last_committed_entry_index_ != -1) {
3169 entries_[last_committed_entry_index_]->SetTransitionType(
3170 ui::PAGE_TRANSITION_RELOAD);
3171 }
[email protected]46bb5e9c2013-10-03 22:16:473172}
3173
[email protected]d202a7c2012-01-04 07:53:473174void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573175 DCHECK_LT(index, GetEntryCount());
3176 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313177 DiscardNonCommittedEntries();
3178
Nate Chapin9eb16be72022-09-23 22:54:313179 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313180 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123181 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313182 last_committed_entry_index_--;
3183}
3184
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573185NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273186 // If there is no pending_entry_, there should be no pending_entry_index_.
3187 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3188
3189 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363190 // at that index. An exception is while a reload of a post commit error page
3191 // is ongoing; in that case pending entry will point to the entry replaced
3192 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273193 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363194 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3195 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273196
[email protected]022af742011-12-28 18:37:253197 return pending_entry_;
3198}
3199
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573200int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273201 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273202 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553203 return pending_entry_index_;
3204}
3205
avi25764702015-06-23 15:43:373206void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573207 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363208 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313209 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003210 bool in_fenced_frame_tree,
3211 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313212 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3213 // set because:
3214 // 1) They don't influence the history of the outer page.
3215 // 2) They are always replace only navigation (there is always only one entry
3216 // in their history stack).
3217 // 3) Are not top level navigations and appear similar to iframes.
3218 // Navigations of the fenced frame might create a new NavigationEntry, which
3219 // will call this function. Non fenced frame navigations will never have
3220 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3221 // InsertOrReplaceEntry.
3222 DCHECK_EQ(in_fenced_frame_tree,
3223 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3224 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203225
avi5cad4912015-06-19 05:25:443226 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3227 // need to keep continuity with the pending entry, so copy the pending entry's
3228 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3229 // then the renderer navigated on its own, independent of the pending entry,
3230 // so don't copy anything.
3231 if (pending_entry_ && pending_entry_index_ == -1)
3232 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203233
Rakina Zata Amnia4e27222021-12-22 01:05:003234 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203235
creisee17e932015-07-17 17:56:223236 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453237 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103238 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573239 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363240 // If the new entry is a post-commit error page, we store the current last
3241 // committed entry to the side so that we can put it back when navigating
3242 // away from the error.
3243 if (was_post_commit_error) {
3244 DCHECK(!entry_replaced_by_post_commit_error_);
3245 entry_replaced_by_post_commit_error_ =
3246 std::move(entries_[last_committed_entry_index_]);
3247 }
dcheng36b6aec92015-12-26 06:16:363248 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223249 return;
3250 }
[email protected]765b35502008-08-21 00:51:203251
creis37979a62015-08-04 19:48:183252 // We shouldn't see replace == true when there's no committed entries.
3253 DCHECK(!replace);
3254
Michael Thiessen9b14d512019-09-23 21:19:473255 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203256
Shivani Sharmad8c8d652019-02-13 17:27:573257 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203258
dcheng36b6aec92015-12-26 06:16:363259 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203260 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293261}
3262
Shivani Sharmad8c8d652019-02-13 17:27:573263void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163264 if (entries_.size() < max_entry_count())
3265 return;
3266
3267 DCHECK_EQ(max_entry_count(), entries_.size());
3268 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573269 CHECK_EQ(pending_entry_index_, -1);
3270
3271 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423272 // Retrieve the oldest skippable entry.
3273 for (; index < GetEntryCount(); index++) {
3274 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3275 break;
Shivani Sharmad8c8d652019-02-13 17:27:573276 }
3277
3278 // If there is no skippable entry or if it is the last committed entry then
3279 // fall back to pruning the oldest entry. It is not safe to prune the last
3280 // committed entry.
3281 if (index == GetEntryCount() || index == last_committed_entry_index_)
3282 index = 0;
3283
3284 bool should_succeed = RemoveEntryAtIndex(index);
3285 DCHECK_EQ(true, should_succeed);
3286
3287 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253288}
3289
William Liu62ae26c2024-08-08 14:28:163290std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273291NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163292 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203293 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373294 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133295 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493296 const std::string* navigation_api_key,
3297 base::TimeTicks actual_navigation_start) {
Alexander Timin3a92df72019-09-20 11:59:503298 TRACE_EVENT0("navigation",
3299 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273300 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023301 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363302 if (pending_entry_index_ != -1) {
3303 // The pending entry may not be in entries_ if a post-commit error page is
3304 // showing.
3305 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3306 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3307 }
Gyuyoung Kim107c2a02021-04-13 01:49:303308 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573309 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013310 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033311 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573312 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133313 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3314 // the same as the top level frame being navigated.
3315 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373316 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133317 }
Arthur Sonzogni620cec62018-12-13 13:08:573318
[email protected]83c2e232011-10-07 21:36:463319 // If we were navigating to a slow-to-commit page, and the user performs
3320 // a session history navigation to the last committed page, RenderViewHost
3321 // will force the throbber to start, but WebKit will essentially ignore the
3322 // navigation, and won't send a message to stop the throbber. To prevent this
3323 // from happening, we drop the navigation here and stop the slow-to-commit
3324 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023325 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083326 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273327 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033328 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123329
[email protected]83c2e232011-10-07 21:36:463330 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163331 return {};
[email protected]83c2e232011-10-07 21:36:463332 }
3333
Arthur Sonzognic686e8f2024-01-11 08:36:373334 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333335 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3336 if (initiator_rfh) {
3337 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543338 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333339 DCHECK(initiator_frame_token);
3340 }
3341
creisce0ef3572017-01-26 17:53:083342 // Compare FrameNavigationEntries to see which frames in the tree need to be
3343 // navigated.
clamy3cb9bea92018-07-10 12:42:023344 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3345 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333346 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3347 initiator_process_id, soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493348 actual_navigation_start, &same_document_loads,
3349 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303350
3351 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573352 // We were unable to match any frames to navigate. This can happen if a
3353 // history navigation targets a subframe that no longer exists
3354 // (https://crbug.com/705550). In this case, we need to update the current
3355 // history entry to the pending one but keep the main document loaded. We
3356 // also need to ensure that observers are informed about the updated
3357 // current history entry (e.g., for greying out back/forward buttons), and
Charlie Reis99b2eba22025-01-31 19:18:573358 // that renderer processes update their history indices. The easiest way
Alex Moshchuk3a4e77a2020-05-29 21:32:573359 // to do all that is to schedule a "redundant" same-document navigation in
3360 // the main frame.
3361 //
3362 // Note that we don't want to remove this history entry, as it might still
3363 // be valid later, since a frame that it's targeting may be recreated.
3364 //
3365 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3366 // need to repeat history navigations until finding the one that works.
3367 // Consider changing this behavior to keep looking for the first valid
3368 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023369 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423370 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573371 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573372 ReloadType::NONE /* reload_type */,
3373 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433374 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493375 initiator_frame_token, initiator_process_id,
3376 actual_navigation_start);
clamy3cb9bea92018-07-10 12:42:023377 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573378 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023379 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163380 return {};
clamy3cb9bea92018-07-10 12:42:023381 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573382 same_document_loads.push_back(std::move(navigation_request));
3383
3384 // Sanity check that we never take this branch for any kinds of reloads,
3385 // as those should've queued a different-document load in the main frame.
3386 DCHECK(!is_forced_reload);
3387 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303388 }
3389
Nate Chapinbf682fa32022-09-26 22:41:203390 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163391 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203392 if (initiator_rfh && initiator_rfh->IsSandboxed(
3393 network::mojom::WebSandboxFlags::kTopNavigation)) {
3394 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3395 initiator_rfh, same_document_loads) &&
3396 DoesSandboxNavigationStayWithinSubtree(
3397 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503398 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163399 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203400 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3401 initiator_rfh,
3402 navigates_inside_tree
3403 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3404 : blink::mojom::WebFeature::
3405 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523406
3407 // If the navigation occurred outside the tree discard it because
3408 // the sandboxed frame didn't have permission to navigate outside
3409 // its tree. If it is possible that the navigation is both inside and
3410 // outside the frame tree and we discard it entirely because we don't
3411 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143412 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203413 // If a |navigation_api_key| was provided, this navigation originated from
3414 // the navigation API. Notify the renderer that the navigation was
3415 // cancelled so the navigation API can fire an error event and reject the
3416 // relevant promise.
3417 if (navigation_api_key) {
3418 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3419 *navigation_api_key,
3420 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3421 }
Dave Tapuska855c1e12019-08-23 20:45:523422 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133423
3424 for (auto& unused_request : same_document_loads) {
3425 unused_request->set_navigation_discard_reason(
3426 NavigationDiscardReason::kNeverStarted);
3427 }
3428 for (auto& unused_request : different_document_loads) {
3429 unused_request->set_navigation_discard_reason(
3430 NavigationDiscardReason::kNeverStarted);
3431 }
William Liu62ae26c2024-08-08 14:28:163432 return {};
Dave Tapuska855c1e12019-08-23 20:45:523433 }
Dave Tapuska8bfd84c2019-03-26 20:47:163434 }
3435
Nate Chapin6c43c022023-02-13 23:32:423436 // If it is possible that this traverse may involve a same-document navigation
3437 // in the initiator and there is a Navigation API key involved, then we may
3438 // need to notify the initiator if it fails. (The early returns above either
3439 // do not involve these cases or already notify the initiator.)
3440 // The event only needs to fire for the initiator, and only if the initiator
3441 // itself is performing a same-document navigation (because the event will not
3442 // fire if it navigates cross-document).
3443 if (navigation_api_key) {
3444 for (auto& item : same_document_loads) {
3445 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3446 item->set_pending_navigation_api_key(*navigation_api_key);
3447 break;
3448 }
3449 }
3450 }
3451
Carlos Caballero539a421c2020-07-06 10:25:573452 // BackForwardCache:
3453 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563454 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573455 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
Charlie Reis3696ab62025-05-28 07:02:303456 // TODO(crbug.com/420275259): Diagnose failures and upgrade to a CHECK.
3457 DCHECK_EQ(reload_type, ReloadType::NONE);
Charlie Reis655c8f02025-05-15 01:16:173458 base::WeakPtr<NavigationRequest> request;
Rakina Zata Amni58681c62024-06-25 06:32:133459
Charlie Reis655c8f02025-05-15 01:16:173460 // Skip a redundant NavigationRequest creation, per
3461 // https://crbug.com/417251428.
3462 if (base::FeatureList::IsEnabled(kSkipExtraBfcacheNavigationRequest)) {
3463 // If the BackForwardCache can handle this request, it must be for a main
3464 // frame, cross-document, non-reload request. This means there is only one
3465 // item in `different_document_loads` and no `same_document_loads`.
3466 CHECK_EQ(different_document_loads.size(), 1u);
3467 CHECK(same_document_loads.empty());
3468 request = different_document_loads.at(0)->GetWeakPtr();
Charlie Reisd3e4fef2025-05-20 02:04:173469
3470 // Ensure that no re-entrant calls or discards of the pending entry occur
3471 // while calling `Navigator::Navigate` for a pending entry.
3472 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3473 weak_factory_.GetSafeRef());
3474
Charlie Reis655c8f02025-05-15 01:16:173475 root->navigator().Navigate(std::move(different_document_loads.at(0)),
3476 ReloadType::NONE);
Charlie Reisd3e4fef2025-05-20 02:04:173477
3478 // `reentrancy_guard` deleted here.
Charlie Reis655c8f02025-05-15 01:16:173479 } else {
3480 // The legacy approach creates a new NavigationRequest for the entry and
3481 // discards any previously created NavigationRequests, even though the new
3482 // request is identical to the sole existing request.
3483 // TODO(crbug.com/417251428): Remove this path once we measure the impact.
3484 auto navigation_request = CreateNavigationRequestFromEntry(
3485 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3486 ReloadType::NONE, false /* is_same_document_history_load */,
3487 false /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:493488 initiator_process_id, actual_navigation_start);
Charlie Reis655c8f02025-05-15 01:16:173489 request = navigation_request->GetWeakPtr();
3490 root->navigator().Navigate(std::move(navigation_request),
3491 ReloadType::NONE);
3492
3493 for (auto& unused_request : same_document_loads) {
3494 unused_request->set_navigation_discard_reason(
3495 NavigationDiscardReason::kNeverStarted);
3496 }
3497 for (auto& unused_request : different_document_loads) {
3498 unused_request->set_navigation_discard_reason(
3499 NavigationDiscardReason::kNeverStarted);
3500 }
Rakina Zata Amni58681c62024-06-25 06:32:133501 }
3502
Charlie Reis655c8f02025-05-15 01:16:173503 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_requests;
William Liu62ae26c2024-08-08 14:28:163504 if (request) {
Charlie Reis655c8f02025-05-15 01:16:173505 bf_cache_requests.push_back(std::move(request));
William Liu62ae26c2024-08-08 14:28:163506 }
Charlie Reis655c8f02025-05-15 01:16:173507 return bf_cache_requests;
Carlos Caballero539a421c2020-07-06 10:25:573508 }
3509
3510 // History navigation might try to reuse a specific BrowsingInstance, already
3511 // used by a page in the cache. To avoid having two different main frames that
3512 // live in the same BrowsingInstance, evict the all pages with this
3513 // BrowsingInstance from the cache.
3514 //
3515 // For example, take the following scenario:
3516 //
3517 // A1 = Some page on a.com
3518 // A2 = Some other page on a.com
3519 // B3 = An uncacheable page on b.com
3520 //
3521 // Then the following navigations occur:
3522 // A1->A2->B3->A1
3523 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3524 // take its place) and A1 will be created in the same BrowsingInstance (and
3525 // SiteInstance), as A2.
3526 //
3527 // If we didn't do anything, both A1 and A2 would remain alive in the same
3528 // BrowsingInstance/SiteInstance, which is unsupported by
3529 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3530 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483531 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3532 pending_entry_->site_instance()
3533 ? pending_entry_->site_instance()->GetId().value()
3534 : -1);
3535 SCOPED_CRASH_KEY_NUMBER(
3536 "rvh_double", "pending_entry_bi",
3537 pending_entry_->site_instance()
3538 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3539 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573540 if (pending_entry_->site_instance()) {
3541 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3542 pending_entry_->site_instance());
3543 }
3544
Rakina Zata Amnid605d462022-06-01 10:17:033545 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3546 pending_entry_ && pending_entry_->IsRestored());
3547 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3548 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3549 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3550 pending_entry_index_);
3551 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3552 last_committed_entry_index_);
3553 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3554 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3555 pending_entry_ && pending_entry_->IsInitialEntry());
3556 SCOPED_CRASH_KEY_BOOL(
3557 "nav_reentrancy", "pending_entry_initial2",
3558 pending_entry_ &&
3559 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3560 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3561 IsInitialNavigation());
3562 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3563 IsInitialBlankNavigation());
3564 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3565 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3566 (int)pending_reload_);
3567
Charlie Reisd3e4fef2025-05-20 02:04:173568 // Ensure that no re-entrant calls or discards of the pending entry occur
3569 // while calling `Navigator::Navigate` for a pending entry.
3570 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3571 weak_factory_.GetSafeRef());
creis4e2ecb72015-06-20 00:46:303572
Rakina Zata Amnid605d462022-06-01 10:17:033573 // If the navigation-reentrancy is caused by calling
3574 // NavigateToExistingPendingEntry twice, this will note the previous call's
3575 // pending entry's ID.
3576 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3577 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3578
Nate Chapin154b14b2023-02-17 18:28:163579 // If there is a main-frame same-document history navigation, we may defer
3580 // the subframe history navigations in order to give JS in the main frame the
3581 // opportunity to cancel the entire traverse via the navigate event. In that
3582 // case, we need to stash the main frame request's navigation token on the
3583 // subframes, so they can look up the main frame request and defer themselves
3584 // until it completes.
3585 if (!same_document_loads.empty() &&
3586 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3587 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3588 // The token will only be returned in cases where deferring the navigation
3589 // is necessary.
3590 if (auto main_frame_same_document_token =
3591 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3592 for (auto& item : same_document_loads) {
3593 if (item.get() != main_frame_request) {
3594 item->set_main_frame_same_document_history_token(
3595 main_frame_same_document_token);
3596 }
3597 }
3598 for (auto& item : different_document_loads) {
3599 item->set_main_frame_same_document_history_token(
3600 main_frame_same_document_token);
3601 }
3602 }
3603 }
3604
William Liu122754942024-01-18 22:34:393605 if (!initiator_rfh) {
3606 // A browser-initiated navigation won't have a `initiator_rfh`.
3607 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3608 different_document_loads, same_document_loads);
3609 }
3610
William Liu62ae26c2024-08-08 14:28:163611 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3612 all_requests.reserve(same_document_loads.size() +
3613 different_document_loads.size());
3614 bool seen_primary_main_frame_request = false;
3615
creis4e2ecb72015-06-20 00:46:303616 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023617 for (auto& item : same_document_loads) {
3618 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273619 // The request could be destroyed before `navigator().Navigate()` returns.
3620 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053621 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163622 if (request) {
3623 // Can only have one primary main frame request.
3624 CHECK(!seen_primary_main_frame_request ||
3625 !request->IsInPrimaryMainFrame());
3626 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3627 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273628 }
creis4e2ecb72015-06-20 00:46:303629 }
clamy3cb9bea92018-07-10 12:42:023630 for (auto& item : different_document_loads) {
3631 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273632 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053633 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163634 if (request) {
3635 // Can only have one primary main frame request.
3636 CHECK(!seen_primary_main_frame_request ||
3637 !request->IsInPrimaryMainFrame());
3638 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3639 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273640 }
creis4e2ecb72015-06-20 00:46:303641 }
clamy3cb9bea92018-07-10 12:42:023642
William Liu62ae26c2024-08-08 14:28:163643 return all_requests;
Charlie Reisd3e4fef2025-05-20 02:04:173644 // `reentrancy_guard` deleted here.
creis4e2ecb72015-06-20 00:46:303645}
3646
Alex Moshchuk3a4e77a2020-05-29 21:32:573647NavigationControllerImpl::HistoryNavigationAction
3648NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303649 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573650 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423651 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583652 // Only active and prerendered documents are allowed to navigate in their
3653 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423654 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013655 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583656 // - If the document is in pending deletion, the browser already committed
3657 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3658 // - If the document is in back-forward cache, it's not allowed to navigate
3659 // as it should remain frozen. Ignore the request and evict the document
3660 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423661 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583662 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423663 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113664 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3665 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423666 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113667 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423668 }
arthursonzogni03f76152019-02-12 10:35:203669
Alex Moshchuk3a4e77a2020-05-29 21:32:573670 // Reloads should result in a different-document load. Note that reloads may
3671 // also happen via the |needs_reload_| mechanism where the reload_type is
3672 // NONE, so detect this by comparing whether we're going to the same
3673 // entry that we're currently on. Similarly to above, only main frames
3674 // should reach this. Note that subframes support reloads, but that's done
3675 // via a different path that doesn't involve FindFramesToNavigate (see
3676 // RenderFrameHost::Reload()).
3677 if (reload_type != ReloadType::NONE ||
3678 pending_entry_index_ == last_committed_entry_index_) {
3679 DCHECK(frame->IsMainFrame());
3680 return HistoryNavigationAction::kDifferentDocument;
3681 }
3682
Alex Moshchuk47d1a4bd2020-06-01 22:15:343683 // If there is no new FrameNavigationEntry for the frame, ignore the
3684 // load. For example, this may happen when going back to an entry before a
3685 // frame was created. Suppose we commit a same-document navigation that also
3686 // results in adding a new subframe somewhere in the tree. If we go back,
3687 // the new subframe will be missing a FrameNavigationEntry in the previous
3688 // NavigationEntry, but we shouldn't delete or change what's loaded in
3689 // it.
3690 //
Alex Moshchuke65c39272020-06-03 17:55:373691 // Note that in this case, there is no need to keep looking for navigations
3692 // in subframes, which would be missing FrameNavigationEntries as well.
3693 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343694 // It's important to check this before checking |old_item| below, since both
3695 // might be null, and in that case we still shouldn't change what's loaded in
3696 // this frame. Note that scheduling any loads assumes that |new_item| is
3697 // non-null. See https://crbug.com/1088354.
3698 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3699 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373700 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343701
Charlie Reisa474fb62022-03-17 02:31:363702 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3703 // which history item it is currently on, since this may be different than the
3704 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3705 // (e.g., if a history navigation is targeting multiple frames and only some
3706 // have committed so far).
creis4e2ecb72015-06-20 00:46:303707 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363708 frame->current_frame_host()->last_committed_frame_entry();
3709 if (!old_item) {
3710 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3711 // fall back to the last committed NavigationEntry's record for this frame.
3712 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583713 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363714 // accurate FrameNavigationEntry and eliminate this case.
3715 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3716 }
3717 // If neither approach finds a FrameNavigationEntry, schedule a
3718 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583719 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573720 if (!old_item)
3721 return HistoryNavigationAction::kDifferentDocument;
3722
Alex Moshchuk3a4e77a2020-05-29 21:32:573723 // If the new item is not in the same SiteInstance, schedule a
3724 // different-document load. Newly restored items may not have a SiteInstance
3725 // yet, in which case it will be assigned on first commit.
3726 if (new_item->site_instance() &&
3727 new_item->site_instance() != old_item->site_instance())
3728 return HistoryNavigationAction::kDifferentDocument;
3729
Charlie Reis71e4ae32025-01-29 21:37:573730 // If the origins of the new and old items are both present but don't match,
3731 // schedule a different document load even if the document sequence numbers
3732 // somehow match.
3733 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3734 // committed origin on `new_item`, and update the Blink DSN computation to
3735 // avoid a cross-origin DSN match when possible.
3736 if (new_item->committed_origin().has_value() &&
3737 old_item->committed_origin().has_value() &&
3738 !new_item->committed_origin()->IsSameOriginWith(
3739 old_item->committed_origin().value())) {
3740 return HistoryNavigationAction::kDifferentDocument;
3741 }
3742
Alex Moshchuk3a4e77a2020-05-29 21:32:573743 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313744 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3745 // that we do this even if the history navigation would not be modifying this
3746 // frame were it live.
3747 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573748 return HistoryNavigationAction::kDifferentDocument;
3749
3750 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313751 // Starting a navigation after a crash early-promotes the speculative
3752 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3753 // committed yet, so we can not possibly perform a same-document history
3754 // navigation. The frame would need to be reloaded with a cross-document
3755 // navigation.
3756 if (!frame->current_frame_host()->has_committed_any_navigation())
3757 return HistoryNavigationAction::kDifferentDocument;
3758
creis54131692016-08-12 18:32:253759 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493760 // sequence number but different item sequence number.
3761 if (new_item->document_sequence_number() ==
3762 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573763 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493764 }
avib48cb312016-05-05 21:35:003765
Alex Moshchuk3a4e77a2020-05-29 21:32:573766 // Otherwise, if both item and document sequence numbers differ, this
3767 // should be a different document load.
3768 return HistoryNavigationAction::kDifferentDocument;
3769 }
3770
3771 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373772 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573773 DCHECK_EQ(new_item->document_sequence_number(),
3774 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373775 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573776}
3777
3778void NavigationControllerImpl::FindFramesToNavigate(
3779 FrameTreeNode* frame,
3780 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373781 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333782 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373783 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133784 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493785 base::TimeTicks actual_navigation_start,
Alex Moshchuk3a4e77a2020-05-29 21:32:573786 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3787 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3788 DCHECK(pending_entry_);
3789 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3790
3791 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3792
3793 if (action == HistoryNavigationAction::kSameDocument) {
3794 std::unique_ptr<NavigationRequest> navigation_request =
3795 CreateNavigationRequestFromEntry(
3796 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133797 /*is_same_document_history_load=*/true,
3798 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333799 initiator_frame_token, initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:493800 actual_navigation_start, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573801 if (navigation_request) {
3802 // Only add the request if was properly created. It's possible for the
3803 // creation to fail in certain cases, e.g. when the URL is invalid.
3804 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303805 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573806 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473807 std::unique_ptr<NavigationRequest> navigation_request =
3808 CreateNavigationRequestFromEntry(
3809 frame, pending_entry_, new_item, reload_type,
3810 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433811 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493812 initiator_frame_token, initiator_process_id,
3813 actual_navigation_start);
Lei Zhang96031532019-10-10 19:05:473814 if (navigation_request) {
3815 // Only add the request if was properly created. It's possible for the
3816 // creation to fail in certain cases, e.g. when the URL is invalid.
3817 different_document_loads->push_back(std::move(navigation_request));
3818 }
3819 // For a different document, the subframes will be destroyed, so there's
3820 // no need to consider them.
3821 return;
Alex Moshchuke65c39272020-06-03 17:55:373822 } else if (action == HistoryNavigationAction::kStopLooking) {
3823 return;
creis4e2ecb72015-06-20 00:46:303824 }
3825
Yoav Weiss8c573952022-11-17 17:35:133826 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3827 // we currently only support soft navigation heuristics for the top level
3828 // frame.
creis4e2ecb72015-06-20 00:46:303829 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333830 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3831 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373832 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:493833 actual_navigation_start, same_document_loads,
3834 different_document_loads);
creis4e2ecb72015-06-20 00:46:303835 }
3836}
3837
Harkiran Bolariaba823e42021-05-21 18:30:363838base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
Charlie Reisf4d51f402025-05-23 18:00:493839 const LoadURLParams& params,
3840 base::TimeTicks actual_navigation_start) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553841 FrameTreeNode* node = GetTargetFrameTreeNodeForNavigation(params);
clamy21718cc22018-06-13 13:34:243842
Camille Lamy5193caa2018-10-12 11:59:423843 // Compute overrides to the LoadURLParams for |override_user_agent|,
3844 // |should_replace_current_entry| and |has_user_gesture| that will be used
3845 // both in the creation of the NavigationEntry and the NavigationRequest.
3846 // Ideally, the LoadURLParams themselves would be updated, but since they are
3847 // passed as a const reference, this is not possible.
3848 // TODO(clamy): When we only create a NavigationRequest, move this to
3849 // CreateNavigationRequestFromLoadURLParams.
3850 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3851 GetLastCommittedEntry());
3852
Rakina Zata Amnie2d31312022-11-18 03:38:453853 // An entry replacement must happen if the current browsing context should
3854 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333855 bool should_replace_current_entry =
3856 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453857 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423858
clamy21718cc22018-06-13 13:34:243859 // Javascript URLs should not create NavigationEntries. All other navigations
3860 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243861 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373862 std::unique_ptr<NavigationEntryImpl> entry =
3863 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3864 should_replace_current_entry,
3865 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243866 DiscardPendingEntry(false);
3867 SetPendingEntry(std::move(entry));
3868 }
3869
Tim Judkins59548192023-05-17 17:51:203870 // Renderer-debug URLs are sent to the current renderer process immediately
3871 // for processing and don't need to create a NavigationRequest. Note: this
3872 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243873 // renderer-debug URLs.
3874 // Note: we intentionally leave the pending entry in place for renderer debug
3875 // URLs, unlike the cases below where we clear it if the navigation doesn't
3876 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303877 if (blink::IsRendererDebugURL(params.url)) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553878 // Renderer-debug URLs won't go through NavigationThrottles so we have to
3879 // check them explicitly. See crbug.com/40605746.
Aaron Colwelle1908d982020-06-26 22:08:153880 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203881 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483882 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363883 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483884 }
3885
clamy21718cc22018-06-13 13:34:243886 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363887 return nullptr;
clamy21718cc22018-06-13 13:34:243888 }
3889
Antonio Sartori78a749f2020-11-30 12:03:393890 DCHECK(pending_entry_);
3891
clamy21718cc22018-06-13 13:34:243892 // Convert navigations to the current URL to a reload.
3893 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3894 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3895 // DevTools sometimes issues navigations to main frames that they do not
3896 // expect to see treated as reload, and it only works because they pass a
3897 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3898 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543899 ReloadType reload_type = params.reload_type;
3900 if (reload_type == ReloadType::NONE &&
3901 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043902 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243903 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243904 params.load_type ==
3905 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543906 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243907 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473908 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393909
3910 // If this is a reload of an existing FrameNavigationEntry and we had a
3911 // policy container for it, then we should copy it into the pending entry,
3912 // so that it is copied to the navigation request in
3913 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453914 FrameNavigationEntry* previous_frame_entry =
3915 GetLastCommittedEntry()->GetFrameEntry(node);
3916 if (previous_frame_entry &&
3917 previous_frame_entry->policy_container_policies()) {
3918 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3919 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393920 }
3921 }
3922
3923 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173924 // document, then we should copy the document polices from RenderFrameHost's
3925 // PolicyContainerHost. The NavigationRequest will create a new
3926 // PolicyContainerHost with the document policies from the |pending_entry_|,
3927 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3928 // the navigation. This way, we ensure that we keep enforcing the right
3929 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453930 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393931 if (node->current_frame_host() &&
3932 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193933 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163934 node->current_frame_host()
3935 ->policy_container_host()
3936 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233937 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393938 }
clamy21718cc22018-06-13 13:34:243939 }
3940
3941 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263942 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243943
Tsuyoshi Horo167ca6432022-03-09 05:16:393944 // This will be used to set the Navigation Timing API navigationStart
3945 // parameter for browser navigations in new tabs (intents, tabs opened through
3946 // "Open link in new tab"). If the navigation must wait on the current
3947 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3948 // will be updated when the BeforeUnload ack is received.
3949 const auto navigation_start_time = base::TimeTicks::Now();
Tsuyoshi Horo167ca6432022-03-09 05:16:393950
Camille Lamy5193caa2018-10-12 11:59:423951 std::unique_ptr<NavigationRequest> request =
3952 CreateNavigationRequestFromLoadParams(
3953 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143954 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393955 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
Charlie Reisf4d51f402025-05-23 18:00:493956 actual_navigation_start, navigation_start_time);
clamy21718cc22018-06-13 13:34:243957
3958 // If the navigation couldn't start, return immediately and discard the
3959 // pending NavigationEntry.
3960 if (!request) {
3961 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363962 return nullptr;
clamy21718cc22018-06-13 13:34:243963 }
3964
Camille Lamy5193caa2018-10-12 11:59:423965#if DCHECK_IS_ON()
3966 // Safety check that NavigationRequest and NavigationEntry match.
3967 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3968#endif
3969
Charlie Reisd3e4fef2025-05-20 02:04:173970 // Ensure that no re-entrant calls or discards of the pending entry occur
3971 // while calling `Navigator::Navigate` for a pending entry.
3972 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3973 weak_factory_.GetSafeRef());
arthursonzogni66f711c2019-10-08 14:40:363974
Harkiran Bolariaba823e42021-05-21 18:30:363975 base::WeakPtr<NavigationHandle> created_navigation_handle(
3976 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053977 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243978
Harkiran Bolariaba823e42021-05-21 18:30:363979 return created_navigation_handle;
Charlie Reisd3e4fef2025-05-20 02:04:173980 // `reentrancy_guard` deleted here.
clamy21718cc22018-06-13 13:34:243981}
3982
Emmanuel Arias Soto9e159652025-05-16 07:53:553983FrameTreeNode* NavigationControllerImpl::GetTargetFrameTreeNodeForNavigation(
3984 const LoadURLParams& params) {
3985 FrameTreeNode* node = nullptr;
3986 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3987 node = params.frame_tree_node_id
3988 ? frame_tree_->FindByID(params.frame_tree_node_id)
3989 : frame_tree_->FindByName(params.frame_name);
3990 DCHECK(!node || &node->frame_tree() == &frame_tree());
3991 if (!node && params.frame_tree_node_id) {
3992 // If the specified FrameTreeNode exists in another FrameTree, the caller
3993 // is using the wrong NavigationController.
3994 CHECK(!FrameTreeNode::GloballyFindByID(params.frame_tree_node_id),
3995 base::NotFatalUntil::M140);
3996 }
3997 }
3998
3999 // If no FrameTreeNode was specified, navigate the main frame.
4000 if (!node) {
4001 node = frame_tree_->root();
4002 }
4003 return node;
4004}
4005
clamyea99ea12018-05-28 13:54:234006void NavigationControllerImpl::HandleRendererDebugURL(
4007 FrameTreeNode* frame_tree_node,
4008 const GURL& url) {
4009 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:244010 // Any renderer-side debug URLs or javascript: URLs should be ignored if
4011 // the renderer process is not live, unless it is the initial navigation
4012 // of the tab.
clamyea99ea12018-05-28 13:54:234013 if (!IsInitialNavigation()) {
4014 DiscardNonCommittedEntries();
4015 return;
4016 }
Fergal Dalyecd3b0202020-06-25 01:57:374017 // The current frame is always a main frame. If IsInitialNavigation() is
4018 // true then there have been no navigations and any frames of this tab must
4019 // be in the same renderer process. If that has crashed then the only frame
4020 // that can be revived is the main frame.
4021 frame_tree_node->render_manager()
4022 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:234023 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:224024
4025 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
4026 // notification, so set is loading to true here to properly surface it when
4027 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:314028 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:224029 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:224030 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:224031 }
clamyea99ea12018-05-28 13:54:234032 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
4033}
4034
clamy21718cc22018-06-13 13:34:244035std::unique_ptr<NavigationEntryImpl>
4036NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
4037 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:424038 const LoadURLParams& params,
4039 bool override_user_agent,
4040 bool should_replace_current_entry,
4041 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:394042 // Browser initiated navigations might not have a blob_url_loader_factory set
4043 // in params even if the navigation is to a blob URL. If that happens, lookup
4044 // the correct url loader factory to use here.
4045 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:484046 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:474047 // Resolve the blob URL in the storage partition associated with the target
4048 // frame. This is the storage partition the URL will be loaded in, and only
4049 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:394050 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:474051 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:394052 }
4053
clamy21718cc22018-06-13 13:34:244054 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:444055 // extra_headers in params are \n separated; navigation entries want \r\n.
4056 std::string extra_headers_crlf;
4057 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:244058
4059 // For subframes, create a pending entry with a corresponding frame entry.
4060 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:454061 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:244062 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:084063 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:244064 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:374065 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:214066 params.initiator_base_url, params.redirect_chain, blink::PageState(),
4067 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:394068 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:164069 // a conversion of a new navigation into a reload, we will set the right
4070 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:194071 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:244072 } else {
4073 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:174074 // If `node` is the outermost main frame, it rewrites a virtual url in order
4075 // to adjust the original input url if needed. For inner frames such as
4076 // fenced frames or subframes, they don't rewrite urls as the urls are not
4077 // input urls by users.
4078 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:324079 scoped_refptr<SiteInstance> source_site_instance =
4080 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:374081 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:324082 if (source_site_instance && source_site_instance->HasProcess()) {
4083 source_process_site_url =
4084 source_site_instance->GetProcess()->GetProcessLock().site_url();
4085 }
clamy21718cc22018-06-13 13:34:244086 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:064087 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:324088 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:214089 params.transition_type, params.is_renderer_initiated,
4090 extra_headers_crlf, browser_context_, blob_url_loader_factory,
4091 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:244092 entry->set_source_site_instance(
4093 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
4094 entry->SetRedirectChain(params.redirect_chain);
4095 }
4096
4097 // Set the FTN ID (only used in non-site-per-process, for tests).
4098 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:244099 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:424100 entry->SetIsOverridingUserAgent(override_user_agent);
4101 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:544102 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:244103
clamy21718cc22018-06-13 13:34:244104 switch (params.load_type) {
4105 case LOAD_TYPE_DEFAULT:
4106 break;
4107 case LOAD_TYPE_HTTP_POST:
4108 entry->SetHasPostData(true);
4109 entry->SetPostData(params.post_data);
4110 break;
4111 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:544112 // LoadDataWithBaseURL is a special case that needs to assign both a base
4113 // URL and a virtual URL, while loading the actual content from a data
4114 // URL.
clamy21718cc22018-06-13 13:34:244115 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:544116 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:284117#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:244118 entry->SetDataURLAsString(params.data_url_as_string);
4119#endif
4120 entry->SetCanLoadLocalResources(params.can_load_local_resources);
4121 break;
Shu Yang112ad492024-07-25 17:11:544122#if BUILDFLAG(IS_ANDROID)
4123 case LOAD_TYPE_PDF_ANDROID:
4124 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
4125 // internal URL is used for the navigation URL.
4126 entry->SetVirtualURL(params.virtual_url_for_special_cases);
4127 break;
4128#endif
clamy21718cc22018-06-13 13:34:244129 }
4130
4131 // TODO(clamy): NavigationEntry is meant for information that will be kept
4132 // after the navigation ended and therefore is not appropriate for
4133 // started_from_context_menu. Move started_from_context_menu to
4134 // NavigationUIData.
4135 entry->set_started_from_context_menu(params.started_from_context_menu);
4136
4137 return entry;
4138}
4139
clamyea99ea12018-05-28 13:54:234140std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:424141NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
4142 FrameTreeNode* node,
4143 const LoadURLParams& params,
4144 bool override_user_agent,
4145 bool should_replace_current_entry,
4146 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:144147 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:424148 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574149 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:394150 FrameNavigationEntry* frame_entry,
Charlie Reise1d9b8182025-04-02 04:32:124151 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:224152 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:494153 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:454154 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584155 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:344156 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:374157 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574158 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:524159
4160 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
4161 // subframes have FrameNavigationEntries associated with them. Until then,
4162 // there may be cases where a subframe navigation is missing `frame_entry`
4163 // (e.g., see https://crbug.com/358084015).
4164
Nasko Oskov3c2f9e252019-01-10 17:45:534165 // All renderer-initiated navigations must have an initiator_origin.
4166 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:514167
Camille Lamy5193caa2018-10-12 11:59:424168 GURL url_to_load;
4169 GURL virtual_url;
Nasko Oskov039121012019-01-11 00:21:324170
Camille Lamy2baa8022018-10-19 16:43:174171 // For main frames, rewrite the URL if necessary and compute the virtual URL
4172 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:264173 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424174 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:174175 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424176 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:424177
Shu Yang112ad492024-07-25 17:11:544178 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
4179 // that need to define a virtual URL to display, which differs from the
4180 // navigation URL.
4181 if (params.load_type == LOAD_TYPE_DATA) {
4182 virtual_url = params.virtual_url_for_special_cases;
4183 }
4184#if BUILDFLAG(IS_ANDROID)
4185 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
4186 virtual_url = params.virtual_url_for_special_cases;
4187 }
4188#endif
Camille Lamy5193caa2018-10-12 11:59:424189
Camille Lamy2baa8022018-10-19 16:43:174190 if (virtual_url.is_empty())
4191 virtual_url = url_to_load;
4192
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574193 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:284194
Aran Gilman249eb122019-12-02 23:32:464195 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
4196 // behavior: it is possible for two calls to RewriteUrlForNavigation to
4197 // return different results, leading to a different URL in the
4198 // NavigationRequest and FrameEntry. This will be fixed once we remove the
4199 // pending NavigationEntry, as we'll only make one call to
4200 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:524201 if (frame_entry) {
4202 VLOG_IF(1, (url_to_load != frame_entry->url()))
4203 << "NavigationRequest and FrameEntry have different URLs: "
4204 << url_to_load << " vs " << frame_entry->url();
4205 }
Camille Lamyb9ed3c52018-11-19 15:34:284206
Camille Lamy2baa8022018-10-19 16:43:174207 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424208 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174209 // NavigationRequest.
4210 } else {
4211 url_to_load = params.url;
4212 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244213 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174214 }
Camille Lamy5193caa2018-10-12 11:59:424215
Ehsan Karamad44fc72112019-02-26 18:15:474216 if (node->render_manager()->is_attaching_inner_delegate()) {
4217 // Avoid starting any new navigations since this node is now preparing for
4218 // attaching an inner delegate.
4219 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204220 }
Camille Lamy5193caa2018-10-12 11:59:424221
Alex Moshchuk99242832023-05-22 17:21:444222 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424223 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444224 }
Camille Lamy5193caa2018-10-12 11:59:424225
danakjd83d706d2020-11-25 22:11:124226 // Look for a pending commit that is to another document in this
4227 // FrameTreeNode. If one exists, then the last committed URL will not be the
4228 // current URL by the time this navigation commits.
4229 bool has_pending_cross_document_commit =
4230 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214231 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124232
Minggang Wangb9f3fa92021-07-01 15:30:314233 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494234 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524235 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494236 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134237 /*is_same_document_history_load=*/false,
4238 is_embedder_initiated_fenced_frame_navigation,
4239 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424240
4241 // Create the NavigationParams based on |params|.
4242
Hiroki Nakagawa4ed61282021-06-18 05:37:234243 bool is_view_source_mode = entry->IsViewSourceMode();
4244 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294245
Antonio Sartori6984c742021-08-26 08:03:414246 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294247
Hiroki Nakagawa4ed61282021-06-18 05:37:234248 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294249 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254250 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294251
Charlie Reisf21cd182024-08-09 21:44:524252 std::string page_state_data =
4253 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4254
Minggang Wangb9f3fa92021-07-01 15:30:314255 blink::mojom::CommonNavigationParamsPtr common_params =
4256 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214257 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514258 blink::mojom::Referrer::New(params.referrer.url,
4259 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214260 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514261 should_replace_current_entry, params.base_url_for_data_url,
Charlie Reise1d9b8182025-04-02 04:32:124262 actual_navigation_start_time, navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514263 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144264 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414265 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274266 false /* has_text_fragment_token */,
4267 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4268 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514269 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd0a2023-03-28 14:48:054270 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424271
Minggang Wangb9f3fa92021-07-01 15:30:314272 blink::mojom::CommitNavigationParamsPtr commit_params =
4273 blink::mojom::CommitNavigationParams::New(
Diana Quae845bf2025-04-03 20:12:374274 url::Origin(),
Ari Chivukulac7533522024-05-14 21:52:344275 // The correct storage key will be computed before committing the
4276 // navigation.
4277 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324278 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504279 std::vector<net::RedirectInfo>(), params.post_content_type,
4280 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524281 params.can_load_local_resources, page_state_data,
4282 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134283 /*intended_as_new_entry=*/true,
Charlie Reis99b2eba22025-01-31 19:18:574284 /*pending_history_list_index=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144285 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4286 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134287 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314288 params.should_clear_history_list,
4289 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224290 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134291 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514292 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284293#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134294 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144295#endif
Yoav Weiss8c573952022-11-17 17:35:134296 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154297 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134298 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074299 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134300 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4301 /*origin_agent_cluster=*/false,
4302 /*origin_agent_cluster_left_as_default=*/true,
4303 /*enabled_client_hints=*/
4304 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264305 /*is_cross_site_cross_browsing_context_group=*/false,
4306 /*should_have_sticky_user_activation=*/false,
4307 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134308 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014309 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134310 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584311 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134312 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134313 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284314 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134315 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444316 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424317 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374318 /*view_transition_state=*/std::nullopt,
4319 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054320 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464321 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374322 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd0a2023-03-28 14:48:054323 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094324 /*load_with_storage_access=*/
4325 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374326 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374327 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484328 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314329 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164330 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174331 node->current_frame_host()->GetCachedPermissionStatuses(),
Charlie Reiscdb798342025-02-14 22:04:464332 /*should_skip_screentshot=*/false,
Alex Moshchukd0d759c22025-05-09 18:18:354333 /*force_new_document_sequence_number=*/false,
4334 /*navigation_metrics_token=*/base::UnguessableToken::Create());
Xiaohan Wang7f8052e02022-01-14 18:44:284335#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424336 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564337 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424338 }
4339#endif
4340
Lucas Furukawa Gadania9c45682019-07-31 22:05:144341 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074342 commit_params->navigation_timing->system_entropy_at_navigation_start =
4343 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4344 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424345
Camille Lamy5193caa2018-10-12 11:59:424346 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4347 std::string extra_headers_crlf;
4348 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094349
Alex Moshchuk9321e6a2022-12-07 21:58:314350 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144351 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084352 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094353 params.initiator_frame_token, params.initiator_process_id,
4354 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214355 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294356 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454357 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344358 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034359 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134360
4361 if (!navigation_request) {
4362 return nullptr;
4363 }
4364
Yao Xiaodc5ed102019-06-04 19:19:094365 navigation_request->set_from_download_cross_origin_redirect(
4366 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554367 navigation_request->set_force_new_browsing_instance(
4368 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514369 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434370 if (params.force_no_https_upgrade) {
4371 navigation_request->set_force_no_https_upgrade();
4372 }
Yao Xiaodc5ed102019-06-04 19:19:094373 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424374}
4375
4376std::unique_ptr<NavigationRequest>
4377NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234378 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574379 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234380 FrameNavigationEntry* frame_entry,
4381 ReloadType reload_type,
4382 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434383 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374384 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334385 int initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:494386 base::TimeTicks actual_navigation_start,
Arthur Sonzognic686e8f2024-01-11 08:36:374387 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134388 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344389 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234390 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434391 // We should never navigate to an existing initial NavigationEntry that is the
4392 // initial NavigationEntry for the initial empty document that hasn't been
4393 // overridden by the synchronous about:blank commit, to preserve previous
4394 // behavior where trying to reload when the main frame is on the initial empty
4395 // document won't result in a navigation.
4396 // See also https://crbug.com/1277414.
4397 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov039121012019-01-11 00:21:324398
clamyea99ea12018-05-28 13:54:234399 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234400
Ehsan Karamad44fc72112019-02-26 18:15:474401 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4402 // Avoid starting any new navigations since this node is now preparing for
4403 // attaching an inner delegate.
4404 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204405 }
4406
Alex Moshchuk99242832023-05-22 17:21:444407 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4408 dest_url)) {
clamyea99ea12018-05-28 13:54:234409 return nullptr;
4410 }
4411
clamyea99ea12018-05-28 13:54:234412 // This will be used to set the Navigation Timing API navigationStart
4413 // parameter for browser navigations in new tabs (intents, tabs opened through
4414 // "Open link in new tab"). If the navigation must wait on the current
4415 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4416 // will be updated when the BeforeUnload ack is received.
clamyea99ea12018-05-28 13:54:234417 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074418 const auto navigation_start_system_entropy =
4419 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4420 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234421
danakjd83d706d2020-11-25 22:11:124422 // Look for a pending commit that is to another document in this
4423 // FrameTreeNode. If one exists, then the last committed URL will not be the
4424 // current URL by the time this navigation commits.
4425 bool has_pending_cross_document_commit =
4426 frame_tree_node->render_manager()
4427 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494428 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214429 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124430
Minggang Wangb9f3fa92021-07-01 15:30:314431 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124432 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524433 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494434 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494435 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134436 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494437 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424438
4439 // A form submission may happen here if the navigation is a
4440 // back/forward/reload navigation that does a form resubmission.
4441 scoped_refptr<network::ResourceRequestBody> request_body;
4442 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394443 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504444 // entry. This way, it could be directly retrieved here. Right now, it is only
4445 // partially recovered when request.method == "POST" and request.body exists.
4446 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424447 if (frame_entry->method() == "POST") {
4448 request_body = frame_entry->GetPostData(&post_content_type);
4449 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304450 post_content_type = std::string(
4451 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504452 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424453 }
4454
4455 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314456 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514457 entry->ConstructCommonNavigationParams(
4458 *frame_entry, request_body, dest_url,
4459 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Charlie Reisf4d51f402025-05-23 18:00:494460 navigation_type, actual_navigation_start, navigation_start,
Charlie Reise1d9b8182025-04-02 04:32:124461 /*input_start=*/base::TimeTicks());
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514462 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554463 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424464
4465 // TODO(clamy): |intended_as_new_entry| below should always be false once
4466 // Reload no longer leads to this being called for a pending NavigationEntry
4467 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314468 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144469 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404470 *frame_entry, common_params->url, common_params->method,
4471 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144472 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534473 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484474 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134475 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074476 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144477 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074478 commit_params->navigation_timing->system_entropy_at_navigation_start =
4479 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4480 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164481 commit_params->initial_permission_statuses =
4482 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424483
W. James MacLeanb7d6092682022-10-05 15:23:264484 if (common_params->url.IsAboutSrcdoc()) {
4485 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4486 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594487 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264488 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334489 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314490 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144491 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434492 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334493 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4494 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374495 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294496 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4497 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474498 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234499}
4500
[email protected]d202a7c2012-01-04 07:53:474501void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214502 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274503 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404504
Takashi Toyoshimaea534ef22021-07-21 03:27:594505 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404506 // location bar will have up-to-date information about the security style
4507 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134508 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404509
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374510 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574511 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294512}
4513
initial.commit09911bf2008-07-26 23:55:294514// static
[email protected]d202a7c2012-01-04 07:53:474515size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234516 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154517 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214518 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234519}
4520
[email protected]d202a7c2012-01-04 07:53:474521void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224522 if (is_active && needs_reload_)
4523 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214524
4525 if (frame_tree_->is_primary();
4526 auto* cache = GetNavigationEntryScreenshotCache()) {
4527 cache->SetVisible(is_active);
4528 }
initial.commit09911bf2008-07-26 23:55:294529}
4530
[email protected]d202a7c2012-01-04 07:53:474531void NavigationControllerImpl::LoadIfNecessary() {
Charlie Reisf4d51f402025-05-23 18:00:494532 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:034533 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4534 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294535 if (!needs_reload_)
4536 return;
4537
Bo Liucdfa4b12018-11-06 00:21:444538 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4539 needs_reload_type_);
4540
initial.commit09911bf2008-07-26 23:55:294541 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004542 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294543 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004544 if (entry_replaced_by_post_commit_error_) {
4545 // If the current entry is a post commit error, we reload the entry it
4546 // replaced instead. We leave the error entry in place until a commit
4547 // replaces it, but the pending entry points to the original entry in the
4548 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4549 // case that pending_entry_ != entries_[pending_entry_index_].
4550 // Note that this handling is similar to
4551 // `NavigationControllerImpl::Reload()`.
4552 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4553 pending_entry_index_ = GetCurrentEntryIndex();
4554 NavigateToExistingPendingEntry(
4555 ReloadType::NONE,
4556 /*initiator_rfh=*/nullptr,
4557 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494558 /*navigation_api_key=*/nullptr, actual_navigation_start);
Xinghui Lue4e50be2024-05-15 21:46:004559 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134560 NavigateToExistingPendingEntry(
4561 ReloadType::NONE,
4562 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374563 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494564 /*navigation_api_key=*/nullptr, actual_navigation_start);
Rakina Zata Amnie2d31312022-11-18 03:38:454565 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434566 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274567 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344568 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134569 NavigateToExistingPendingEntry(
4570 ReloadType::NONE,
4571 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374572 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494573 /*navigation_api_key=*/nullptr, actual_navigation_start);
avicc872d7242015-08-19 21:26:344574 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434575 // We should never navigate to an existing initial NavigationEntry that is
4576 // the initial NavigationEntry for the initial empty document that hasn't
4577 // been overridden by the synchronous about:blank commit, to preserve
4578 // legacy behavior where trying to reload when the main frame is on the
4579 // initial empty document won't result in a navigation. See also
4580 // https://crbug.com/1277414. If there is something to reload, the
4581 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4582 // it here.
avicc872d7242015-08-19 21:26:344583 needs_reload_ = false;
4584 }
initial.commit09911bf2008-07-26 23:55:294585}
4586
Kevin McNeeccca6172021-10-19 17:11:144587base::WeakPtr<NavigationHandle>
4588NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364589 RenderFrameHost* render_frame_host,
4590 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364591 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134592 RenderFrameHostImpl* rfhi =
4593 static_cast<RenderFrameHostImpl*>(render_frame_host);
Andrew Verge754c70a2025-04-17 17:19:194594 std::unique_ptr<NavigationRequest> navigation_request =
4595 CreateNavigationRequestForErrorPage(rfhi, url, error_page_html,
4596 /*is_post_commit_error_page=*/true);
4597 if (!navigation_request) {
Kevin McNeeccca6172021-10-19 17:11:144598 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114599 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584600
Rakina Zata Amni919b7922020-12-11 09:03:134601 FrameTreeNode* node = rfhi->frame_tree_node();
Charlie Reis09952ee2022-12-08 16:35:074602 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414603 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144604
Andrew Verge754c70a2025-04-17 17:19:194605 // TODO(crbug.com/406729265): LoadPostCommitErrorPage() does not initiate a
4606 // navigation via Navigator::Navigate(). We should fix that, so that
4607 // post-commit error page navigations don't bypass other important checks in
4608 // this function.
Kevin McNeeccca6172021-10-19 17:11:144609 // Calling BeginNavigation may destroy the NavigationRequest.
4610 base::WeakPtr<NavigationRequest> created_navigation_request(
4611 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414612 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144613 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414614}
4615
Andrew Verge754c70a2025-04-17 17:19:194616void NavigationControllerImpl::NavigateFrameToErrorPage(
Xiaochen Zhou9088e642025-07-07 15:08:104617 RenderFrameHost* render_frame_host,
Andrew Verge754c70a2025-04-17 17:19:194618 const GURL& url,
4619 const std::string& error_page_html) {
Xiaochen Zhou9088e642025-07-07 15:08:104620 RenderFrameHostImpl* render_frame_host_impl =
4621 static_cast<RenderFrameHostImpl*>(render_frame_host);
Andrew Verge754c70a2025-04-17 17:19:194622 std::unique_ptr<NavigationRequest> navigation_request =
4623 CreateNavigationRequestForErrorPage(render_frame_host_impl, url,
4624 error_page_html,
4625 /*is_post_commit_error_page=*/false);
4626 if (!navigation_request) {
4627 return;
4628 }
4629
4630 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
4631 node->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
4632}
4633
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574634void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214635 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094636 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154637 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144638 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294639}
4640
[email protected]d202a7c2012-01-04 07:53:474641void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364642 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584643 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474644 // represent a no-committed-entry state.
4645 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364646 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584647 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474648 // if `entries_` contains pre-existing entries from the NavigationController
4649 // before restore, which would not be removed and will be at the front of the
4650 // entries list, causing the index to be off by the amount of pre-existing
4651 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294652 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294653}
[email protected]765b35502008-08-21 00:51:204654
arthursonzogni69a6a1b2019-09-17 09:23:004655void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004656 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4657}
4658
4659void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4660 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474661 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104662 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4663 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294664 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474665 return;
Michael Thiessenc5676d22019-09-25 22:32:104666 }
avi45a72532015-04-07 21:01:454667 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314668
4669 if (!delegate_)
4670 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374671 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484672}
4673
avi7c6f35e2015-05-08 17:52:384674int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4675 int nav_entry_id) const {
4676 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4677 if (entries_[i]->GetUniqueID() == nav_entry_id)
4678 return i;
4679 }
4680 return -1;
4681}
4682
[email protected]d202a7c2012-01-04 07:53:474683void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574684 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254685 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574686 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594687 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254688 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374689 // Normally, cloning a NavigationEntryImpl results in sharing
4690 // FrameNavigationEntries between the original and the clone. However, when
4691 // cloning from a different NavigationControllerImpl, we want to fork the
4692 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374693 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594694 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254695 }
Rakina Zata Amnie2d31312022-11-18 03:38:454696 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274697 DCHECK(pending_entry_index_ == -1 ||
4698 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254699}
[email protected]c5b88d82012-10-06 17:03:334700
4701void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184702 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334703 get_timestamp_callback_ = get_timestamp_callback;
4704}
[email protected]8ff00d72012-10-23 19:12:214705
Shivani Sharmaffb32b82019-04-09 16:58:474706// History manipulation intervention:
4707void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474708 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564709 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404710 bool is_renderer_initiated,
4711 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564712 // Note that for a subframe,
4713 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454714 // gesture happened in any subframe (propagated to main frame) or in the main
4715 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564716 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274717 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474718 return;
4719 }
4720 if (last_committed_entry_index_ == -1)
4721 return;
4722
Shivani Sharmac4cc8922019-04-18 03:11:174723 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474724
Alexander Timine3ec4192020-04-20 16:39:404725 // Log UKM with the URL we are navigating away from.
4726 ukm::builders::HistoryManipulationIntervention(
4727 previous_page_load_ukm_source_id)
4728 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474729}
4730
Shivani Sharmac4cc8922019-04-18 03:11:174731void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4732 int reference_index,
4733 bool skippable) {
4734 auto* reference_entry = GetEntryAtIndex(reference_index);
4735 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4736
4737 int64_t document_sequence_number =
4738 reference_entry->root_node()->frame_entry->document_sequence_number();
4739 for (int index = 0; index < GetEntryCount(); index++) {
4740 auto* entry = GetEntryAtIndex(index);
4741 if (entry->root_node()->frame_entry->document_sequence_number() ==
4742 document_sequence_number) {
4743 entry->set_should_skip_on_back_forward_ui(skippable);
4744 }
4745 }
4746}
4747
arthursonzogni66f711c2019-10-08 14:40:364748std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4749NavigationControllerImpl::ReferencePendingEntry() {
4750 DCHECK(pending_entry_);
4751 auto pending_entry_ref =
4752 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4753 pending_entry_refs_.insert(pending_entry_ref.get());
4754 return pending_entry_ref;
4755}
4756
4757void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4758 // Ignore refs that don't correspond to the current pending entry.
4759 auto it = pending_entry_refs_.find(ref);
4760 if (it == pending_entry_refs_.end())
4761 return;
4762 pending_entry_refs_.erase(it);
4763
4764 if (!pending_entry_refs_.empty())
4765 return;
4766
4767 // The pending entry may be deleted before the last PendingEntryRef.
4768 if (!pending_entry_)
4769 return;
4770
4771 // We usually clear the pending entry when the matching NavigationRequest
4772 // fails, so that an arbitrary URL isn't left visible above a committed page.
4773 //
4774 // However, we do preserve the pending entry in some cases, such as on the
4775 // initial navigation of an unmodified blank tab. We also allow the delegate
4776 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4777 // user edit the URL and try again. This may be useful in cases that the
4778 // committed page cannot be attacker-controlled. In these cases, we still
4779 // allow the view to clear the pending entry and typed URL if the user
4780 // requests (e.g., hitting Escape with focus in the address bar).
4781 //
4782 // Do not leave the pending entry visible if it has an invalid URL, since this
4783 // might be formatted in an unexpected or unsafe way.
4784 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364785 bool should_preserve_entry =
4786 (pending_entry_ == GetVisibleEntry()) &&
4787 pending_entry_->GetURL().is_valid() &&
4788 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4789 if (should_preserve_entry)
4790 return;
4791
4792 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374793 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364794}
4795
Titouan Rigoudy6ec70402021-02-02 15:42:194796std::unique_ptr<PolicyContainerPolicies>
4797NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394798 RenderFrameHostImpl* rfh,
4799 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214800 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174801 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214802 if (navigation_encountered_error) {
4803 // We should never reload the policy container of an error page from
4804 // history, see https://crbug.com/364773822.
4805 return nullptr;
4806 }
4807
Antonio Sartori78a749f2020-11-30 12:03:394808 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454809 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394810 FrameNavigationEntry* previous_frame_entry =
4811 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4812
Alison Gale770f3fc2024-04-27 00:39:584813 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394814 // ensure we always have a FrameNavigationEntry here.
4815 if (!previous_frame_entry)
4816 return nullptr;
4817
Titouan Rigoudy6ec70402021-02-02 15:42:194818 const PolicyContainerPolicies* previous_policies =
4819 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394820
Titouan Rigoudy6ec70402021-02-02 15:42:194821 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394822 return nullptr;
4823
4824 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234825 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394826 }
4827
Titouan Rigoudy72f892d2022-05-02 18:21:234828 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394829}
4830
Charlie Reis99b2eba22025-01-31 19:18:574831void NavigationControllerImpl::BroadcastHistoryIndexAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504832 OPTIONAL_TRACE_EVENT2(
Charlie Reis99b2eba22025-01-31 19:18:574833 "content", "NavigationControllerImpl::BroadcastHistoryIndexAndLength",
4834 "history_index", GetLastCommittedEntryIndex(), "history_length",
Hayato Ito2c8c08d02021-06-23 03:38:434835 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504836
Charlie Reis99b2eba22025-01-31 19:18:574837 int history_index = GetLastCommittedEntryIndex();
Kevin McNee7705fe82024-11-07 18:56:314838 int history_length = GetEntryCount();
Charlie Reis99b2eba22025-01-31 19:18:574839 auto callback = [history_index, history_length](RenderViewHostImpl* rvh) {
Kevin McNee7705fe82024-11-07 18:56:314840 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
Charlie Reis99b2eba22025-01-31 19:18:574841 broadcast->SetHistoryIndexAndLength(history_index, history_length);
Kevin McNee7705fe82024-11-07 18:56:314842 }
4843 };
Ali Hijazid87307d2022-11-07 20:15:034844 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504845}
4846
4847void NavigationControllerImpl::DidAccessInitialMainDocument() {
4848 // We may have left a failed browser-initiated navigation in the address bar
4849 // to let the user edit it and try again. Clear it now that content might
4850 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034851 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504852 DiscardPendingEntry(false);
4853
4854 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374855 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504856}
4857
4858void NavigationControllerImpl::UpdateStateForFrame(
4859 RenderFrameHostImpl* rfhi,
4860 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564861 OPTIONAL_TRACE_EVENT1("content",
4862 "NavigationControllerImpl::UpdateStateForFrame",
4863 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504864 // The state update affects the last NavigationEntry associated with the given
4865 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4866 // in the case of an UpdateState from a frame being swapped out). We track
4867 // which entry this is in the RenderFrameHost's nav_entry_id.
4868 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4869 if (!entry)
4870 return;
4871
4872 FrameNavigationEntry* frame_entry =
4873 entry->GetFrameEntry(rfhi->frame_tree_node());
4874 if (!frame_entry)
4875 return;
4876
4877 // The SiteInstance might not match if we do a cross-process navigation with
4878 // replacement (e.g., auto-subframe), in which case the swap out of the old
4879 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4880 // has already been replaced and destroyed.
4881 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4882 return;
4883
4884 if (page_state == frame_entry->page_state())
4885 return; // Nothing to update.
4886
4887 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4888
4889 // The document_sequence_number and item_sequence_number recorded in the
4890 // FrameNavigationEntry should not differ from the one coming with the update,
4891 // since it must come from the same document. Do not update it if a difference
4892 // is detected, as this indicates that |frame_entry| is not the correct one.
4893 blink::ExplodedPageState exploded_state;
4894 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4895 return;
4896
4897 if (exploded_state.top.document_sequence_number !=
4898 frame_entry->document_sequence_number() ||
4899 exploded_state.top.item_sequence_number !=
4900 frame_entry->item_sequence_number()) {
4901 return;
4902 }
4903
4904 frame_entry->SetPageState(page_state);
4905 NotifyEntryChanged(entry);
4906}
4907
Nate Chapina2c881f52023-11-07 17:02:094908namespace {
4909
4910// The caller is responsible for ensuring the entry is same-origin to the
4911// origin to be committed.
4912blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4913 FrameNavigationEntry* frame_entry,
4914 int64_t pending_document_sequence_number) {
4915 blink::ExplodedPageState exploded_state;
4916 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4917 &exploded_state)) {
4918 return nullptr;
4919 }
4920 blink::ExplodedFrameState frame_state = exploded_state.top;
4921
4922 // If the document represented by this FNE hid its full url from appearing in
4923 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4924 // in the navigation API as well (unless we're navigating to that document).
4925 std::u16string url;
4926 if (pending_document_sequence_number ==
4927 frame_entry->document_sequence_number() ||
4928 !frame_entry->protect_url_in_navigation_api()) {
4929 url = frame_state.url_string.value_or(std::u16string());
4930 }
4931
4932 return blink::mojom::NavigationApiHistoryEntry::New(
4933 frame_state.navigation_api_key.value_or(std::u16string()),
4934 frame_state.navigation_api_id.value_or(std::u16string()), url,
4935 frame_state.item_sequence_number, frame_state.document_sequence_number,
4936 frame_state.navigation_api_state);
4937}
4938
4939} // namespace
4940
Domenic Denicolacd30f5f82022-03-16 21:48:014941std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4942NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574943 Direction direction,
4944 int entry_index,
4945 const url::Origin& pending_origin,
4946 FrameTreeNode* node,
4947 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304948 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094949 int64_t pending_document_sequence_number,
4950 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014951 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454952 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174953 // Don't process the initial entry.
4954 DCHECK_EQ(GetEntryCount(), 1);
4955 return entries;
4956 }
Nate Chapind1fe3612021-04-16 20:45:574957 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304958 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574959 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4960 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094961 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574962 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414963 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574964 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014965 // An entry should only appear in the navigation API entries if it is for
4966 // the same origin as the document being committed. Check the committed
4967 // origin, or if that is not available (during restore), check against the
4968 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584969 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094970 // once we can be sure that entries with the same ISN will never be
4971 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414972 url::Origin frame_entry_origin =
4973 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4974 frame_entry->url(),
4975 frame_entry->initiator_origin().value_or(url::Origin())));
4976 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574977 break;
4978 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4979 continue;
Nate Chapina2c881f52023-11-07 17:02:094980 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4981 ToNavigationApiHistoryEntry(frame_entry,
4982 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304983 DCHECK(entry->url.empty() ||
4984 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574985 entries.push_back(std::move(entry));
4986 previous_item_sequence_number = frame_entry->item_sequence_number();
4987 }
4988 }
4989 // If |entries| was constructed by iterating backwards from
4990 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4991 // earliest-at-the-front. Reverse it.
4992 if (direction == Direction::kBack)
4993 std::reverse(entries.begin(), entries.end());
4994 return entries;
4995}
4996
Domenic Denicolacd30f5f82022-03-16 21:48:014997blink::mojom::NavigationApiHistoryEntryArraysPtr
4998NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554999 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:575000 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:405001 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:445002 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:405003 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:575004
Nate Chapind1fe3612021-04-16 20:45:575005 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:555006 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:575007
Nate Chapine82339d02022-05-03 23:48:255008 // NOTE: |entry_index| is the index where this entry will commit if no
5009 // modifications are made between now and DidCommitNavigation. This is used to
5010 // walk |entries_| and determine which entries should be exposed by the
5011 // navigation API. It is important to calculate this correctly, because blink
5012 // will cancel a same-document history commit if it's not present in the
5013 // entries blink knows about.
5014 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:575015 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:305016 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:255017 bool will_create_new_entry = false;
5018 if (GetPendingEntryIndex() != -1) {
5019 entry_index = GetPendingEntryIndex();
5020 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
5021 pending_item_sequence_number = frame_entry->item_sequence_number();
5022 pending_document_sequence_number =
5023 frame_entry->document_sequence_number();
5024 }
5025 } else if (request &&
5026 !NavigationTypeUtils::IsReload(
5027 request->common_params().navigation_type) &&
5028 !NavigationTypeUtils::IsHistory(
5029 request->common_params().navigation_type) &&
5030 !request->common_params().should_replace_current_entry &&
5031 !request->common_params()
5032 .is_history_navigation_in_new_child_frame) {
5033 will_create_new_entry = true;
5034 entry_index = GetLastCommittedEntryIndex() + 1;
5035 // Don't set pending_item_sequence_number or
5036 // pending_document_sequence_number in this case - a new unique isn/dsn will
5037 // be calculated in the renderer later.
5038 } else if (GetLastCommittedEntryIndex() != -1) {
5039 entry_index = GetLastCommittedEntryIndex();
5040 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:575041 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:305042 pending_document_sequence_number =
5043 frame_entry->document_sequence_number();
5044 }
Nate Chapind1fe3612021-04-16 20:45:575045 }
5046
Domenic Denicolacd30f5f82022-03-16 21:48:015047 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:255048 if (entry_index == -1) {
5049 // TODO(rakina): Exit early when there is no last committed entry.
5050 // Remove when InitialNavigationEntry ships.
5051 return entry_arrays;
5052 }
5053
Nate Chapina2c881f52023-11-07 17:02:095054 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:015055 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:575056 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:095057 pending_item_sequence_number, pending_document_sequence_number,
5058 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:575059
5060 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:095061 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:575062 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:015063 entry_arrays->forward_entries =
5064 PopulateSingleNavigationApiHistoryEntryVector(
5065 Direction::kForward, entry_index, pending_origin, node,
5066 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:095067 pending_document_sequence_number, forwardmost_index);
5068 }
5069
5070 // If the previous entry is within the block of contiguous entries being
5071 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:255072 FrameNavigationEntry* previous_entry = nullptr;
5073 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:055074 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
5075 .initiator_frame_tree_node_id();
5076 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:255077 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
5078 previous_entry = initiator_node->frame_tree()
5079 .controller()
5080 .GetLastCommittedEntry()
5081 ->GetFrameEntry(initiator_node);
5082 }
5083 } else if (GetLastCommittedEntryIndex() != -1 &&
5084 GetLastCommittedEntryIndex() >= backmost_index &&
5085 GetLastCommittedEntryIndex() <= forwardmost_index) {
5086 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
5087 }
5088 if (previous_entry) {
5089 url::Origin previous_entry_origin =
5090 previous_entry->committed_origin().value_or(url::Origin::Resolve(
5091 previous_entry->url(),
5092 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:585093 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:255094 // once we can be sure that entries with the same ISN will never be
5095 // cross-origin.
5096 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
5097 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
5098 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:095099 }
Nate Chapind1fe3612021-04-16 20:45:575100 }
Nate Chapinc06cf80a2023-11-18 01:12:255101
Nate Chapin4e657a472022-02-06 03:38:375102 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:575103}
5104
Nate Chapinfbfe5af2021-06-10 17:22:085105NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:575106NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085107 FrameNavigationEntry* current_entry,
5108 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:575109 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:085110 if (!target_entry || !target_entry->committed_origin())
5111 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:085112 if (!current_entry->committed_origin()->IsSameOriginWith(
5113 *target_entry->committed_origin())) {
5114 return HistoryNavigationAction::kStopLooking;
5115 }
5116
5117 // NOTE: We don't actually care between kSameDocument and
5118 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:575119 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:085120 return HistoryNavigationAction::kDifferentDocument;
5121 return HistoryNavigationAction::kKeepLooking;
5122}
5123
Domenic Denicolacc094fb2022-03-16 23:40:575124void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:205125 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:375126 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:145127 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:495128 const std::string& key,
5129 base::TimeTicks actual_navigation_start) {
Nate Chapinbf682fa32022-09-26 22:41:205130 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:085131 FrameNavigationEntry* current_entry =
5132 GetLastCommittedEntry()->GetFrameEntry(node);
Nate Chapin0dbc93af2025-03-28 17:02:525133 if (!current_entry || !current_entry->committed_origin()) {
Nate Chapinfbfe5af2021-06-10 17:22:085134 return;
Nate Chapin0dbc93af2025-03-28 17:02:525135 }
Nate Chapinfbfe5af2021-06-10 17:22:085136
Alison Gale47d1537d2024-04-19 21:31:465137 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:135138 // when `navigation.traverseTo()` is called.
5139
Nate Chapinfbfe5af2021-06-10 17:22:085140 // We want to find the nearest matching entry that is contiguously
5141 // same-instance and same-origin. Check back first, then forward.
5142 // TODO(japhet): Link spec here once it exists.
5143 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:575144 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085145 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5146 if (result == HistoryNavigationAction::kStopLooking)
5147 break;
5148 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495149 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5150 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085151 return;
5152 }
5153 }
5154 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:575155 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085156 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5157 if (result == HistoryNavigationAction::kStopLooking)
5158 break;
5159 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495160 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5161 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085162 return;
5163 }
5164 }
Nate Chapinbf682fa32022-09-26 22:41:205165
5166 // If we fall through to here, a matching NavigationEntry couldn't be found.
5167 // Notify the renderer that the navigation was cancelled.
5168 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
5169 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:085170}
5171
Domenic Denicolacc094fb2022-03-16 23:40:575172bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:305173 network::mojom::ReferrerPolicy referrer_policy) {
5174 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
5175 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
5176}
5177
shivanigithubf405bf0d2021-11-05 17:58:335178bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
5179 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:315180 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:335181 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:545182 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:465183 // The preview mode appears as prerendered page in renderers, and
5184 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:035185 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:515186 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:335187 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:545188}
5189
Julie Jeongeun Kim0e242242022-11-30 10:45:095190void NavigationControllerImpl::DidChangeReferrerPolicy(
5191 FrameTreeNode* node,
5192 network::mojom::ReferrerPolicy referrer_policy) {
5193 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
5194 if (!entry)
5195 return;
5196
5197 // The FrameNavigationEntry may want to change whether to protect its url
5198 // in the navigation API when the referrer policy changes.
5199 entry->set_protect_url_in_navigation_api(
5200 ShouldProtectUrlInNavigationApi(referrer_policy));
5201}
5202
Minoru Chikamune646eba42025-04-14 01:25:035203void NavigationControllerImpl::CheckPotentialNavigationReentrancy() {
Minoru Chikamune13ab4de2025-05-14 21:54:075204 if (can_be_in_navigate_to_pending_entry_) {
Minoru Chikamune646eba42025-04-14 01:25:035205 // This DumpWithoutCrashing is an investigation code for
5206 // https://crbug.com/396998476.
5207 base::debug::DumpWithoutCrashing();
5208 }
5209}
5210
Andrew Verge754c70a2025-04-17 17:19:195211std::unique_ptr<NavigationRequest>
5212NavigationControllerImpl::CreateNavigationRequestForErrorPage(
5213 RenderFrameHostImpl* render_frame_host_impl,
5214 const GURL& url,
5215 const std::string& error_page_html,
5216 bool is_post_commit_error_page) {
5217 // Only active documents can load error pages:
5218 // - If the document is in pending deletion, the browser already committed to
5219 // destroying this RenderFrameHost so ignore loading the error page.
5220 // - If the document is in back-forward cache, it's not allowed to navigate as
5221 // it should remain frozen. Ignore the request and evict the document from
5222 // back-forward cache.
5223 // - If the document is prerendering, it can navigate but when loading error
5224 // pages, cancel prerendering.
5225 if (render_frame_host_impl->IsInactiveAndDisallowActivation(
5226 is_post_commit_error_page
5227 ? DisallowActivationReasonId::kLoadPostCommitErrorPage
5228 : DisallowActivationReasonId::kBrowserInitiatedErrorPage)) {
5229 return nullptr;
5230 }
5231
5232 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
5233
5234 blink::mojom::CommonNavigationParamsPtr common_params =
5235 blink::CreateCommonNavigationParams();
5236 // |url| might be empty, such as when this method is called before
5237 // the frame actually committed (e.g. iframe with "src" set to a
5238 // slow-responding URL). We should rewrite the URL to about:blank in this
5239 // case, as the renderer will only think a page is an error page if it has a
5240 // non-empty unreachable URL.
5241 common_params->url = url.is_empty() ? GURL("about:blank") : url;
5242
5243 // Loading an error page via LoadPostCommitErrorPage() performs a temporary
5244 // replacement of the entire NavigationEntry and swaps it back in later.
5245 // All other error page types should permanently replace the current entry.
5246 if (!is_post_commit_error_page) {
5247 common_params->should_replace_current_entry = true;
5248 }
5249
5250 blink::mojom::CommitNavigationParamsPtr commit_params =
5251 blink::CreateCommitNavigationParams();
5252 commit_params->original_url = common_params->url;
5253
5254 commit_params->navigation_timing->system_entropy_at_navigation_start =
5255 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
5256 node, blink::mojom::SystemEntropy::kNormal);
5257
5258 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
5259 // error pages.
5260 commit_params->frame_policy = node->pending_frame_policy();
5261
5262 std::unique_ptr<NavigationRequest> navigation_request =
5263 NavigationRequest::CreateBrowserInitiated(
5264 node, std::move(common_params), std::move(commit_params),
5265 false /* was_opener_suppressed */, "" /* extra_headers */,
5266 nullptr /* frame_entry */, nullptr /* entry */,
5267 false /* is_form_submission */, nullptr /* navigation_ui_data */,
5268 std::nullopt /* impression */, false /* is_pdf */);
5269 if (is_post_commit_error_page) {
5270 navigation_request->set_browser_initiated_error_navigation_type(
5271 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit);
5272 } else {
5273 navigation_request->set_browser_initiated_error_navigation_type(
5274 NavigationRequest::BrowserInitiatedErrorNavigationType::kRegular);
5275 }
5276 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
5277 navigation_request->set_error_page_html(error_page_html);
5278 return navigation_request;
5279}
5280
[email protected]8ff00d72012-10-23 19:12:215281} // namespace content