blob: fe7a7a7fd3219f398f175b164d7ce0289eb4ddfb [file] [log] [blame]
Avi Drissman4e1b7bc32022-09-15 14:03:501// Copyright 2013 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
creis4e2ecb72015-06-20 00:46:305/*
6 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
9 * (http://www.torchmobile.com/)
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 *
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
21 * its contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
25 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
28 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35
danakjc492bf82020-09-09 20:02:4436#include "content/browser/renderer_host/navigation_controller_impl.h"
initial.commit09911bf2008-07-26 23:55:2937
Lei Zhang96031532019-10-10 19:05:4738#include <algorithm>
dcheng36b6aec92015-12-26 06:16:3639#include <utility>
40
[email protected]eabfe1912014-05-12 10:07:2841#include "base/command_line.h"
Ayu Ishii2f825852022-03-08 19:47:3842#include "base/containers/adapters.h"
Lei Zhang302bc3fa2025-06-04 20:10:3443#include "base/debug/crash_logging.h"
Rakina Zata Amni627360d2022-02-24 00:53:4044#include "base/debug/dump_without_crashing.h"
Avi Drissmanadac21992023-01-11 23:46:3945#include "base/functional/bind.h"
initial.commit09911bf2008-07-26 23:55:2946#include "base/logging.h"
asvitkine30330812016-08-30 04:01:0847#include "base/metrics/histogram_macros.h"
Kevin McNee37a109792025-04-14 21:16:3848#include "base/not_fatal_until.h"
Charlie Reis23c26da2022-01-29 00:57:4749#include "base/numerics/safe_conversions.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3950#include "base/strings/escape.h"
[email protected]348fbaac2013-06-11 06:31:5151#include "base/strings/string_util.h"
Daniel Cheng17390fd2025-06-07 06:38:2652#include "base/strings/string_view_util.h"
[email protected]74ebfb12013-06-07 20:48:0053#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3754#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0055#include "base/trace_event/optional_trace_event.h"
ssid3e765612015-01-28 04:03:4256#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0857#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5958#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2859#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1860#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3961#include "content/browser/blob_storage/chrome_blob_storage_context.h"
William Liu055a3542023-04-02 17:21:1962#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3163#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4164#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0465#include "content/browser/dom_storage/session_storage_namespace_impl.h"
Nate Chapinc06cf80a2023-11-18 01:12:2566#include "content/browser/preloading/prerender/prerender_host.h"
Sharon Yang242ef822023-05-15 21:07:3267#include "content/browser/process_lock.h"
Mingyu Lei68f34412023-08-21 07:31:3768#include "content/browser/renderer_host/back_forward_cache_impl.h"
danakjc492bf82020-09-09 20:02:4469#include "content/browser/renderer_host/debug_urls.h"
70#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0071#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3372#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4473#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5774#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4475#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1976#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
77#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
Khushal Sagar94ea2dc2024-08-06 17:15:2678#include "content/browser/renderer_host/navigation_transitions/navigation_transition_config.h"
danakjc492bf82020-09-09 20:02:4479#include "content/browser/renderer_host/navigator.h"
Takashi Toyoshima4dad2c12023-11-13 10:04:4680#include "content/browser/renderer_host/page_delegate.h"
danakjc492bf82020-09-09 20:02:4481#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0082#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0783#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3284#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3385#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4286#include "content/common/content_constants_internal.h"
Rakina Zata Amni84a859df2024-06-07 15:56:3287#include "content/common/content_navigation_policy.h"
Nate Chapind1fe3612021-04-16 20:45:5788#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5189#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1190#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1991#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1192#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4693#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0094#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4795#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5896#include "content/public/browser/render_widget_host.h"
97#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1098#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3499#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:19100#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:38101#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:10102#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47103#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43104#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59105#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36106#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57107#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18108#include "services/metrics/public/cpp/ukm_builders.h"
109#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17110#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37111#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44112#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58113#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39114#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30115#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21116#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06117#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43118#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50119#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31120#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51121#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46122#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26123#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29124
[email protected]8ff00d72012-10-23 19:12:21125namespace content {
[email protected]e9ba4472008-09-14 15:42:43126namespace {
127
Charlie Reis655c8f02025-05-15 01:16:17128// Feature to skip a redundant NavigationRequest creation for bfcache
129// activations, per https://crbug.com/417251428.
Charlie Reis3696ab62025-05-28 07:02:30130// TODO(crbug.com/420275259): Diagnose crashes and enable by default.
Charlie Reis655c8f02025-05-15 01:16:17131BASE_FEATURE(kSkipExtraBfcacheNavigationRequest,
132 "SkipExtraBfcacheNavigationRequest",
Charlie Reis3696ab62025-05-28 07:02:30133 base::FEATURE_DISABLED_BY_DEFAULT);
Charlie Reis655c8f02025-05-15 01:16:17134
[email protected]e9ba4472008-09-14 15:42:43135// Invoked when entries have been pruned, or removed. For example, if the
136// current entries are [google, digg, yahoo], with the current entry google,
137// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47138void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50139 int index,
[email protected]c12bf1a12008-09-17 16:28:49140 int count) {
[email protected]8ff00d72012-10-23 19:12:21141 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50142 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49143 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14144 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43145}
146
[email protected]e9ba4472008-09-14 15:42:43147// Configure all the NavigationEntries in entries for restore. This resets
148// the transition type to reload and makes sure the content state isn't empty.
149void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57150 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48151 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47152 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43153 // Use a transition type of reload so that we don't incorrectly increase
154 // the typed count.
Lei Zhang96031532019-10-10 19:05:47155 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
156 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43157 }
158}
159
[email protected]bf70edce2012-06-20 22:32:22160// Determines whether or not we should be carrying over a user agent override
161// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57162bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22163 return last_entry && last_entry->GetIsOverridingUserAgent();
164}
165
Camille Lamy5193caa2018-10-12 11:59:42166// Determines whether to override user agent for a navigation.
167bool ShouldOverrideUserAgent(
168 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57169 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42170 switch (override_user_agent) {
171 case NavigationController::UA_OVERRIDE_INHERIT:
172 return ShouldKeepOverride(last_committed_entry);
173 case NavigationController::UA_OVERRIDE_TRUE:
174 return true;
175 case NavigationController::UA_OVERRIDE_FALSE:
176 return false;
Camille Lamy5193caa2018-10-12 11:59:42177 }
Peter Boströmfc7ddc182024-10-31 19:37:21178 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42179}
180
Rakina Zata Amni312822d72021-06-04 16:13:37181// Returns true if this navigation should be treated as a reload. For e.g.
Liang Zhao0351d762024-11-13 00:10:07182// clicking on a link which results in a navigation to the last committed URL
183// (but wasn't converted to do a replacement navigation in the renderer), etc.
184// This intentionally excludes navigating to the last committed URL via the
185// address bar, so that the current scroll position is not restored.
Fergal Daly766177d2020-07-07 07:54:04186// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
187// |base_url_for_data_url|, |transition_type| correspond to the new navigation
188// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
189// navigation that committed.
190bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
191 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57192 const GURL& virtual_url,
193 const GURL& base_url_for_data_url,
194 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57195 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37196 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57197 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37198 // Navigations intended to do a replacement shouldn't be converted to do a
199 // reload.
200 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28201 return false;
clamy0a656e42018-02-06 18:18:28202 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45203 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55204 return false;
205
arthursonzogni7a8243682017-12-14 16:41:42206 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28207 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42208 return false;
209
Liang Zhao0351d762024-11-13 00:10:07210 // Same URL navigations from the address bar should only be treated as reloads
211 // if PAGE_TRANSITION_RELOAD is set (not for PAGE_TRANSITION_TYPED or
212 // PAGE_TRANSITION_LINK). In non-address-bar cases, PAGE_TRANSITION_TYPED
213 // and PAGE_TRANSITION_LINK can be treated as reloads.
clamy0a656e42018-02-06 18:18:28214 bool transition_type_can_be_converted = false;
Liang Zhao0351d762024-11-13 00:10:07215 if (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
216 if (ui::PageTransitionCoreTypeIs(transition_type,
217 ui::PAGE_TRANSITION_RELOAD)) {
218 transition_type_can_be_converted = true;
219 }
220 } else {
221 if (ui::PageTransitionCoreTypeIs(transition_type,
222 ui::PAGE_TRANSITION_TYPED) ||
223 ui::PageTransitionCoreTypeIs(transition_type,
224 ui::PAGE_TRANSITION_LINK)) {
225 transition_type_can_be_converted = true;
226 }
ananta3bdd8ae2016-12-22 17:11:55227 }
clamy0a656e42018-02-06 18:18:28228 if (!transition_type_can_be_converted)
229 return false;
230
231 // This check is required for cases like view-source:, etc. Here the URL of
232 // the navigation entry would contain the url of the page, while the virtual
233 // URL contains the full URL including the view-source prefix.
234 if (virtual_url != last_committed_entry->GetVirtualURL())
235 return false;
236
Fergal Daly766177d2020-07-07 07:54:04237 // Check that the URLs match.
238 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
239 // If there's no frame entry then by definition the URLs don't match.
240 if (!frame_entry)
241 return false;
242
243 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28244 return false;
245
246 // This check is required for Android WebView loadDataWithBaseURL. Apps
247 // can pass in anything in the base URL and we need to ensure that these
248 // match before classifying it as a reload.
249 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
250 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
251 return false;
ananta3bdd8ae2016-12-22 17:11:55252 }
253
clamy0a656e42018-02-06 18:18:28254 // Skip entries with SSL errors.
255 if (last_committed_entry->ssl_error())
256 return false;
257
258 // Don't convert to a reload when the last navigation was a POST or the new
259 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04260 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28261 return false;
262
263 return true;
ananta3bdd8ae2016-12-22 17:11:55264}
265
Arthur Sonzognic686e8f2024-01-11 08:36:37266std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12267 const mojom::DidCommitProvisionalLoadParams& params,
268 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32269 // Error pages commit in an opaque origin, yet have the real URL that resulted
270 // in an error as the |params.url|. Since successful reload of an error page
271 // should commit in the correct origin, setting the opaque origin on the
272 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17273 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37274 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32275
Arthur Sonzognic686e8f2024-01-11 08:36:37276 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32277}
278
Alex Moshchuk99242832023-05-22 17:21:44279bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42280 const GURL& virtual_url,
281 const GURL& dest_url) {
282 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44283 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
284 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42285 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
286 << virtual_url.possibly_invalid_spec();
287 return false;
288 }
289
290 // Don't attempt to navigate to non-empty invalid URLs.
291 if (!dest_url.is_valid() && !dest_url.is_empty()) {
292 LOG(WARNING) << "Refusing to load invalid URL: "
293 << dest_url.possibly_invalid_spec();
294 return false;
295 }
296
297 // The renderer will reject IPC messages with URLs longer than
298 // this limit, so don't attempt to navigate with a longer URL.
299 if (dest_url.spec().size() > url::kMaxURLChars) {
300 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
301 << " characters.";
302 return false;
303 }
304
Aaron Colwell33109c592020-04-21 21:31:19305 // Reject renderer debug URLs because they should have been handled before
306 // we get to this point. This check handles renderer debug URLs
307 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
308 // provides defense-in-depth if a renderer debug URL manages to get here via
309 // some other path. We want to reject the navigation here so it doesn't
310 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30311 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19312 LOG(WARNING) << "Refusing to load renderer debug URL: "
313 << dest_url.possibly_invalid_spec();
314 return false;
315 }
316
Alex Moshchuk99242832023-05-22 17:21:44317 // Guests only support navigations to known-safe schemes. This check already
318 // exists in the extensions layer, where it also dispatches proper events to
319 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
320 // for defense-in-depth to ensure that no other places in the codebase
321 // accidentally navigate guests to schemes such as WebUI, which is not
322 // supported. See https://crbug.com/1444221.
323 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
324 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
325 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
326 !dest_url.SchemeIs(url::kAboutScheme)) {
327 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
328 << dest_url.possibly_invalid_spec();
329 return false;
330 }
331 }
332
Camille Lamy5193caa2018-10-12 11:59:42333 return true;
334}
335
Mikel Astizba9cf2fd2017-12-17 10:38:10336// See replaced_navigation_entry_data.h for details: this information is meant
337// to ensure |*output_entry| keeps track of its original URL (landing page in
338// case of server redirects) as it gets replaced (e.g. history.replaceState()),
339// without overwriting it later, for main frames.
340void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57341 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10342 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17343 if (output_entry->GetReplacedEntryData().has_value() ||
344 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10345 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17346 }
Mikel Astizba9cf2fd2017-12-17 10:38:10347
348 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57349 data.first_committed_url = replaced_entry->GetURL();
350 data.first_timestamp = replaced_entry->GetTimestamp();
351 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29352 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10353}
354
Minggang Wangb9f3fa92021-07-01 15:30:31355blink::mojom::NavigationType GetNavigationType(
356 const GURL& old_url,
357 const GURL& new_url,
358 ReloadType reload_type,
359 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52360 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31361 bool has_pending_cross_document_commit,
362 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49363 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13364 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49365 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23366 // Reload navigations
367 switch (reload_type) {
368 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31369 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23370 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31371 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23372 case ReloadType::NONE:
373 break; // Fall through to rest of function.
374 }
375
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08376 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31377 return entry->GetHasPostData()
378 ? blink::mojom::NavigationType::RESTORE_WITH_POST
379 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23380 }
381
danakjb952ef12021-01-14 19:58:49382 const bool can_be_same_document =
383 // A pending cross-document commit means this navigation will not occur in
384 // the current document, as that document would end up being replaced in
385 // the meantime.
386 !has_pending_cross_document_commit &&
387 // If the current document is an error page, we should always treat it as
388 // a different-document navigation so that we'll attempt to load the
389 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49390 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13391 // If the navigation is an embedder-initiated navigation of a fenced
392 // frame root (i.e. enters a fenced frame tree from outside),
393 // same-document navigations should be disabled because we don't want to
394 // allow information to be joined across multiple embedder-initiated
395 // fenced frame navigations (which may contain separate cross-site data).
396 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49397 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
398 // same-document navigations should be disabled because we want to force
399 // the creation of a new browsing context group.
400 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12401
clamyea99ea12018-05-28 13:54:23402 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52403 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12404 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31405 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
406 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23407 }
408 DCHECK(!is_same_document_history_load);
409
410 // A same-document fragment-navigation happens when the only part of the url
411 // that is modified is after the '#' character.
412 //
413 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12414 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23415 //
416 // Note: this check is only valid for navigations that are not history
417 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
418 // history navigation from 'A#foo' to 'A#bar' is not a same-document
419 // navigation, but a different-document one. This is why history navigation
420 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47421 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52422 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12423
424 // The one case where we do the wrong thing here and incorrectly choose
425 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
426 // the renderer is a frameset. All frameset navigations should be
427 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
428 // navigation would do the right thing, as it would send it to the browser and
429 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
430 // into this method). But since we can't tell that case here for browser-
431 // initiated navigations, we have to get the renderer involved. In that case
432 // the navigation would be restarted due to the renderer spending a reply of
433 // mojom::CommitResult::RestartCrossDocument.
434
435 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31436 ? blink::mojom::NavigationType::SAME_DOCUMENT
437 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23438}
439
Camille Lamy5193caa2018-10-12 11:59:42440// Adjusts the original input URL if needed, to get the URL to actually load and
441// the virtual URL, which may differ.
442void RewriteUrlForNavigation(const GURL& original_url,
443 BrowserContext* browser_context,
444 GURL* url_to_load,
445 GURL* virtual_url,
446 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42447 // Allow the browser URL handler to rewrite the URL. This will, for example,
448 // remove "view-source:" from the beginning of the URL to get the URL that
449 // will actually be loaded. This real URL won't be shown to the user, just
450 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31451 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42452 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
453 url_to_load, browser_context, reverse_on_redirect);
454}
455
456#if DCHECK_IS_ON()
457// Helper sanity check function used in debug mode.
458void ValidateRequestMatchesEntry(NavigationRequest* request,
459 NavigationEntryImpl* entry) {
460 if (request->frame_tree_node()->IsMainFrame()) {
461 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
462 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31463 ui::PageTransitionFromInt(request->common_params().transition),
464 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42465 }
Nasko Oskovc36327d2019-01-03 23:23:04466 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42467 entry->should_clear_history_list());
468 DCHECK_EQ(request->common_params().has_user_gesture,
469 entry->has_user_gesture());
470 DCHECK_EQ(request->common_params().base_url_for_data_url,
471 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04472 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42473 entry->GetCanLoadLocalResources());
474 DCHECK_EQ(request->common_params().started_from_context_menu,
475 entry->has_started_from_context_menu());
476
477 FrameNavigationEntry* frame_entry =
478 entry->GetFrameEntry(request->frame_tree_node());
479 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52480 // TODO(https://crbug.com/40467594): This case should be unreachable once
481 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42482 return;
483 }
484
Camille Lamy5193caa2018-10-12 11:59:42485 DCHECK_EQ(request->common_params().method, frame_entry->method());
486
Nasko Oskovc36327d2019-01-03 23:23:04487 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42488 if (redirect_size == frame_entry->redirect_chain().size()) {
489 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04490 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42491 frame_entry->redirect_chain()[i]);
492 }
493 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21494 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42495 }
496}
497#endif // DCHECK_IS_ON()
498
Dave Tapuska8bfd84c2019-03-26 20:47:16499// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20500// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16501bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20502 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16503 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20504 DCHECK(sandboxed_initiator_rfh);
505 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
506 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16507 for (auto& item : navigations) {
508 bool within_subtree = false;
509 // Check whether this NavigationRequest affects a frame within the
510 // sandboxed frame's subtree by walking up the tree looking for the
511 // sandboxed frame.
512 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03513 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20514 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16515 within_subtree = true;
516 break;
517 }
518 }
519 if (!within_subtree)
520 return false;
521 }
522 return true;
523}
524
William Liu122754942024-01-18 22:34:39525// Used for "Navigation.SessionHistoryCount" histogram.
526enum class HistoryNavTypeForHistogram {
527 // A same-doc or cross-doc navigation of the main frame. We can only have one
528 // main frame request per `NavigationController::GoToIndex()`.
529 kMainFrame = 0,
530 // `NavigationController::GoToIndex()` creates one main frame request and
531 // one or more subframe requests.
532 kMainFrameAndSubframe,
533 // `NavigationController::GoToIndex()` creates one or more subframe requests.
534 kSubframe,
535 // Used for histogram boundary.
536 kCount
537};
538
539void CountRequests(
540 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
541 int& mutable_main_frame_cnt,
542 int& mutable_subframe_cnt) {
543 for (const auto& req : requests) {
544 if (req->IsInPrimaryMainFrame()) {
545 // We can only have one main frame navigation at a time.
546 CHECK_EQ(mutable_main_frame_cnt, 0);
547 ++mutable_main_frame_cnt;
548 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
549 ++mutable_subframe_cnt;
550 }
551 }
552}
553
554// Record the number of different types of navigations as histograms. See
555// `HistoryNavTypeForHistogram` for the types.
556void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
557 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
558 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
559 // We must have one request.
560 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
561
562 int main_frame_cnt = 0;
563 int subframe_cnt = 0;
564 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
565 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
566
567 std::optional<HistoryNavTypeForHistogram> history_nav_type;
568 if (main_frame_cnt > 0) {
569 if (subframe_cnt == 0) {
570 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
571 } else {
572 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
573 }
574 } else if (subframe_cnt > 0) {
575 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
576 }
577 if (history_nav_type.has_value()) {
578 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
579 history_nav_type.value(),
580 HistoryNavTypeForHistogram::kCount);
581 }
582}
583
[email protected]e9ba4472008-09-14 15:42:43584} // namespace
585
arthursonzogni66f711c2019-10-08 14:40:36586// NavigationControllerImpl::PendingEntryRef------------------------------------
587
588NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
589 base::WeakPtr<NavigationControllerImpl> controller)
590 : controller_(controller) {}
591
592NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
593 if (!controller_) // Can be null with interstitials.
594 return;
595
596 controller_->PendingEntryRefDeleted(this);
597}
598
Charlie Reisd3e4fef2025-05-20 02:04:17599// NavigationControllerImpl::ScopedPendingEntryReentrancyGuard------------------
600
601NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
602 ScopedPendingEntryReentrancyGuard(
603 base::SafeRef<NavigationControllerImpl> controller)
604 : controller_(controller) {
605 // Navigations that involve pending entries do not support re-entrancy.
606 // Encountering this CHECK failure means the caller is attempting to start
607 // another navigation while a navigation to an existing pending entry is on
608 // the stack. In most cases, the new navigation should be done from a posted
609 // task instead. See http://crbug.com/40353566 for context.
610 CHECK(!controller->in_navigate_to_pending_entry_);
611
612 controller->in_navigate_to_pending_entry_ = true;
613 controller->CheckPotentialNavigationReentrancy();
614
615 // It must not be possible to delete the pending NavigationEntry while
616 // navigating to it. Grab a reference to delay potential deletion until
617 // this scoped object is deleted at the end of the relevant function call.
618 pending_entry_ref_ = controller->ReferencePendingEntry();
619}
620
621NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
622 ~ScopedPendingEntryReentrancyGuard() {
623 controller_->in_navigate_to_pending_entry_ = false;
624}
625
[email protected]d202a7c2012-01-04 07:53:47626// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29627
[email protected]23a918b2014-07-15 09:51:36628const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23629
[email protected]765b35502008-08-21 00:51:20630// static
[email protected]d202a7c2012-01-04 07:53:47631size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23632 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20633
[email protected]e6fec472013-05-14 05:29:02634// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20635// when testing.
636static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29637
[email protected]71fde352011-12-29 03:29:56638// static
dcheng9bfa5162016-04-09 01:00:57639std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
640 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10641 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37642 std::optional<url::Origin> initiator_origin,
643 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10644 ui::PageTransition transition,
645 bool is_renderer_initiated,
646 const std::string& extra_headers,
647 BrowserContext* browser_context,
648 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
649 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21650 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37651 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32652 is_renderer_initiated, extra_headers, browser_context,
653 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10654}
655
656// static
657std::unique_ptr<NavigationEntryImpl>
658NavigationControllerImpl::CreateNavigationEntry(
659 const GURL& url,
660 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37661 std::optional<url::Origin> initiator_origin,
662 std::optional<GURL> initiator_base_url,
663 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57664 ui::PageTransition transition,
665 bool is_renderer_initiated,
666 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09667 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17668 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
669 bool rewrite_virtual_urls) {
670 GURL url_to_load = url;
671 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56672 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17673 if (rewrite_virtual_urls) {
674 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
675 &reverse_on_redirect);
676 }
Lukasz Anforowicz641234d52019-11-07 21:07:10677 // Let the NTP override the navigation params and pretend that this is a
678 // browser-initiated, bookmark-like navigation.
679 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32680 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21681 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10682
Patrick Monettef507e982019-06-19 20:18:06683 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28684 nullptr, // The site instance for tabs is sent on navigation
685 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21686 url_to_load, referrer, initiator_origin, initiator_base_url,
687 std::u16string(), transition, is_renderer_initiated,
688 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17689 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42690 entry->SetVirtualURL(virtual_url);
691 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56692 entry->set_update_virtual_url_with_url(reverse_on_redirect);
693 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06694 return entry;
[email protected]71fde352011-12-29 03:29:56695}
696
[email protected]cdcb1dee2012-01-04 00:46:20697// static
698void NavigationController::DisablePromptOnRepost() {
699 g_check_for_repost = false;
700}
701
[email protected]c5b88d82012-10-06 17:03:33702base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
703 base::Time t) {
704 // If |t| is between the water marks, we're in a run of duplicates
705 // or just getting out of it, so increase the high-water mark to get
706 // a time that probably hasn't been used before and return it.
707 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35708 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33709 return high_water_mark_;
710 }
711
712 // Otherwise, we're clear of the last duplicate run, so reset the
713 // water marks.
714 low_water_mark_ = high_water_mark_ = t;
715 return t;
716}
717
ckitagawa0faa5e42020-06-17 17:30:54718NavigationControllerImpl::ScopedShowRepostDialogForTesting::
719 ScopedShowRepostDialogForTesting()
720 : was_disallowed_(g_check_for_repost) {
721 g_check_for_repost = true;
722}
723
724NavigationControllerImpl::ScopedShowRepostDialogForTesting::
725 ~ScopedShowRepostDialogForTesting() {
726 g_check_for_repost = was_disallowed_;
727}
728
Nate Chapin9eb16be72022-09-23 22:54:31729NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
730 base::SafeRef<NavigationControllerImpl> controller)
731 : controller_(controller) {
732 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
733 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
734 frame_tree_node_id_to_keys_.insert(
735 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
736 if (auto* frame_entry = frame_tree_node->current_frame_host()
737 ->last_committed_frame_entry()) {
738 frame_tree_node_id_to_doc_seq_nos_.insert(
739 {frame_tree_node->frame_tree_node_id(),
740 frame_entry->document_sequence_number()});
741 }
742 }
743 PopulateKeySet(Direction::kBack);
744 PopulateKeySet(Direction::kForward);
745}
746
747void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
748 Direction direction) {
749 // Keep track of which FrameTreeNodes may still have relevant API keys in
750 // additional FrameNavigationEntries.
751 std::set<FrameTreeNode*> nodes_to_process;
752 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
753 nodes_to_process.insert(node);
754 }
755
756 const int offset = direction == Direction::kForward ? 1 : -1;
757 const int start = direction == Direction::kForward
758 ? controller_->GetLastCommittedEntryIndex()
759 : controller_->GetLastCommittedEntryIndex() - 1;
760 for (int i = start;
761 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
762 i += offset) {
763 std::set<FrameTreeNode*> nodes_to_continue_processing;
764
765 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
766 entry->ForEachFrameEntry([this, &nodes_to_process,
767 &nodes_to_continue_processing,
768 &entry](FrameNavigationEntry* frame_entry) {
769 // Find the |node| that matches |frame_entry|, if any.
770 FrameTreeNode* node = nullptr;
771 if (frame_entry == entry->root_node()->frame_entry) {
772 node = controller_->frame_tree().root();
773 } else {
774 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
775 if (it == names_to_nodes_.end())
776 return;
777 node = it->second;
778 }
779
780 // Skip this node if a previous step determine there are no longer
781 // relevant navigation API keys in this direction.
782 if (nodes_to_process.find(node) == nodes_to_process.end())
783 return;
784
785 // Stop processing |node| if we reach a point where it's cross-origin.
786 // See also PopulateSingleNavigationApiHistoryEntryVector().
787 url::Origin frame_entry_origin =
788 frame_entry->committed_origin().value_or(url::Origin::Resolve(
789 frame_entry->url(),
790 frame_entry->initiator_origin().value_or(url::Origin())));
791 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
792 return;
793
794 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
795 frame_entry->navigation_api_key());
796 // Mark |node| as needing more processing for the next entry.
797 nodes_to_continue_processing.insert(node);
798
799 // Check whether |node| went cross-document. If so, its children are
800 // no longer the same conceptual iframe as the current one, and
801 // should no longer be processed. This check is intentionally done
802 // after processing the current |node|, which may still have relevant
803 // discarded API keys.
804 if (frame_entry->document_sequence_number() !=
805 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50806 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31807 nodes_to_process.erase(descendant);
808 }
809 });
810
811 nodes_to_process.swap(nodes_to_continue_processing);
812 }
813}
814
815NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
816 std::set<std::string> all_keys;
817 // Find all remaining navigation API keys after some entries have been
818 // removed.
819 for (auto& entry : controller_->entries_) {
820 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
821 all_keys.insert(frame_entry->navigation_api_key());
822 });
823 }
824
825 // Notify each frame in the renderer of any disposed navigation API keys.
826 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
827 std::vector<std::string> disposed_keys;
828 for (const auto& key : id_to_keys.second) {
829 if (all_keys.find(key) == all_keys.end())
830 disposed_keys.push_back(key);
831 }
832 if (disposed_keys.empty())
833 continue;
834
835 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
836 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
837 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
838 }
839}
840
[email protected]d202a7c2012-01-04 07:53:47841NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00842 BrowserContext* browser_context,
843 FrameTree& frame_tree,
844 NavigationControllerDelegate* delegate)
845 : frame_tree_(frame_tree),
846 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57847 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22848 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37849 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
850 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37851 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29852}
853
[email protected]d202a7c2012-01-04 07:53:47854NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00855 // The NavigationControllerImpl might be called inside its delegate
856 // destructor. Calling it is not valid anymore.
857 delegate_ = nullptr;
858 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29859}
860
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57861BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55862 return browser_context_;
863}
864
[email protected]d202a7c2012-01-04 07:53:47865void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30866 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36867 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57868 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47869 // Note that it's possible for `entries_` to contain multiple entries at this
870 // point, as Restore() might be called on a NavigationController that is
871 // already used (e.g. due to WebView's restoreState() API), not only for fresh
872 // NavigationControllers. These entries are not cleared to preserve legacy
873 // behavior and also because `pending_entry_` might point to one of the
874 // pre-existing entries. An exception for this is when `entries_` contains
875 // only the initial NavigationEntry, which must be removed.
876
877 // Do not proceed if selected_navigation will be out of bounds for the updated
878 // entries_ list, since it will be assigned to last_committed_entry_index_ and
879 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58880 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47881 // is empty, since there should be no work to do (rather than marking the
882 // existing entries as needing reload). Also consider returning early if the
883 // selected index is -1, which represents a no-committed-entry state.
884 if (selected_navigation < -1 ||
885 selected_navigation >=
886 base::checked_cast<int>(entries->size() + entries_.size())) {
887 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24888 }
Charlie Reis23c26da2022-01-29 00:57:47889
Rakina Zata Amni46087a12022-11-11 08:28:38890 // There will always be at least one entry (new NavigationControllers will
891 // have the initial NavigationEntry).
892 if (selected_navigation == -1)
893 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47894
Rakina Zata Amni46087a12022-11-11 08:28:38895 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
896 // If we are on the initial NavigationEntry, it must be the only entry in
897 // the list. Since it's impossible to do a history navigation to the
898 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
899 // `pending_entry` might be set for a new non-history navigation).
900 // Note that we should not clear `entries_` if `entries` is empty (when
901 // InitialNavigationEntry mode is enabled), since that would leave us
902 // without any NavigationEntry.
903 CHECK_EQ(1, GetEntryCount());
904 CHECK_EQ(-1, pending_entry_index_);
905 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47906 }
[email protected]ce3fa3c2009-04-20 19:55:57907
[email protected]ce3fa3c2009-04-20 19:55:57908 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44909 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03910 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47911 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43912 if (entry->GetURL().is_empty()) {
913 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01914 // persisting the initial NavigationEntry [which is no longer possible but
915 // some old persisted sessions might still contain it] or when the
916 // serializer failed to write the URL because it's too long). Trying to
917 // restore and navigate to an entry with an empty URL will result in
918 // crashes, so change the URL to about:blank. See also
919 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43920 entry->SetURL(GURL(url::kAboutBlankURL));
921 }
dcheng36b6aec92015-12-26 06:16:36922 entries_.push_back(
923 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47924 }
avif16f85a72015-11-13 18:25:03925
926 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
927 // cleared out safely.
928 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57929
930 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36931 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57932}
933
toyoshim6142d96f2016-12-19 09:07:25934void NavigationControllerImpl::Reload(ReloadType reload_type,
935 bool check_for_repost) {
Charlie Reisf4d51f402025-05-23 18:00:49936 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:03937 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
938 (int)reload_type);
939 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
940 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28941 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28942 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32943 int current_index = -1;
944
Carlos IL42b416592019-10-07 23:10:36945 if (entry_replaced_by_post_commit_error_) {
946 // If there is an entry that was replaced by a currently active post-commit
947 // error navigation, this can't be the initial navigation.
948 DCHECK(!IsInitialNavigation());
949 // If the current entry is a post commit error, we reload the entry it
950 // replaced instead. We leave the error entry in place until a commit
951 // replaces it, but the pending entry points to the original entry in the
952 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
953 // case that pending_entry_ != entries_[pending_entry_index_].
954 entry = entry_replaced_by_post_commit_error_.get();
955 current_index = GetCurrentEntryIndex();
956 } else if (IsInitialNavigation() && pending_entry_) {
957 // If we are reloading the initial navigation, just use the current
958 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32959 entry = pending_entry_;
960 // The pending entry might be in entries_ (e.g., after a Clone), so we
961 // should also update the current_index.
962 current_index = pending_entry_index_;
963 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00964 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32965 current_index = GetCurrentEntryIndex();
966 if (current_index != -1) {
creis3da03872015-02-20 21:12:32967 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32968 }
[email protected]979a4bc2013-04-24 01:27:15969 }
[email protected]241db352013-04-22 18:04:05970
[email protected]59167c22013-06-03 18:07:32971 // If we are no where, then we can't reload. TODO(darin): We should add a
972 // CanReload method.
973 if (!entry)
974 return;
975
Rakina Zata Amnif297a802022-01-18 03:53:43976 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
977 // We should never navigate to an existing initial NavigationEntry that is
978 // the initial NavigationEntry for the initial empty document that hasn't
979 // been overridden by the synchronous about:blank commit, to preserve
980 // legacy behavior where trying to reload when the main frame is on the
981 // initial empty document won't result in a navigation. See also
982 // https://crbug.com/1277414.
983 return;
984 }
985
Aran Gilman37d11632019-10-08 23:07:15986 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30987 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07988 // they really want to do this. If they do, the dialog will call us back
989 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57990 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02991
[email protected]106a0812010-03-18 00:15:12992 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57993 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47994 return;
initial.commit09911bf2008-07-26 23:55:29995 }
Lei Zhang96031532019-10-10 19:05:47996
Wang Huia25efabc2022-09-24 17:27:22997 // Set ReloadType for |entry|.
998 entry->set_reload_type(reload_type);
999
Lei Zhang96031532019-10-10 19:05:471000 if (!IsInitialNavigation())
1001 DiscardNonCommittedEntries();
1002
1003 pending_entry_ = entry;
1004 pending_entry_index_ = current_index;
1005 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
1006
Nate Chapin45f620582021-09-30 17:45:431007 // location.reload() goes through BeginNavigation, so all reloads triggered
1008 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:131009 NavigateToExistingPendingEntry(
1010 reload_type,
1011 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371012 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491013 /*navigation_api_key=*/nullptr, actual_navigation_start);
initial.commit09911bf2008-07-26 23:55:291014}
1015
[email protected]d202a7c2012-01-04 07:53:471016void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:481017 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121018}
1019
[email protected]d202a7c2012-01-04 07:53:471020void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:491021 // If the pending reload type has been cleared by another navigation
1022 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:481023 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:491024 return;
[email protected]106a0812010-03-18 00:15:121025 }
Wang Hui96ab1012022-10-11 02:05:491026 Reload(pending_reload_, false);
1027 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121028}
1029
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571030bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:091031 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:111032}
1033
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571034bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:381035 // Check that we're on the initial NavigationEntry and that this is not a
1036 // cloned tab.
1037 return IsInitialNavigation() && GetEntryCount() == 1 &&
1038 GetLastCommittedEntry()->IsInitialEntry() &&
1039 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401040}
1041
Aran Gilman37d11632019-10-08 23:07:151042NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1043 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581044 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031045 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581046}
1047
Adithya Srinivasan9b0c99c2021-08-10 15:19:451048NavigationEntryImpl*
1049NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1050 int nav_entry_id) const {
1051 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1052 if (entry)
1053 return entry;
1054 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521055 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451056 : nullptr;
1057}
1058
W. James MacLeanc07dc41b2022-07-25 18:52:161059void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571060 const url::Origin& origin) {
1061 for (int i = 0; i < GetEntryCount(); i++) {
1062 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161063 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571064 }
1065 if (entry_replaced_by_post_commit_error_) {
1066 // It's possible we could come back to this entry if the error
1067 // page/interstitial goes away.
1068 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161069 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571070 }
W. James MacLean1c40862c2020-04-27 21:05:571071}
1072
avi25764702015-06-23 15:43:371073void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571074 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001075 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371076 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271077 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201078}
1079
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571080NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471081 if (pending_entry_)
1082 return pending_entry_;
1083 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201084}
1085
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571086NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321087 // The pending entry is safe to return for new (non-history), browser-
1088 // initiated navigations. Most renderer-initiated navigations should not
1089 // show the pending entry, to prevent URL spoof attacks.
1090 //
1091 // We make an exception for renderer-initiated navigations in new tabs, as
1092 // long as no other page has tried to access the initial empty document in
1093 // the new tab. If another page modifies this blank page, a URL spoof is
1094 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321095 bool safe_to_show_pending =
1096 pending_entry_ &&
1097 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091098 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321099 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461100 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321101
1102 // Also allow showing the pending entry for history navigations in a new tab,
1103 // such as Ctrl+Back. In this case, no existing page is visible and no one
1104 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151105 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1106 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321107 safe_to_show_pending = true;
1108
1109 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191110 return pending_entry_;
1111 return GetLastCommittedEntry();
1112}
1113
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571114int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201115 if (pending_entry_index_ != -1)
1116 return pending_entry_index_;
1117 return last_committed_entry_index_;
1118}
1119
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571120NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381121 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031122 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201123}
1124
Elad Alon32044f532025-03-04 22:16:031125const NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry()
1126 const {
1127 CHECK_NE(last_committed_entry_index_, -1);
1128 return entries_[last_committed_entry_index_].get();
1129}
1130
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571131bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351132 const std::string& mime_type = frame_tree_->root()
1133 ->current_frame_host()
1134 ->GetPage()
1135 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531136 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1137 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271138 NavigationEntry* visible_entry = GetVisibleEntry();
1139 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391140 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161141}
1142
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571143int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271144 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451145 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271146 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551147 return last_committed_entry_index_;
1148}
1149
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571150int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451151 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291152 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551153 return static_cast<int>(entries_.size());
1154}
1155
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571156NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371157 if (index < 0 || index >= GetEntryCount())
1158 return nullptr;
1159
avif16f85a72015-11-13 18:25:031160 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251161}
1162
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571163NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471164 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201165}
1166
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571167int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461168 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031169}
1170
Arthur Sonzognic686e8f2024-01-11 08:36:371171std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031172 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591173 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1174 return index;
1175 }
Shivani Sharma298d12852019-01-22 20:04:031176 }
Arthur Sonzognic686e8f2024-01-11 08:36:371177 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591178}
1179
1180bool NavigationControllerImpl::CanGoBack() {
1181 return GetIndexForGoBack().has_value();
1182}
1183
Arthur Sonzognic686e8f2024-01-11 08:36:371184std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591185 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1186 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1187 return index;
1188 }
1189 }
Arthur Sonzognic686e8f2024-01-11 08:36:371190 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201191}
1192
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571193bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591194 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201195}
1196
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571197bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031198 int index = GetIndexForOffset(offset);
1199 return index >= 0 && index < GetEntryCount();
1200}
1201
Xiaohan Wang7f8052e02022-01-14 18:44:281202#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151203bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151204 if (offset == 0)
1205 return true;
1206 int increment = offset > 0 ? 1 : -1;
1207 int non_skippable_entries = 0;
1208 for (int index = GetIndexForOffset(increment);
1209 index >= 0 && index < GetEntryCount(); index += increment) {
1210 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1211 non_skippable_entries++;
1212
1213 if (non_skippable_entries == std::abs(offset))
1214 return true;
1215 }
1216 return false;
1217}
1218#endif
1219
David Bokanb8e0df02025-05-14 22:03:481220NavigationController::WeakNavigationHandleVector
1221NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371222 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061223
Kevin McNeeedc481c2023-04-27 22:30:581224 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211225
David Bokanb8e0df02025-05-14 22:03:481226 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201227}
1228
David Bokanb8e0df02025-05-14 22:03:481229NavigationController::WeakNavigationHandleVector
1230NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161231 // Note that at least one entry (the last one) will be non-skippable since
1232 // entries are marked skippable only when they add another entry because of
1233 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371234 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591235
Kevin McNeeedc481c2023-04-27 22:30:581236 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591237
David Bokanb8e0df02025-05-14 22:03:481238 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201239}
1240
David Bokanb8e0df02025-05-14 22:03:481241NavigationController::WeakNavigationHandleVector
1242NavigationControllerImpl::GoToIndex(int index) {
1243 std::vector<base::WeakPtr<NavigationRequest>> requests =
1244 GoToIndex(index, /*initiator_rfh=*/nullptr,
1245 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491246 /*navigation_api_key=*/nullptr,
1247 /*actual_navigation_start=*/base::TimeTicks::Now());
David Bokanb8e0df02025-05-14 22:03:481248 std::vector<base::WeakPtr<NavigationHandle>> handles;
1249 std::ranges::move(requests, std::back_inserter(handles));
1250 return handles;
Dave Tapuska8bfd84c2019-03-26 20:47:161251}
1252
William Liu62ae26c2024-08-08 14:28:161253std::vector<base::WeakPtr<NavigationRequest>>
1254NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201255 int index,
1256 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371257 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131258 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491259 const std::string* navigation_api_key,
1260 base::TimeTicks actual_navigation_start) {
sunjian30574a62017-03-21 21:39:441261 TRACE_EVENT0("browser,navigation,benchmark",
1262 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501263 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1264 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1265 entries_.size());
1266 // Indices should have have been validated by the caller.
1267 CHECK_GE(index, 0);
1268 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201269
Rakina Zata Amnif297a802022-01-18 03:53:431270 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1271 // We should never navigate to an existing initial NavigationEntry that is
1272 // the initial NavigationEntry for the initial empty document that hasn't
1273 // been overridden by the synchronous about:blank commit, to preserve
1274 // legacy behavior where trying to reload when the main frame is on the
1275 // initial empty document won't result in a navigation. See also
1276 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161277 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431278 }
1279
[email protected]cbab76d2008-10-13 22:42:471280 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201281
arthursonzogni5c4c202d2017-04-25 23:41:271282 DCHECK_EQ(nullptr, pending_entry_);
1283 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431284
arthursonzogni5c4c202d2017-04-25 23:41:271285 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201286 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271287 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1288 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Charlie Reisf4d51f402025-05-23 18:00:491289 return NavigateToExistingPendingEntry(
1290 ReloadType::NONE, initiator_rfh, soft_navigation_heuristics_task_id,
1291 navigation_api_key, actual_navigation_start);
[email protected]765b35502008-08-21 00:51:201292}
1293
[email protected]d202a7c2012-01-04 07:53:471294void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121295 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031296 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201297 return;
1298
[email protected]9ba14052012-06-22 23:50:031299 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201300}
1301
Nate Chapinbf682fa32022-09-26 22:41:201302void NavigationControllerImpl::GoToOffsetFromRenderer(
1303 int offset,
Yoav Weiss8c573952022-11-17 17:35:131304 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371305 std::optional<blink::scheduler::TaskAttributionId>
Charlie Reisf4d51f402025-05-23 18:00:491306 soft_navigation_heuristics_task_id,
1307 base::TimeTicks actual_navigation_start) {
Nate Chapinbb74c5a52023-07-21 23:13:351308 // Note: This is actually reached in unit tests.
1309 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431310 return;
1311
Nate Chapinbf682fa32022-09-26 22:41:201312 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131313 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491314 /*navigation_api_key=*/nullptr, actual_navigation_start);
Nate Chapin45f620582021-09-30 17:45:431315}
1316
William Liu62ae26c2024-08-08 14:28:161317std::vector<base::WeakPtr<NavigationRequest>>
1318NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271319 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1320 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491321 /*navigation_api_key=*/nullptr,
1322 /*actual_navigation_start=*/base::TimeTicks::Now());
William Liuec04e382024-05-23 18:03:271323}
1324
Xiaohan Wang7f8052e02022-01-14 18:44:281325#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151326void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1327 // Note: This is actually reached in unit tests.
1328 if (!CanGoToOffsetWithSkipping(offset))
1329 return;
1330
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421331 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151332 GoToIndex(GetIndexForOffset(offset));
1333 return;
1334 }
1335 int increment = offset > 0 ? 1 : -1;
1336 // Find the offset without counting skippable entries.
1337 int target_index = GetIndexForOffset(increment);
1338 int non_skippable_entries = 0;
1339 for (int index = target_index; index >= 0 && index < GetEntryCount();
1340 index += increment) {
1341 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1342 non_skippable_entries++;
1343
1344 if (non_skippable_entries == std::abs(offset)) {
1345 target_index = index;
1346 break;
1347 }
1348 }
1349
1350 GoToIndex(target_index);
1351}
1352#endif
1353
[email protected]41374f12013-07-24 02:49:281354bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151355 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281356 return false;
[email protected]6a13a6c2011-12-20 21:47:121357
[email protected]43032342011-03-21 14:10:311358 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281359 return true;
[email protected]cbab76d2008-10-13 22:42:471360}
1361
Michael Thiessen9b14d512019-09-23 21:19:471362void NavigationControllerImpl::PruneForwardEntries() {
1363 DiscardNonCommittedEntries();
1364 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471365 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471366 if (num_removed <= 0)
1367 return;
Nate Chapin9eb16be72022-09-23 22:54:311368 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471369 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1370 NotifyPrunedEntries(this, remove_start_index /* start index */,
1371 num_removed /* count */);
1372}
1373
Aran Gilman37d11632019-10-08 23:07:151374void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1375 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321376 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311377 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511378 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1379 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321380 }
1381}
1382
Harkiran Bolariaba823e42021-05-21 18:30:361383base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1384 const GURL& url,
1385 const Referrer& referrer,
1386 ui::PageTransition transition,
1387 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471388 LoadURLParams params(url);
1389 params.referrer = referrer;
1390 params.transition_type = transition;
1391 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361392 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471393}
1394
Harkiran Bolariaba823e42021-05-21 18:30:361395base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1396 const LoadURLParams& params) {
Charlie Reisf4d51f402025-05-23 18:00:491397 // For now, treat this as the actual navigation start time, even though a fair
1398 // amount of work is done in the browser process between the various ways to
1399 // start a navigation and reaching here (e.g., sending OpenURLParams through
1400 // the embedder and converting them to LoadURLParams). Note that this may be
1401 // used for some renderer-initiated navigations that go through
1402 // RenderFrameHostImpl::OpenURL as well.
1403 // TODO(crbug.com/385170155): Consider whether tracking this earlier work with
1404 // an earlier start time is worthwhile for metrics.
1405 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
1406
Lukasz Anforowicz435bcb582019-07-12 20:50:061407 if (params.is_renderer_initiated)
1408 DCHECK(params.initiator_origin.has_value());
1409
naskob8744d22014-08-28 17:07:431410 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151411 "NavigationControllerImpl::LoadURLWithParams", "url",
1412 params.url.possibly_invalid_spec());
Emmanuel Arias Soto9e159652025-05-16 07:53:551413
1414 if (IsDebugURL(params.url)) {
1415 // Browser-debug URLs won't go through NavigationThrottles so we have to
1416 // check them explicitly. See crbug.com/40605746.
1417 ContentBrowserClient* client = GetContentClient()->browser();
1418 if (client->ShouldBlockRendererDebugURL(
1419 params.url, browser_context_,
1420 GetTargetFrameTreeNodeForNavigation(params)
1421 ->current_frame_host())) {
1422 DiscardPendingEntry(false);
1423 return nullptr;
1424 }
1425 HandleDebugURL(params.url, params.transition_type,
1426 client->IsExplicitNavigation(params.transition_type));
[email protected]47752982014-07-29 08:01:431427 // If Telemetry is running, allow the URL load to proceed as if it's
1428 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491429 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181430 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361431 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181432 }
[email protected]47752982014-07-29 08:01:431433 }
[email protected]8bf1048012012-02-08 01:22:181434
[email protected]cf002332012-08-14 19:17:471435 // Checks based on params.load_type.
1436 switch (params.load_type) {
1437 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431438 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541439#if BUILDFLAG(IS_ANDROID)
1440 case LOAD_TYPE_PDF_ANDROID:
1441#endif
[email protected]cf002332012-08-14 19:17:471442 break;
1443 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261444 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211445 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471446 }
1447 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461448 }
[email protected]e47ae9472011-10-13 19:48:341449
[email protected]e47ae9472011-10-13 19:48:341450 // The user initiated a load, we don't need to reload anymore.
1451 needs_reload_ = false;
1452
Charlie Reisf4d51f402025-05-23 18:00:491453 return NavigateWithoutEntry(params, actual_navigation_start);
[email protected]132e281a2012-07-31 18:32:441454}
1455
Charlie Reis4c53a962023-06-21 23:17:531456void NavigationControllerImpl::LoadOriginalRequestURL() {
1457 // If the original request URL is not valid, matches the current URL, or
1458 // involves POST data, then simply reload. The POST check avoids issues with
1459 // sending data to the wrong page.
1460 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1461 const GURL& original_request_url =
1462 GetLastCommittedEntry()->GetOriginalRequestURL();
1463 if (!original_request_url.is_valid() ||
1464 original_request_url == last_committed_url ||
1465 GetLastCommittedEntry()->GetHasPostData()) {
1466 Reload(ReloadType::NORMAL, true);
1467 return;
1468 }
1469
1470 // Otherwise, attempt to load the original request URL without any of the
1471 // other data from the current NavigationEntry, replacing the current entry.
1472 // Loading the original URL is useful in cases such as modifying the user
1473 // agent.
1474 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1475 std::make_unique<NavigationController::LoadURLParams>(
1476 original_request_url);
1477 load_params->should_replace_current_entry = true;
1478 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1479 LoadURLWithParams(*load_params.get());
1480}
1481
Mohamed Abdelhalim833de902019-09-16 17:41:451482bool NavigationControllerImpl::PendingEntryMatchesRequest(
1483 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191484 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451485 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191486}
1487
[email protected]d202a7c2012-01-04 07:53:471488bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321489 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071490 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331491 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441492 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251493 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561494 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131495 NavigationRequest* navigation_request) {
1496 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331497
1498 // Note: validation checks and renderer kills due to invalid commit messages
1499 // must happen before getting here, in
1500 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1501 // effects of the navigation have already occurred.
1502
[email protected]cd2e15742013-03-08 04:08:311503 is_initial_navigation_ = false;
1504
Wang Hui96ab1012022-10-11 02:05:491505 // Any pending request to repost a form submission is no longer valid, since a
1506 // different NavigationEntry is committing.
1507 pending_reload_ = ReloadType::NONE;
1508
[email protected]0e8db942008-09-24 21:21:481509 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431510 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451511 if (entry_replaced_by_post_commit_error_) {
1512 // Same document navigation events with a post-commit error should already
1513 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1514 // reaching here.
1515 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331516
Xinghui Lub9e86a352024-05-17 16:29:421517 if (pending_entry_) {
1518 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1519 // `pending_entry_` isn't pointing to the last committed entry.
1520 // Instead, all reload approaches (e.g., in `Reload` and
1521 // `LoadIfNecessary`) should attempt to load the
1522 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1523 // entry itself.
1524 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1525 << "Incorrectly reloading the post commit error page entry.";
1526 }
Xinghui Lue4e50be2024-05-15 21:46:001527
Rakina Zata Amnie2d31312022-11-18 03:38:451528 // Any commit while a post-commit error page is showing should put the
1529 // original entry back, replacing the error page's entry. This includes
1530 // reloads, where the original entry was used as the pending entry and
1531 // should now be at the correct index at commit time.
1532 entries_[last_committed_entry_index_] =
1533 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481534 }
Rakina Zata Amnie2d31312022-11-18 03:38:451535 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1536 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001537 // Must honor user agent overrides in the |navigation_request|, such as
1538 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1539 // result, besides comparing |pending_entry_|'s user agent against
1540 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1541 // agent against LastCommittedEntry's.
1542 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541543 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1544 (PendingEntryMatchesRequest(navigation_request) &&
1545 pending_entry_->GetIsOverridingUserAgent() !=
1546 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001547 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451548 }
[email protected]ecd9d8702008-08-28 22:10:171549
Dave Tapuskaa2ab4f252021-07-08 21:31:281550 bool is_main_frame_navigation = !rfh->GetParent();
1551
Alexander Timind2f2e4f22019-04-02 20:04:531552 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1553 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281554 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141555 // BackForwardCacheMetrics to be associated with the new navigation's
1556 // NavigationEntry, by either creating a new object or reusing the previous
1557 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281558 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211559 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141560 back_forward_cache_metrics = BackForwardCacheMetrics::
1561 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281562 GetLastCommittedEntry(), is_main_frame_navigation,
1563 params.document_sequence_number);
1564 }
Yuzu Saijo29f96ca92022-12-08 04:54:121565
Alexander Timind2f2e4f22019-04-02 20:04:531566 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281567 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451568 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1569 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531570 }
1571 }
1572
Rakina Zata Amnifd8370b2022-11-14 13:32:251573 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1574 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091575 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251576 details->did_replace_entry =
1577 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091578
fdegans9caf66a2015-07-30 21:10:421579 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111580 // except for restored entries. This should be true even if the current commit
1581 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291582 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481583 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081584 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111585
1586 // Only make changes based on the pending entry if the NavigationRequest
1587 // matches it. Otherwise, the pending entry may be for a different request
1588 // (e.g., if a slow history navigation is pending while an auto-subframe
1589 // commit occurs).
1590 if (PendingEntryMatchesRequest(navigation_request)) {
1591 // It is no longer necessary to consider the pending entry as restored.
1592 if (pending_entry_->IsRestored()) {
1593 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1594 was_restored = true;
1595 }
[email protected]e9ba4472008-09-14 15:42:431596
Charlie Reisf8cde712022-10-20 16:25:091597 // If the SiteInstance has changed from the matching pending entry, this
1598 // must be treated as a new navigation with replacement. Set the replacement
1599 // bit here and ClassifyNavigation will identify this case and return
1600 // NEW_ENTRY.
1601 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1602 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1603 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251604 // TODO(nasko,creis,rakina): Move this to happen before committing the
1605 // navigation. This is a bit complicated because we don't currently
1606 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091607 details->did_replace_entry = true;
1608 }
Nasko Oskovaee2f862018-06-15 00:05:521609 }
[email protected]bcd904482012-02-01 01:54:221610
[email protected]e9ba4472008-09-14 15:42:431611 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101612 NavigationType navigation_type =
1613 ClassifyNavigation(rfh, params, navigation_request);
1614 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451615
Rakina Zata Amnie2d31312022-11-18 03:38:451616 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451617 // Ensure that this navigation does not add a navigation entry, since
1618 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1619 // beyond the last committed one. Therefore, `should_replace_current_entry`
1620 // should be set, which replaces the current entry, or this should be a
1621 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251622 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331623 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451624 }
1625
Rakina Zata Amnie2d31312022-11-18 03:38:451626 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551627 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241628 // This is a subframe navigation on the initial empty document, which used
1629 // to not have a NavigationEntry to attach to. Now it can attach to the
1630 // initial NavigationEntry, and we must ensure that its NavigationEntry
1631 // will keep the "initial NavigationEntry" status and won't append a new
1632 // NavigationEntry (it should always do replacement instead).
1633 // See also https://crbug.com/1277414.
1634 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551635 // Subframe navigation on initial NavigationEntry must not append a new
1636 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1637 // means every subframe navigation that happens while we're on the initial
1638 // NavigationEntry will always reuse the existing NavigationEntry and
1639 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101640 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1641 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551642 // This is a navigation that modifies the initial NavigationEntry, either
1643 // for a replacement or a reload. The initial NavigationEntry should
1644 // retain its "initial NavigationEntry" status in this case.
1645 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241646 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251647 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1648 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241649 // This is a synchronous about:blank navigation on the main frame, which
1650 // used to not create a NavigationEntry when we have no NavigationEntry on
1651 // FrameTree creation. We now have the initial NavigationEntry and are on
1652 // the initial NavigationEntry. To preserve old behavior, we should still
1653 // keep the "initial" status for the new NavigationEntry that we will
1654 // create for this navigation, so that subframe navigations under the
1655 // synchronously committed about:blank document will never append new
1656 // NavigationEntry, and instead will just reuse the initial
1657 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1658 // See also https://crbug.com/1277414.
1659 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551660 }
1661 }
1662 DCHECK(!details->should_stay_as_initial_entry ||
1663 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201664
eugenebutee08663a2017-04-27 17:43:121665 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441666 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121667
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071668 details->is_prerender_activation =
1669 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241670 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1671 ->GetOutermostMainFrame()
1672 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071673
Peter Boströmd7592132019-01-30 04:50:311674 // Make sure we do not discard the pending entry for a different ongoing
1675 // navigation when a same document commit comes in unexpectedly from the
1676 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1677 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581678 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061679 bool keep_pending_entry =
1680 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101681 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061682 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311683
Miyoung Shin3299cbf2022-11-22 01:41:101684 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061685 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491686 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051687 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561688 previous_document_had_history_intervention_activation,
1689 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431690 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061691 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491692 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1693 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001694 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431695 break;
[email protected]8ff00d72012-10-23 19:12:211696 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471697 RendererDidNavigateNewSubframe(
1698 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561699 previous_document_had_history_intervention_activation,
1700 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431701 break;
[email protected]8ff00d72012-10-23 19:12:211702 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391703 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251704 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001705 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081706 // We don't send a notification about auto-subframe PageState during
1707 // UpdateStateForFrame, since it looks like nothing has changed. Send
1708 // it here at commit time instead.
1709 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431710 return false;
creis59d5a47cb2016-08-24 23:57:191711 }
[email protected]e9ba4472008-09-14 15:42:431712 break;
Aran Gilman37d11632019-10-08 23:07:151713 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211714 NOTREACHED();
[email protected]765b35502008-08-21 00:51:201715 }
1716
[email protected]688aa65c62012-09-28 04:32:221717 // At this point, we know that the navigation has just completed, so
1718 // record the time.
1719 //
1720 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261721 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331722 base::Time timestamp =
1723 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1724 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131725 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221726
Peter Boströmd7592132019-01-30 04:50:311727 // If we aren't keeping the pending entry, there shouldn't be one at this
1728 // point. Clear it again in case any error cases above forgot to do so.
1729 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1730 // been cleared instead of protecting against it.
1731 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551732 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141733
[email protected]e9ba4472008-09-14 15:42:431734 // All committed entries should have nonempty content state so WebKit doesn't
1735 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471736 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321737 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221738 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441739 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141740
Alexander Timind2f2e4f22019-04-02 20:04:531741 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1742 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281743 if (back_forward_cache_metrics &&
1744 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531745 active_entry->set_back_forward_cache_metrics(
1746 std::move(back_forward_cache_metrics));
1747 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281748
1749 // `back_forward_cache_metrics()` may return null as we do not record
1750 // back-forward cache metrics for navigations in non-primary frame trees.
1751 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581752 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141753 // These are both only available from details at this point, so we capture
1754 // them here.
1755 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101756 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141757 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1758 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281759 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1760 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321761 IsBackForwardCacheEnabled() &&
1762 rfh->delegate()->IsBackForwardCacheSupported() &&
1763 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281764 }
naskoc7533512016-05-06 17:01:121765
Charles Reisc0507202017-09-21 00:40:021766 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1767 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1768 // A mismatch can occur if the renderer lies or due to a unique name collision
1769 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121770 FrameNavigationEntry* frame_entry =
1771 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021772 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1773 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031774 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081775 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1776 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031777 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201778
1779 // Remember the bindings the renderer process has at this point, so that
1780 // we do not grant this entry additional bindings if we come back to it.
1781 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301782 }
[email protected]132e281a2012-07-31 18:32:441783
[email protected]97d8f0d2013-10-29 16:49:211784 // Once it is committed, we no longer need to track several pieces of state on
1785 // the entry.
naskoc7533512016-05-06 17:01:121786 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131787
[email protected]49bd30e62011-03-22 20:12:591788 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221789 // TODO(creis): This check won't pass for subframes until we create entries
1790 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001791 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421792 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591793
[email protected]e9ba4472008-09-14 15:42:431794 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001795 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001796 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311797 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531798
arthursonzogni7ddc6542021-04-09 09:16:501799 active_entry->SetIsOverridingUserAgent(
1800 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031801
[email protected]93f230e02011-06-01 14:40:001802 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291803
aelias100c9192017-01-13 00:01:431804 if (overriding_user_agent_changed)
1805 delegate_->UpdateOverridingUserAgent();
1806
creis03b48002015-11-04 00:54:561807 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1808 // one knows the latest NavigationEntry it is showing (whether it has
1809 // committed anything in this navigation or not). This allows things like
1810 // state and title updates from RenderFrames to apply to the latest relevant
1811 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381812 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031813 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381814 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431815
1816 if (navigation_request->IsPrerenderedPageActivation()) {
Charlie Reis99b2eba22025-01-31 19:18:571817 BroadcastHistoryIndexAndLength();
Alison Gale47d1537d2024-04-19 21:31:461818 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431819 // is activated. As a result, a "prerenderingchange" event listener sees the
1820 // history.length which is not updated yet. We should guarantee that
Charlie Reis99b2eba22025-01-31 19:18:571821 // history's length and index should be updated before a
Hayato Ito2c8c08d02021-06-23 03:38:431822 // "prerenderingchange" event listener runs. One possible approach is to use
1823 // the same IPC which "prerenderingchange" uses, and propagate history's
Charlie Reis99b2eba22025-01-31 19:18:571824 // length and index together with that.
Hayato Ito2c8c08d02021-06-23 03:38:431825 }
1826
[email protected]e9ba4472008-09-14 15:42:431827 return true;
initial.commit09911bf2008-07-26 23:55:291828}
1829
[email protected]8ff00d72012-10-23 19:12:211830NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321831 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101832 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241833 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591834 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511835 "ClassifyNavigation");
1836
avi7c6f35e2015-05-08 17:52:381837 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241838 // A new entry. We may or may not have a corresponding pending entry, and
1839 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001840 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491841 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061842 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381843 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241844 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511845 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381846 return NAVIGATION_TYPE_NEW_SUBFRAME;
1847 }
1848
Charlie Reisc0f17d2d2021-01-12 18:52:491849 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381850 DCHECK(!params.history_list_was_cleared);
1851
avi39c1edd32015-06-04 20:06:001852 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381853 // All manual subframes would be did_create_new_entry and handled above, so
1854 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081855 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1856 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381857 }
1858
Rakina Zata Amnif6950d552020-11-24 03:26:101859 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1860 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381861 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1862 // create a new page.
1863
Hayato Ito2ae49442021-07-02 02:59:251864 // This main frame navigation is not a history navigation (since
1865 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1866 // reload or a replacement navigation, which will modify the existing entry.
1867 //
Nasko Oskov332593c2018-08-16 17:21:341868 // TODO(nasko): With error page isolation, reloading an existing session
1869 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491870 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341871 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511872 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491873 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061874 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381875 }
1876
Charlie Reisf8cde712022-10-20 16:25:091877 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521878 // If the SiteInstance of the |pending_entry_| does not match the
1879 // SiteInstance that got committed, treat this as a new navigation with
1880 // replacement. This can happen if back/forward/reload encounters a server
1881 // redirect to a different site or an isolated error page gets successfully
1882 // reloaded into a different SiteInstance.
1883 if (pending_entry_->site_instance() &&
1884 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491885 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061886 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521887 }
creis77c9aa32015-09-25 19:59:421888
Nasko Oskovaee2f862018-06-15 00:05:521889 if (pending_entry_index_ == -1) {
1890 // In this case, we have a pending entry for a load of a new URL but Blink
1891 // didn't do a new navigation (params.did_create_new_entry). First check
1892 // to make sure Blink didn't treat a new cross-process navigation as
1893 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161894 // we must treat it as NEW rather than the converted reload case below,
1895 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451896 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161897 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061898 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521899 }
1900
1901 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161902 // We will create a pending entry, but NavigateWithoutEntry will convert
1903 // it to a reload since it's the same page and not create a new entry for
1904 // it. (The user doesn't want to have a new back/forward entry when they
1905 // do this.) Therefore we want to just ignore the pending entry and go
1906 // back to where we were (the "existing entry").
1907 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061908 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521909 }
avi7c6f35e2015-05-08 17:52:381910 }
1911
Rakina Zata Amni153d5702021-09-13 22:48:001912 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381913 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491914 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1915 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161916 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061917 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381918 }
1919
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121920 if (navigation_request->DidEncounterError() &&
1921 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101922 nav_entry_id == failed_pending_entry_id_) {
Charlie Reisb5f39cf2024-11-12 16:55:011923 // If the renderer was going to a pending entry that got cleared because of
1924 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511925 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491926 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061927 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381928 }
1929
Charlie Reisc0f17d2d2021-01-12 18:52:491930 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101931 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511932 trace_return.traced_value()->SetInteger("existing_entry_index",
1933 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381934 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441935 // The renderer has committed a navigation to an entry that no longer
1936 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491937 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061938 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381939 }
1940
avi7c6f35e2015-05-08 17:52:381941 // Since we weeded out "new" navigations above, we know this is an existing
1942 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491943 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061944 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381945}
1946
Rakina Zata Amni3460d382021-10-29 00:43:371947void NavigationControllerImpl::UpdateNavigationEntryDetails(
1948 NavigationEntryImpl* entry,
1949 RenderFrameHostImpl* rfh,
1950 const mojom::DidCommitProvisionalLoadParams& params,
1951 NavigationRequest* request,
1952 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001953 bool is_new_entry,
1954 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371955 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171956 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371957 entry->AddOrUpdateFrameEntry(
1958 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571959 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371960 rfh->GetSiteInstance(), nullptr, params.url,
1961 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171962 Referrer(*params.referrer),
1963 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371964 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171965 request ? request->GetRedirectChain() : redirects, params.page_state,
1966 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371967 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171968 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211969 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171970 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371971
1972 if (rfh->GetParent()) {
1973 // Only modify the NavigationEntry for main frame navigations.
1974 return;
1975 }
1976 if (entry->update_virtual_url_with_url())
1977 UpdateVirtualURLToURL(entry, params.url);
1978 // Don't use the page type from the pending entry. Some interstitial page
1979 // may have set the type to interstitial. Once we commit, however, the page
1980 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171981 entry->set_page_type((request && request->DidEncounterError())
1982 ? PAGE_TYPE_ERROR
1983 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431984 if (commit_details && commit_details->should_stay_as_initial_entry) {
1985 // Retain the "initial NavigationEntry" status.
1986 if (request->IsSameDocument()) {
1987 // If this is for a same-document navigation, the NavigationEntry must be
1988 // reused and should already be marked as the initial NavigationEntry.
1989 DCHECK(entry->IsInitialEntry());
1990 } else {
1991 // If this is for a cross-document navigation, it can be caused by a
1992 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1993 // "for synchronous about:blank" in the latter case, and also when it is
1994 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1995 // is not for a synchronous about:blank commit.
1996 NavigationEntryImpl::InitialNavigationEntryState new_state =
1997 NavigationEntryImpl::InitialNavigationEntryState::
1998 kInitialNotForSynchronousAboutBlank;
1999 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
2000 request->is_synchronous_renderer_commit()) {
2001 new_state = NavigationEntryImpl::InitialNavigationEntryState::
2002 kInitialForSynchronousAboutBlank;
2003 }
2004 entry->set_initial_navigation_entry_state(new_state);
2005 }
2006 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
2007 // Remove the "initial NavigationEntry" status.
2008 entry->set_initial_navigation_entry_state(
2009 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:002010 }
Rakina Zata Amniddf10502022-01-15 02:56:552011
Rakina Zata Amni3460d382021-10-29 00:43:372012 if (is_new_entry) {
2013 // Some properties of the NavigationEntry are only set when the entry is
2014 // new (we aren't reusing it).
2015 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:172016 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:402017 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:012018 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
2019 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:372020 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
2021 } else {
2022 // We are reusing the NavigationEntry. The site instance will normally be
2023 // the same except for a few cases:
2024 // 1) session restore, when no site instance will be assigned or
2025 // 2) redirect, when the site instance is reset.
2026 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
2027 entry->site_instance() == rfh->GetSiteInstance());
2028 }
2029}
2030
Rakina Zata Amniafd3c6582021-11-30 06:19:172031void NavigationControllerImpl::CreateInitialEntry() {
2032 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:032033 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:172034 auto params = mojom::DidCommitProvisionalLoadParams::New();
2035 // The initial NavigationEntry's URL is the empty URL. This preserves the old
2036 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
2037 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:402038 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:172039 params->http_status_code = 0;
2040 params->url_is_unreachable = false;
2041 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:172042 params->post_id = -1;
2043 params->embedding_token = base::UnguessableToken::Create();
2044 params->navigation_token = base::UnguessableToken::Create();
2045 params->did_create_new_entry = true;
2046 params->origin = rfh->GetLastCommittedOrigin();
2047 params->should_update_history = true;
2048 params->item_sequence_number = 0;
2049 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:152050 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:172051 params->transition = is_in_fenced_frame_tree
2052 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
2053 : ui::PAGE_TRANSITION_LINK;
2054 params->referrer = blink::mojom::Referrer::New();
2055
Rakina Zata Amniafd3c6582021-11-30 06:19:172056 auto new_entry = std::make_unique<NavigationEntryImpl>(
2057 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:382058 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:212059 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
2060 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
2061 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172062 UpdateNavigationEntryDetails(
2063 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:002064 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
2065 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172066
2067 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
2068 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:002069 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172070}
2071
Charlie Reisc0f17d2d2021-01-12 18:52:492072void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:322073 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072074 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362075 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442076 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562077 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002078 NavigationRequest* request,
2079 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572080 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372081 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452082 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372083 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522084 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2085 initiator_base_url = request->common_params().initiator_base_url;
2086 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062087
creisf49dfc92016-07-26 17:05:182088 // First check if this is an in-page navigation. If so, clone the current
2089 // entry instead of looking at the pending entry, because the pending entry
2090 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452091 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302092 FrameNavigationEntry* previous_frame_entry =
2093 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452094 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482095 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572096 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082097 rfh->GetSiteInstance(), nullptr, params.url,
2098 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212099 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092100 request->GetRedirectChain(), params.page_state, params.method,
2101 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392102 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302103 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572104 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302105 // FrameNavigationEntry.
2106 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572107 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032108
creisf49dfc92016-07-26 17:05:182109 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032110 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522111 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2112 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572113 // TODO(jam): we had one report of this with a URL that was redirecting to
2114 // only tildes. Until we understand that better, don't copy the cert in
2115 // this case.
2116 new_entry->GetSSL() = SSLStatus();
2117 }
creisf49dfc92016-07-26 17:05:182118
Patrick Monette50e8bd82019-06-13 22:40:452119 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2120 // that |frame_entry| should now have a reference count of exactly 2: one
2121 // due to the local variable |frame_entry|, and another due to |new_entry|
2122 // also retaining one. This should never fail, because it's the main frame.
2123 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182124 }
2125
Harkiran Bolaria59290d62021-03-17 01:53:012126 // If this is an activation navigation from a prerendered page, transfer the
2127 // new entry from an entry already created and stored in the
2128 // NavigationRequest. |new_entry| will not have been set prior to this as
2129 // |is_same_document| is mutually exclusive with
2130 // |IsPrerenderedPageActivation|.
2131 if (request->IsPrerenderedPageActivation()) {
2132 DCHECK(!is_same_document);
2133 DCHECK(!new_entry);
2134 new_entry = request->TakePrerenderNavigationEntry();
2135 DCHECK(new_entry);
2136 }
2137
Charlie Reisc0f17d2d2021-01-12 18:52:492138 // Only make a copy of the pending entry if it is appropriate for the new
2139 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452140 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042141 // 1. The SiteInstance hasn't been assigned to something else.
2142 // 2. The pending entry was intended as a new entry, rather than being a
2143 // history navigation that was interrupted by an unrelated,
2144 // renderer-initiated navigation.
2145 // TODO(csharrison): Investigate whether we can remove some of the coarser
2146 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452147 if (!new_entry && PendingEntryMatchesRequest(request) &&
2148 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342149 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432150 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352151 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432152
Camille Lamy62b826012019-02-26 09:15:472153 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452154 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182155 }
2156
Charlie Reisc0f17d2d2021-01-12 18:52:492157 // For cross-document commits with no matching pending entry, create a new
2158 // entry.
creisf49dfc92016-07-26 17:05:182159 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062160 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072161 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212162 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582163 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452164 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172165 nullptr, // blob_url_loader_factory
2166 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242167
2168 // Find out whether the new entry needs to update its virtual URL on URL
2169 // change and set up the entry accordingly. This is needed to correctly
2170 // update the virtual URL when replaceState is called after a pushState.
2171 GURL url = params.url;
2172 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492173 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412174 // update the virtual URL based on the new URL. For example, this is needed
2175 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2176 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372177 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2178 &url, browser_context_, &needs_update);
2179 new_entry->set_update_virtual_url_with_url(needs_update);
2180
Camille Lamy62b826012019-02-26 09:15:472181 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452182 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432183 }
2184
Alison Gale770f3fc2024-04-27 00:39:582185 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2186 // set for prerendered contents, if any. This is because
2187 // prerendering/activation technically won't be creating a new document.
2188 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2189 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012190 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372191 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2192 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002193 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082194
Harkiran Bolaria59290d62021-03-17 01:53:012195 // history.pushState() is classified as a navigation to a new page, but sets
2196 // is_same_document to true. In this case, we already have the title and
2197 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452198 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012199 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2200 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2201 }
[email protected]3a868f212014-08-09 10:41:192202 }
[email protected]ff64b3e2014-05-31 04:07:332203
[email protected]60d6cca2013-04-30 08:47:132204 DCHECK(!params.history_list_was_cleared || !replace_entry);
2205 // The browser requested to clear the session history when it initiated the
2206 // navigation. Now we know that the renderer has updated its state accordingly
2207 // and it is safe to also clear the browser side history.
2208 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552209 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132210 entries_.clear();
2211 last_committed_entry_index_ = -1;
2212 }
2213
Nasko Oskovaee2f862018-06-15 00:05:522214 // If this is a new navigation with replacement and there is a
2215 // pending_entry_ which matches the navigation reported by the renderer
2216 // process, then it should be the one replaced, so update the
2217 // last_committed_entry_index_ to use it.
2218 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092219 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522220 last_committed_entry_index_ = pending_entry_index_;
2221 }
2222
Alexander Timine3ec4192020-04-20 16:39:402223 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562224 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402225 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052226
Yuzu Saijoa725585f2022-11-28 04:14:032227 // If this is a history navigation and the old entry has an existing
2228 // back/forward cache metrics object, keep using the old one so that the
2229 // reasons logged from the last time the page navigated gets preserved.
2230 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2231 request)) {
2232 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2233 // because some tests do not have a pending entry.
2234 NavigationEntryImpl* entry =
2235 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2236 if (entry && entry->back_forward_cache_metrics()) {
2237 scoped_refptr<BackForwardCacheMetrics> metrics =
2238 entry->TakeBackForwardCacheMetrics();
2239 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2240 }
2241 }
2242
Andrew Verge754c70a2025-04-17 17:19:192243 bool was_post_commit_error =
2244 request->browser_initiated_error_navigation_type() ==
2245 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit;
2246
Carlos IL42b416592019-10-07 23:10:362247 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Andrew Verge754c70a2025-04-17 17:19:192248 was_post_commit_error, rfh->IsNestedWithinFencedFrame(),
2249 commit_details);
[email protected]e9ba4472008-09-14 15:42:432250}
2251
Charlie Reisc0f17d2d2021-01-12 18:52:492252void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322253 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072254 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362255 bool is_same_document,
jam48cea9082017-02-15 06:13:292256 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452257 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002258 bool keep_pending_entry,
2259 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562260 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2261 << "that a last committed entry exists.";
2262
[email protected]e9ba4472008-09-14 15:42:432263 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002264 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432265
Charlie Reis7e2cb6d2021-01-26 01:27:162266 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002267 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162268 // We're guaranteed to have a last committed entry if intended_as_new_entry
2269 // is true.
avicbdc4c12015-07-01 16:07:112270 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162271
2272 // If the NavigationRequest matches a new pending entry and is classified as
2273 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2274 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092275 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162276 // Note: The pending entry will usually have a real ReloadType here, but
2277 // it can still be ReloadType::NONE in cases that
2278 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2279
2280 // If we classified this correctly, the SiteInstance should not have
2281 // changed.
2282 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2283
2284 // For converted reloads, we assign the entry's unique ID to be that of
2285 // the new one. Since this is always the result of a user action, we want
2286 // to dismiss infobars, etc. like a regular user-initiated navigation.
2287 entry->set_unique_id(pending_entry_->GetUniqueID());
2288
2289 // The extra headers may have changed due to reloading with different
2290 // headers.
2291 entry->set_extra_headers(pending_entry_->extra_headers());
2292 }
2293 // Otherwise, this was intended as a new entry but the pending entry was
2294 // lost in the meantime and no new entry was created. We are stuck at the
2295 // last committed entry.
2296
2297 // Even if this is a converted reload from pressing enter in the omnibox,
2298 // the server could redirect, requiring an update to the SSL status. If this
2299 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452300 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162301 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472302 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452303 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162304 }
Rakina Zata Amnif6950d552020-11-24 03:26:102305 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112306 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102307 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162308
eugenebut604866f2017-05-10 21:35:362309 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452310 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362311 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2312 // this was a restored same document navigation entry, then it won't have
2313 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2314 // navigated it.
jam48cea9082017-02-15 06:13:292315 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522316 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2317 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292318 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2319 was_restored) {
2320 entry->GetSSL() = last_entry->GetSSL();
2321 }
2322 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452323 // In rapid back/forward navigations |request| sometimes won't have a cert
2324 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192325 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452326 if (request->GetSSLInfo().has_value() &&
2327 request->GetSSLInfo()->is_valid()) {
2328 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522329 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2330 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192331 entry->GetSSL() = SSLStatus();
2332 }
jam48cea9082017-02-15 06:13:292333 }
avicbdc4c12015-07-01 16:07:112334 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272335 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572336 // navigations that are EXISTING_ENTRY are same-document navigations that
2337 // result in replacement (e.g. history.replaceState(), location.replace(),
2338 // forced replacements for trivial session history contexts). For these
2339 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112340 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102341
Alison Gale81f4f2c72024-04-22 19:33:312342 // TODO(crbug.com/40532777): Set page transition type to
2343 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2344 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2345 // well as to fix the inconsistency with what we report to observers
2346 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102347
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572348 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102349
eugenebut604866f2017-05-10 21:35:362350 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452351 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362352 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472353 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452354 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112355 }
2356 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432357
Rakina Zata Amni3460d382021-10-29 00:43:372358 UpdateNavigationEntryDetails(entry, rfh, params, request,
2359 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002360 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302361
[email protected]5ccd4dc2012-10-24 02:28:142362 // The redirected to page should not inherit the favicon from the previous
2363 // page.
eugenebut604866f2017-05-10 21:35:362364 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482365 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142366
Charlie Reis951f43372023-05-05 00:30:072367 // Update the last committed index to reflect the committed entry. Do this
2368 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2369 // delegate sees the correct committed index when notified of navigation
2370 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2371 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212372 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072373
Peter Boströmd7592132019-01-30 04:50:312374 // We should also usually discard the pending entry if it corresponds to a
2375 // different navigation, since that one is now likely canceled. In rare
2376 // cases, we leave the pending entry for another navigation in place when we
2377 // know it is still ongoing, to avoid a flicker in the omnibox (see
2378 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432379 //
2380 // Note that we need to use the "internal" version since we don't want to
2381 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312382 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002383 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432384}
2385
[email protected]d202a7c2012-01-04 07:53:472386void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322387 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072388 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362389 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472390 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562391 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002392 NavigationRequest* request,
2393 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262394 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2395 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552396 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2397 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112398
[email protected]e9ba4472008-09-14 15:42:432399 // Manual subframe navigations just get the current entry cloned so the user
2400 // can go back or forward to it. The actual subframe information will be
2401 // stored in the page state for each of those entries. This happens out of
2402 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092403 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2404 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382405
Mikel Astizba9cf2fd2017-12-17 10:38:102406 // The DCHECK below documents the fact that we don't know of any situation
2407 // where |replace_entry| is true for subframe navigations. This simplifies
2408 // reasoning about the replacement struct for subframes (see
2409 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2410 DCHECK(!replace_entry);
2411
Patrick Monette50e8bd82019-06-13 22:40:452412 // This FrameNavigationEntry might not end up being used in the
2413 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372414 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452415 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372416 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522417 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2418 initiator_base_url = request->common_params().initiator_base_url;
2419 }
Nate Chapin63db0d12022-01-20 22:03:302420 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2421 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212422 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302423 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572424 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302425 if (is_same_document) {
2426 FrameNavigationEntry* previous_frame_entry =
2427 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572428 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302429 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572430 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302431 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572432 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302433 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572434 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302435 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572436 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302437 policy_container_policies->referrer_policy);
2438 }
2439
Patrick Monette50e8bd82019-06-13 22:40:452440 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482441 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572442 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082443 rfh->GetSiteInstance(), nullptr, params.url,
2444 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212445 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2446 request->GetRedirectChain(), params.page_state, params.method,
2447 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572448 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032449
creisce0ef3572017-01-26 17:53:082450 std::unique_ptr<NavigationEntryImpl> new_entry =
2451 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452452 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032453 frame_tree_->root());
creise062d542015-08-25 02:01:552454
Alexander Timine3ec4192020-04-20 16:39:402455 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562456 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402457 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472458
creisce0ef3572017-01-26 17:53:082459 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452460 // to replace, which can happen due to a unique name change. See
2461 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2462 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382463
Dave Tapuska87696ae2021-11-18 18:48:312464 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152465 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432466}
2467
[email protected]d202a7c2012-01-04 07:53:472468bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322469 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072470 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392471 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252472 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002473 NavigationRequest* request,
2474 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292475 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2476 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2477
[email protected]e9ba4472008-09-14 15:42:432478 // We're guaranteed to have a previously committed entry, and we now need to
2479 // handle navigation inside of a subframe in it without creating a new entry.
2480 DCHECK(GetLastCommittedEntry());
2481
creis913c63ce2016-07-16 19:52:522482 // For newly created subframes, we don't need to send a commit notification.
2483 // This is only necessary for history navigations in subframes.
2484 bool send_commit_notification = false;
2485
Rakina Zata Amnif6950d552020-11-24 03:26:102486 // If |nav_entry_id| is non-zero and matches an existing entry, this
2487 // is a history navigation. Update the last committed index accordingly. If
2488 // we don't recognize the |nav_entry_id|, it might be a recently
2489 // pruned entry. We'll handle it below.
2490 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2491 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472492 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062493 // Make sure that a subframe commit isn't changing the main frame's
2494 // origin. Otherwise the renderer process may be confused, leading to a
2495 // URL spoof. We can't check the path since that may change
2496 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572497 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2498 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242499 // We should use checks similar to RenderFrameHostImpl's
2500 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2501 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572502 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2503 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2504 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2505 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522506 current_top_url.DeprecatedGetOriginAsURL() !=
2507 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442508 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512509 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062510 }
creis3cdc3b02015-05-29 23:00:472511
creis913c63ce2016-07-16 19:52:522512 // We only need to discard the pending entry in this history navigation
2513 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062514 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002515 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522516
2517 // History navigations should send a commit notification.
2518 send_commit_notification = true;
avi98405c22015-05-21 20:47:062519 }
[email protected]e9ba4472008-09-14 15:42:432520 }
[email protected]f233e4232013-02-23 00:55:142521
creisce0ef3572017-01-26 17:53:082522 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2523 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372524 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2525 // exists), or we may want to clobber it and create a new one. We update in
2526 // cases where the corresponding FrameNavigationEntry is conceptually similar
2527 // to the document described by the commit params: same-document
2528 // navigations, history traversal to an existing entry, and reloads (including
2529 // a "soft reload" where we navigate to the same url without flagging it as a
2530 // reload). But in the case of a different document that is not logically
2531 // related to the committed FrameNavigationEntry's document (cross-document,
2532 // not same url, not a reload, not a history traversal), we replace rather
2533 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252534 //
Nate Chapin9f169072021-06-09 19:32:372535 // In the case where we update, the FrameNavigationEntry will potentially be
2536 // shared across multiple NavigationEntries, and any updates will be reflected
2537 // in all of those NavigationEntries. In the replace case, any existing
2538 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252539 //
2540 // When navigating away from the initial empty document, we also update rather
2541 // than replace. Either update or replace will overwrite the initial empty
2542 // document state for |last_committed|, but if the FrameNavigationEntry for
2543 // the initial empty document is shared across multiple NavigationEntries (due
2544 // to a navigation in another frame), we want to make sure we overwrite the
2545 // initial empty document state everywhere this FrameNavigationEntry is used,
2546 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452547 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372548 FrameNavigationEntry* last_committed_frame_entry =
2549 last_committed->GetFrameEntry(rfh->frame_tree_node());
2550 NavigationEntryImpl::UpdatePolicy update_policy =
2551 NavigationEntryImpl::UpdatePolicy::kUpdate;
2552 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312553 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372554 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252555 last_committed_frame_entry->url() != params.url &&
2556 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372557 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2558 }
2559
Rakina Zata Amni3460d382021-10-29 00:43:372560 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002561 update_policy, false /* is_new_entry */,
2562 commit_details);
creis625a0c7d2015-03-24 23:17:122563
creis913c63ce2016-07-16 19:52:522564 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432565}
2566
[email protected]d202a7c2012-01-04 07:53:472567int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232568 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032569 for (size_t i = 0; i < entries_.size(); ++i) {
2570 if (entries_[i].get() == entry)
2571 return i;
2572 }
2573 return -1;
[email protected]765b35502008-08-21 00:51:202574}
2575
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572576void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242577 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572578 NavigationControllerImpl* source =
2579 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572580 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382581 DCHECK_EQ(1, GetEntryCount());
2582 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472583 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172584 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572585
Francois Dorayeaace782017-06-21 16:37:242586 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442587 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572588 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572589
Fergal Dalya1d569972021-03-16 03:24:532590 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302591 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532592 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2593 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302594 }
[email protected]4e6419c2010-01-15 04:50:342595
Lukasz Anforowicz0de0f452020-12-02 19:57:152596 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572597}
2598
[email protected]79368982013-11-13 01:11:012599bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022600 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162601 if (last_committed_entry_index_ == -1)
2602 return false;
[email protected]9350602e2013-02-26 23:27:442603
[email protected]474f8512013-05-31 22:31:162604 // We cannot prune if there is a pending entry at an existing entry index.
2605 // It may not commit, so we have to keep the last committed entry, and thus
2606 // there is no sensible place to keep the pending entry. It is ok to have
2607 // a new pending entry, which can optionally commit as a new navigation.
2608 if (pending_entry_index_ != -1)
2609 return false;
2610
[email protected]474f8512013-05-31 22:31:162611 return true;
2612}
2613
[email protected]79368982013-11-13 01:11:012614void NavigationControllerImpl::PruneAllButLastCommitted() {
2615 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162616
avi2b177592014-12-10 02:08:022617 DCHECK_EQ(0, last_committed_entry_index_);
2618 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442619
Charlie Reis99b2eba22025-01-31 19:18:572620 BroadcastHistoryIndexAndLength();
[email protected]9350602e2013-02-26 23:27:442621}
2622
[email protected]79368982013-11-13 01:11:012623void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162624 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012625 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262626
Nate Chapin9eb16be72022-09-23 22:54:312627 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2628
[email protected]474f8512013-05-31 22:31:162629 // Erase all entries but the last committed entry. There may still be a
2630 // new pending entry after this.
2631 entries_.erase(entries_.begin(),
2632 entries_.begin() + last_committed_entry_index_);
2633 entries_.erase(entries_.begin() + 1, entries_.end());
2634 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262635}
2636
Christian Dullweber1af31e62018-02-22 11:49:482637void NavigationControllerImpl::DeleteNavigationEntries(
2638 const DeletionPredicate& deletionPredicate) {
2639 // It is up to callers to check the invariants before calling this.
2640 CHECK(CanPruneAllButLastCommitted());
2641 std::vector<int> delete_indices;
2642 for (size_t i = 0; i < entries_.size(); i++) {
2643 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572644 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482645 delete_indices.push_back(i);
2646 }
2647 }
2648 if (delete_indices.empty())
2649 return;
2650
2651 if (delete_indices.size() == GetEntryCount() - 1U) {
2652 PruneAllButLastCommitted();
2653 } else {
2654 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382655 for (const auto& index : base::Reversed(delete_indices)) {
2656 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482657 }
Charlie Reis99b2eba22025-01-31 19:18:572658 BroadcastHistoryIndexAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482659 }
2660 delegate()->NotifyNavigationEntriesDeleted();
2661}
2662
Carlos Caballero35ce710c2019-09-19 10:59:452663BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2664 return back_forward_cache_;
2665}
2666
William Liu055a3542023-04-02 17:21:192667NavigationEntryScreenshotCache*
2668NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212669 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262670 if (!nav_entry_screenshot_cache_ &&
2671 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192672 nav_entry_screenshot_cache_ =
2673 std::make_unique<NavigationEntryScreenshotCache>(
2674 BrowserContextImpl::From(browser_context_)
2675 ->GetNavigationEntryScreenshotManager()
2676 ->GetSafeRef(),
2677 this);
2678 }
2679 return nav_entry_screenshot_cache_.get();
2680}
2681
clamy987a3752018-05-03 17:36:262682void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2683 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2684 // progress, since this will cause a use-after-free. (We only allow this
2685 // when the tab is being destroyed for shutdown, since it won't return to
2686 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032687 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
Minoru Chikamune13ab4de2025-05-14 21:54:072688 // If `was_failure` is true, it means that the pending entry was discarded by
2689 // a `PendingEntryRefDeleted` call within `OnRequestFailedInternal`, in
2690 // response to a navigation request failure. This case is not at risk for
2691 // re-entrancy when `can_be_in_navigate_to_pending_entry_` is true, because
2692 // that code also creates another `PendingEntryRef` that would prevent the
2693 // `DiscardPendingEntry` call if the PostTask were skipped. See
2694 // https://crbug.com/411855273.
2695 if (!was_failure && can_be_in_navigate_to_pending_entry_ &&
Minoru Chikamune646eba42025-04-14 01:25:032696 !frame_tree_->IsBeingDestroyed()) {
2697 CheckPotentialNavigationReentrancy();
2698 }
clamy987a3752018-05-03 17:36:262699
2700 if (was_failure && pending_entry_) {
2701 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2702 } else {
2703 failed_pending_entry_id_ = 0;
2704 }
2705
2706 if (pending_entry_) {
2707 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332708 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262709 pending_entry_index_ = -1;
2710 pending_entry_ = nullptr;
2711 }
arthursonzogni66f711c2019-10-08 14:40:362712
2713 // Ensure any refs to the current pending entry are ignored if they get
2714 // deleted, by clearing the set of known refs. All future pending entries will
2715 // only be affected by new refs.
2716 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262717}
2718
2719void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2720 if (pending_entry_)
2721 pending_entry_->set_ssl_error(error);
2722}
2723
Xiaohan Wang7f8052e02022-01-14 18:44:282724#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422725// static
2726bool NavigationControllerImpl::ValidateDataURLAsString(
2727 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2728 if (!data_url_as_string)
2729 return false;
2730
2731 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2732 return false;
2733
2734 // The number of characters that is enough for validating a data: URI.
2735 // From the GURL's POV, the only important part here is scheme, it doesn't
2736 // check the actual content. Thus we can take only the prefix of the url, to
2737 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562738 constexpr size_t kDataUriPrefixMaxLen = 64;
2739 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2740 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422741 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2742 return false;
2743
2744 return true;
2745}
2746#endif
2747
Shivani Sharma194877032019-03-07 17:52:472748void NavigationControllerImpl::NotifyUserActivation() {
2749 // When a user activation occurs, ensure that all adjacent entries for the
2750 // same document clear their skippable bit, so that the history manipulation
2751 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012752 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172753 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012754 // If the value of CanGoBack changes as a result of making some entries
2755 // non-skippable, then we must let the delegate know to update its UI state.
2756 // See https://crbug.com/1477784.
2757 if (!can_go_back && CanGoBack()) {
2758 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2759 }
Shivani Sharma194877032019-03-07 17:52:472760}
2761
clamy987a3752018-05-03 17:36:262762bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2763 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332764 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2765 blink::LocalFrameToken initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492766 int initiator_process_id,
2767 base::TimeTicks actual_navigation_start) {
clamy987a3752018-05-03 17:36:262768 NavigationEntryImpl* entry =
2769 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2770 if (!entry)
2771 return false;
2772
2773 FrameNavigationEntry* frame_entry =
2774 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2775 if (!frame_entry)
2776 return false;
2777
Camille Lamy5193caa2018-10-12 11:59:422778 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572779 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232780 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332781 true /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492782 initiator_process_id, actual_navigation_start);
clamyea99ea12018-05-28 13:54:232783
2784 if (!request)
2785 return false;
2786
arthursonzognif046d4a2019-12-12 19:08:102787 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412788
Rakina Zata Amni1c83b082023-02-08 01:09:002789 SCOPED_CRASH_KEY_STRING256(
2790 "Bug1400009", "req_url",
2791 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2792 SCOPED_CRASH_KEY_NUMBER(
2793 "Bug1400009", "nav_entry_si",
2794 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2795 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2796 frame_entry->site_instance()
2797 ? ((int)frame_entry->site_instance()->GetId())
2798 : -1);
2799 bool has_sig =
2800 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2801 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2802 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2803 has_sig ? (!!frame_tree_->GetRenderViewHost(
2804 frame_entry->site_instance()->group()))
2805 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052806 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2807 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232808
2809 return true;
clamy987a3752018-05-03 17:36:262810}
2811
Tsuyoshi Horo52fd08e2020-07-07 07:03:452812bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
Charlie Reisf4d51f402025-05-23 18:00:492813 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Tsuyoshi Horo52fd08e2020-07-07 07:03:452814 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2815 if (!entry)
2816 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432817
2818 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2819 // We should never navigate to an existing initial NavigationEntry that is
2820 // the initial NavigationEntry for the initial empty document that hasn't
2821 // been overridden by the synchronous about:blank commit, to preserve
2822 // legacy behavior where trying to reload when the main frame is on the
2823 // initial empty document won't result in a navigation. See also
2824 // https://crbug.com/1277414.
2825 return false;
2826 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452827 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2828 if (!frame_entry)
2829 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142830 ReloadType reload_type = ReloadType::NORMAL;
2831 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452832 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142833 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452834 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432835 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372836 std::nullopt /* initiator_frame_token */,
Charlie Reisf4d51f402025-05-23 18:00:492837 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
2838 actual_navigation_start);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452839 if (!request)
2840 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052841 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452842 return true;
2843}
2844
clamy987a3752018-05-03 17:36:262845void NavigationControllerImpl::NavigateFromFrameProxy(
2846 RenderFrameHostImpl* render_frame_host,
2847 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022848 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452849 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372850 const std::optional<url::Origin>& initiator_origin,
2851 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262852 bool is_renderer_initiated,
2853 SiteInstance* source_site_instance,
2854 const Referrer& referrer,
2855 ui::PageTransition page_transition,
2856 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252857 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262858 const std::string& method,
2859 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092860 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142861 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212862 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502863 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372864 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292865 blink::mojom::NavigationInitiatorActivationAndAdStatus
2866 initiator_activation_and_ad_status,
Charlie Reise1d9b8182025-04-02 04:32:122867 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:222868 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492869 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462870 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452871 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582872 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032873 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342874 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372875 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582876 if (is_renderer_initiated)
2877 DCHECK(initiator_origin.has_value());
2878
clamy987a3752018-05-03 17:36:262879 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582880
Rakina Zata Amni2322f4f82022-01-24 13:24:242881 // Don't allow an entry replacement if there is no entry to replace.
2882 // http://crbug.com/457149
2883 if (GetEntryCount() == 0)
2884 should_replace_current_entry = false;
2885
clamy987a3752018-05-03 17:36:262886 // Create a NavigationEntry for the transfer, without making it the pending
2887 // entry. Subframe transfers should have a clone of the last committed entry
2888 // with a FrameNavigationEntry for the target frame. Main frame transfers
2889 // should have a new NavigationEntry.
2890 // TODO(creis): Make this unnecessary by creating (and validating) the params
2891 // directly, passing them to the destination RenderFrameHost. See
2892 // https://crbug.com/536906.
2893 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262894 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262895 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452896 DCHECK(GetLastCommittedEntry());
2897 entry = GetLastCommittedEntry()->Clone();
2898 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172899 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2900 // Renderer-initiated navigation that target a remote frame are currently
2901 // classified as browser-initiated when this one has already navigated.
2902 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372903 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2904 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2905 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2906 // same-document navigation), they will still be present in the
2907 // committed NavigationEntry that will be referenced to construct the new
2908 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262909 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082910 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582911 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372912 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212913 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152914 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262915 } else {
2916 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172917 // If `node` is the outermost main frame, it rewrites a virtual url in order
2918 // to adjust the original input url if needed. For inner frames such as
2919 // fenced frames or subframes, they don't rewrite urls as the urls are not
2920 // input urls by users.
2921 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372922 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322923 if (source_site_instance && source_site_instance->HasProcess()) {
2924 source_process_site_url =
2925 source_site_instance->GetProcess()->GetProcessLock().site_url();
2926 }
clamy987a3752018-05-03 17:36:262927 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212928 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322929 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212930 extra_headers, browser_context_, blob_url_loader_factory,
2931 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262932 entry->root_node()->frame_entry->set_source_site_instance(
2933 static_cast<SiteInstanceImpl*>(source_site_instance));
2934 entry->root_node()->frame_entry->set_method(method);
2935 }
clamy987a3752018-05-03 17:36:262936
Camille Lamy5193caa2018-10-12 11:59:422937 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452938 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262939 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422940 override_user_agent = true;
clamy987a3752018-05-03 17:36:262941 }
2942 // TODO(creis): Set user gesture and intent received timestamp on Android.
2943
2944 // We may not have successfully added the FrameNavigationEntry to |entry|
2945 // above (per https://crbug.com/608402), in which case we create it from
2946 // scratch. This works because we do not depend on |frame_entry| being inside
2947 // |entry| during NavigateToEntry. This will go away when we shortcut this
2948 // further in https://crbug.com/536906.
2949 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2950 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452951 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082952 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582953 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372954 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212955 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152956 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572957 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262958 }
2959
Camille Lamy5193caa2018-10-12 11:59:422960 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022961 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452962 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292963 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212964 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422965 params.source_site_instance = source_site_instance;
2966 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2967 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032968 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422969 params.referrer = referrer;
2970 /* params.redirect_chain: skip */
2971 params.extra_headers = extra_headers;
2972 params.is_renderer_initiated = is_renderer_initiated;
2973 params.override_user_agent = UA_OVERRIDE_INHERIT;
2974 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542975 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422976 /* params.data_url_as_string: skip */
2977 params.post_data = post_body;
2978 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582979 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422980 /* params.frame_name: skip */
2981 // TODO(clamy): See if user gesture should be propagated to this function.
2982 params.has_user_gesture = false;
2983 params.should_clear_history_list = false;
2984 params.started_from_context_menu = false;
2985 /* params.navigation_ui_data: skip */
2986 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222987 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542988 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212989 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412990 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502991 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292992 params.initiator_activation_and_ad_status =
2993 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032994 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422995
2996 std::unique_ptr<NavigationRequest> request =
2997 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032998 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142999 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:393000 ReloadType::NONE, entry.get(), frame_entry.get(),
Charlie Reise1d9b8182025-04-02 04:32:123001 actual_navigation_start_time, navigation_start_time,
3002 is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583003 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343004 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:233005
3006 if (!request)
3007 return;
3008
Garrett Tanzerbb8db412022-09-27 21:59:463009 // Force the navigation to take place in a new browsing instance.
3010 // This is used by _unfencedTop in fenced frames to ensure that navigations
3011 // leaving the fenced context create a new browsing instance.
3012 if (force_new_browsing_instance) {
3013 request->coop_status().ForceBrowsingInstanceSwap();
3014 }
3015
Arthur Hemery948742762019-09-18 10:06:243016 // At this stage we are proceeding with this navigation. If this was renderer
3017 // initiated with user gesture, we need to make sure we clear up potential
3018 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
3019 DiscardNonCommittedEntries();
3020
Lukasz Anforowicz9ee83c272020-12-01 20:14:053021 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:263022}
3023
[email protected]d1198fd2012-08-13 22:50:193024void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253025 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:213026 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:193027 if (!session_storage_namespace)
3028 return;
3029
3030 // We can't overwrite an existing SessionStorage without violating spec.
3031 // Attempts to do so may give a tab access to another tab's session storage
3032 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:153033 bool successful_insert =
3034 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:253035 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:053036 static_cast<SessionStorageNamespaceImpl*>(
3037 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:303038 .second;
3039 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:193040}
3041
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573042bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:453043 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:033044 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:463045}
3046
Aran Gilman37d11632019-10-08 23:07:153047SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253048 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:303049 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:253050 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:033051 DOMStorageContextWrapper* context_wrapper =
3052 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
3053
3054 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:253055 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:033056 if (it != session_storage_namespace_map_.end()) {
3057 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:153058 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
3059 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:473060
michaelnbacbcbd2016-02-09 00:32:033061 return it->second.get();
3062 }
3063
3064 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:103065 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
3066 SessionStorageNamespaceImpl::Create(context_wrapper);
3067 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
3068 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:253069 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:103070 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:303071
Daniel Murphy31bbb8b12018-02-07 21:44:103072 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:303073}
3074
3075SessionStorageNamespace*
3076NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:253077 return GetSessionStorageNamespace(
3078 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:303079}
3080
3081const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573082NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303083 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553084}
[email protected]d202a7c2012-01-04 07:53:473085
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573086bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563087 return needs_reload_;
3088}
[email protected]a26023822011-12-29 00:23:553089
[email protected]46bb5e9c2013-10-03 22:16:473090void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413091 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3092}
3093
3094void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473095 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413096 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543097
3098 if (last_committed_entry_index_ != -1) {
3099 entries_[last_committed_entry_index_]->SetTransitionType(
3100 ui::PAGE_TRANSITION_RELOAD);
3101 }
[email protected]46bb5e9c2013-10-03 22:16:473102}
3103
[email protected]d202a7c2012-01-04 07:53:473104void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573105 DCHECK_LT(index, GetEntryCount());
3106 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313107 DiscardNonCommittedEntries();
3108
Nate Chapin9eb16be72022-09-23 22:54:313109 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313110 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123111 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313112 last_committed_entry_index_--;
3113}
3114
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573115NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273116 // If there is no pending_entry_, there should be no pending_entry_index_.
3117 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3118
3119 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363120 // at that index. An exception is while a reload of a post commit error page
3121 // is ongoing; in that case pending entry will point to the entry replaced
3122 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273123 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363124 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3125 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273126
[email protected]022af742011-12-28 18:37:253127 return pending_entry_;
3128}
3129
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573130int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273131 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273132 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553133 return pending_entry_index_;
3134}
3135
avi25764702015-06-23 15:43:373136void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573137 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363138 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313139 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003140 bool in_fenced_frame_tree,
3141 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313142 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3143 // set because:
3144 // 1) They don't influence the history of the outer page.
3145 // 2) They are always replace only navigation (there is always only one entry
3146 // in their history stack).
3147 // 3) Are not top level navigations and appear similar to iframes.
3148 // Navigations of the fenced frame might create a new NavigationEntry, which
3149 // will call this function. Non fenced frame navigations will never have
3150 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3151 // InsertOrReplaceEntry.
3152 DCHECK_EQ(in_fenced_frame_tree,
3153 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3154 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203155
avi5cad4912015-06-19 05:25:443156 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3157 // need to keep continuity with the pending entry, so copy the pending entry's
3158 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3159 // then the renderer navigated on its own, independent of the pending entry,
3160 // so don't copy anything.
3161 if (pending_entry_ && pending_entry_index_ == -1)
3162 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203163
Rakina Zata Amnia4e27222021-12-22 01:05:003164 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203165
creisee17e932015-07-17 17:56:223166 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453167 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103168 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573169 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363170 // If the new entry is a post-commit error page, we store the current last
3171 // committed entry to the side so that we can put it back when navigating
3172 // away from the error.
3173 if (was_post_commit_error) {
3174 DCHECK(!entry_replaced_by_post_commit_error_);
3175 entry_replaced_by_post_commit_error_ =
3176 std::move(entries_[last_committed_entry_index_]);
3177 }
dcheng36b6aec92015-12-26 06:16:363178 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223179 return;
3180 }
[email protected]765b35502008-08-21 00:51:203181
creis37979a62015-08-04 19:48:183182 // We shouldn't see replace == true when there's no committed entries.
3183 DCHECK(!replace);
3184
Michael Thiessen9b14d512019-09-23 21:19:473185 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203186
Shivani Sharmad8c8d652019-02-13 17:27:573187 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203188
dcheng36b6aec92015-12-26 06:16:363189 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203190 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293191}
3192
Shivani Sharmad8c8d652019-02-13 17:27:573193void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163194 if (entries_.size() < max_entry_count())
3195 return;
3196
3197 DCHECK_EQ(max_entry_count(), entries_.size());
3198 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573199 CHECK_EQ(pending_entry_index_, -1);
3200
3201 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423202 // Retrieve the oldest skippable entry.
3203 for (; index < GetEntryCount(); index++) {
3204 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3205 break;
Shivani Sharmad8c8d652019-02-13 17:27:573206 }
3207
3208 // If there is no skippable entry or if it is the last committed entry then
3209 // fall back to pruning the oldest entry. It is not safe to prune the last
3210 // committed entry.
3211 if (index == GetEntryCount() || index == last_committed_entry_index_)
3212 index = 0;
3213
3214 bool should_succeed = RemoveEntryAtIndex(index);
3215 DCHECK_EQ(true, should_succeed);
3216
3217 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253218}
3219
William Liu62ae26c2024-08-08 14:28:163220std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273221NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163222 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203223 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373224 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133225 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493226 const std::string* navigation_api_key,
3227 base::TimeTicks actual_navigation_start) {
Alexander Timin3a92df72019-09-20 11:59:503228 TRACE_EVENT0("navigation",
3229 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273230 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023231 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363232 if (pending_entry_index_ != -1) {
3233 // The pending entry may not be in entries_ if a post-commit error page is
3234 // showing.
3235 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3236 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3237 }
Gyuyoung Kim107c2a02021-04-13 01:49:303238 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573239 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013240 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033241 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573242 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133243 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3244 // the same as the top level frame being navigated.
3245 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373246 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133247 }
Arthur Sonzogni620cec62018-12-13 13:08:573248
[email protected]83c2e232011-10-07 21:36:463249 // If we were navigating to a slow-to-commit page, and the user performs
3250 // a session history navigation to the last committed page, RenderViewHost
3251 // will force the throbber to start, but WebKit will essentially ignore the
3252 // navigation, and won't send a message to stop the throbber. To prevent this
3253 // from happening, we drop the navigation here and stop the slow-to-commit
3254 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023255 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083256 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273257 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033258 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123259
[email protected]83c2e232011-10-07 21:36:463260 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163261 return {};
[email protected]83c2e232011-10-07 21:36:463262 }
3263
Arthur Sonzognic686e8f2024-01-11 08:36:373264 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333265 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3266 if (initiator_rfh) {
3267 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543268 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333269 DCHECK(initiator_frame_token);
3270 }
3271
creisce0ef3572017-01-26 17:53:083272 // Compare FrameNavigationEntries to see which frames in the tree need to be
3273 // navigated.
clamy3cb9bea92018-07-10 12:42:023274 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3275 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333276 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3277 initiator_process_id, soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493278 actual_navigation_start, &same_document_loads,
3279 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303280
3281 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573282 // We were unable to match any frames to navigate. This can happen if a
3283 // history navigation targets a subframe that no longer exists
3284 // (https://crbug.com/705550). In this case, we need to update the current
3285 // history entry to the pending one but keep the main document loaded. We
3286 // also need to ensure that observers are informed about the updated
3287 // current history entry (e.g., for greying out back/forward buttons), and
Charlie Reis99b2eba22025-01-31 19:18:573288 // that renderer processes update their history indices. The easiest way
Alex Moshchuk3a4e77a2020-05-29 21:32:573289 // to do all that is to schedule a "redundant" same-document navigation in
3290 // the main frame.
3291 //
3292 // Note that we don't want to remove this history entry, as it might still
3293 // be valid later, since a frame that it's targeting may be recreated.
3294 //
3295 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3296 // need to repeat history navigations until finding the one that works.
3297 // Consider changing this behavior to keep looking for the first valid
3298 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023299 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423300 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573301 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573302 ReloadType::NONE /* reload_type */,
3303 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433304 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493305 initiator_frame_token, initiator_process_id,
3306 actual_navigation_start);
clamy3cb9bea92018-07-10 12:42:023307 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573308 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023309 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163310 return {};
clamy3cb9bea92018-07-10 12:42:023311 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573312 same_document_loads.push_back(std::move(navigation_request));
3313
3314 // Sanity check that we never take this branch for any kinds of reloads,
3315 // as those should've queued a different-document load in the main frame.
3316 DCHECK(!is_forced_reload);
3317 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303318 }
3319
Nate Chapinbf682fa32022-09-26 22:41:203320 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163321 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203322 if (initiator_rfh && initiator_rfh->IsSandboxed(
3323 network::mojom::WebSandboxFlags::kTopNavigation)) {
3324 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3325 initiator_rfh, same_document_loads) &&
3326 DoesSandboxNavigationStayWithinSubtree(
3327 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503328 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163329 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203330 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3331 initiator_rfh,
3332 navigates_inside_tree
3333 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3334 : blink::mojom::WebFeature::
3335 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523336
3337 // If the navigation occurred outside the tree discard it because
3338 // the sandboxed frame didn't have permission to navigate outside
3339 // its tree. If it is possible that the navigation is both inside and
3340 // outside the frame tree and we discard it entirely because we don't
3341 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143342 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203343 // If a |navigation_api_key| was provided, this navigation originated from
3344 // the navigation API. Notify the renderer that the navigation was
3345 // cancelled so the navigation API can fire an error event and reject the
3346 // relevant promise.
3347 if (navigation_api_key) {
3348 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3349 *navigation_api_key,
3350 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3351 }
Dave Tapuska855c1e12019-08-23 20:45:523352 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133353
3354 for (auto& unused_request : same_document_loads) {
3355 unused_request->set_navigation_discard_reason(
3356 NavigationDiscardReason::kNeverStarted);
3357 }
3358 for (auto& unused_request : different_document_loads) {
3359 unused_request->set_navigation_discard_reason(
3360 NavigationDiscardReason::kNeverStarted);
3361 }
William Liu62ae26c2024-08-08 14:28:163362 return {};
Dave Tapuska855c1e12019-08-23 20:45:523363 }
Dave Tapuska8bfd84c2019-03-26 20:47:163364 }
3365
Nate Chapin6c43c022023-02-13 23:32:423366 // If it is possible that this traverse may involve a same-document navigation
3367 // in the initiator and there is a Navigation API key involved, then we may
3368 // need to notify the initiator if it fails. (The early returns above either
3369 // do not involve these cases or already notify the initiator.)
3370 // The event only needs to fire for the initiator, and only if the initiator
3371 // itself is performing a same-document navigation (because the event will not
3372 // fire if it navigates cross-document).
3373 if (navigation_api_key) {
3374 for (auto& item : same_document_loads) {
3375 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3376 item->set_pending_navigation_api_key(*navigation_api_key);
3377 break;
3378 }
3379 }
3380 }
3381
Carlos Caballero539a421c2020-07-06 10:25:573382 // BackForwardCache:
3383 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563384 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573385 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
Charlie Reis3696ab62025-05-28 07:02:303386 // TODO(crbug.com/420275259): Diagnose failures and upgrade to a CHECK.
3387 DCHECK_EQ(reload_type, ReloadType::NONE);
Charlie Reis655c8f02025-05-15 01:16:173388 base::WeakPtr<NavigationRequest> request;
Rakina Zata Amni58681c62024-06-25 06:32:133389
Charlie Reis655c8f02025-05-15 01:16:173390 // Skip a redundant NavigationRequest creation, per
3391 // https://crbug.com/417251428.
3392 if (base::FeatureList::IsEnabled(kSkipExtraBfcacheNavigationRequest)) {
3393 // If the BackForwardCache can handle this request, it must be for a main
3394 // frame, cross-document, non-reload request. This means there is only one
3395 // item in `different_document_loads` and no `same_document_loads`.
3396 CHECK_EQ(different_document_loads.size(), 1u);
3397 CHECK(same_document_loads.empty());
3398 request = different_document_loads.at(0)->GetWeakPtr();
Charlie Reisd3e4fef2025-05-20 02:04:173399
3400 // Ensure that no re-entrant calls or discards of the pending entry occur
3401 // while calling `Navigator::Navigate` for a pending entry.
3402 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3403 weak_factory_.GetSafeRef());
3404
Charlie Reis655c8f02025-05-15 01:16:173405 root->navigator().Navigate(std::move(different_document_loads.at(0)),
3406 ReloadType::NONE);
Charlie Reisd3e4fef2025-05-20 02:04:173407
3408 // `reentrancy_guard` deleted here.
Charlie Reis655c8f02025-05-15 01:16:173409 } else {
3410 // The legacy approach creates a new NavigationRequest for the entry and
3411 // discards any previously created NavigationRequests, even though the new
3412 // request is identical to the sole existing request.
3413 // TODO(crbug.com/417251428): Remove this path once we measure the impact.
3414 auto navigation_request = CreateNavigationRequestFromEntry(
3415 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3416 ReloadType::NONE, false /* is_same_document_history_load */,
3417 false /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:493418 initiator_process_id, actual_navigation_start);
Charlie Reis655c8f02025-05-15 01:16:173419 request = navigation_request->GetWeakPtr();
3420 root->navigator().Navigate(std::move(navigation_request),
3421 ReloadType::NONE);
3422
3423 for (auto& unused_request : same_document_loads) {
3424 unused_request->set_navigation_discard_reason(
3425 NavigationDiscardReason::kNeverStarted);
3426 }
3427 for (auto& unused_request : different_document_loads) {
3428 unused_request->set_navigation_discard_reason(
3429 NavigationDiscardReason::kNeverStarted);
3430 }
Rakina Zata Amni58681c62024-06-25 06:32:133431 }
3432
Charlie Reis655c8f02025-05-15 01:16:173433 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_requests;
William Liu62ae26c2024-08-08 14:28:163434 if (request) {
Charlie Reis655c8f02025-05-15 01:16:173435 bf_cache_requests.push_back(std::move(request));
William Liu62ae26c2024-08-08 14:28:163436 }
Charlie Reis655c8f02025-05-15 01:16:173437 return bf_cache_requests;
Carlos Caballero539a421c2020-07-06 10:25:573438 }
3439
3440 // History navigation might try to reuse a specific BrowsingInstance, already
3441 // used by a page in the cache. To avoid having two different main frames that
3442 // live in the same BrowsingInstance, evict the all pages with this
3443 // BrowsingInstance from the cache.
3444 //
3445 // For example, take the following scenario:
3446 //
3447 // A1 = Some page on a.com
3448 // A2 = Some other page on a.com
3449 // B3 = An uncacheable page on b.com
3450 //
3451 // Then the following navigations occur:
3452 // A1->A2->B3->A1
3453 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3454 // take its place) and A1 will be created in the same BrowsingInstance (and
3455 // SiteInstance), as A2.
3456 //
3457 // If we didn't do anything, both A1 and A2 would remain alive in the same
3458 // BrowsingInstance/SiteInstance, which is unsupported by
3459 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3460 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483461 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3462 pending_entry_->site_instance()
3463 ? pending_entry_->site_instance()->GetId().value()
3464 : -1);
3465 SCOPED_CRASH_KEY_NUMBER(
3466 "rvh_double", "pending_entry_bi",
3467 pending_entry_->site_instance()
3468 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3469 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573470 if (pending_entry_->site_instance()) {
3471 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3472 pending_entry_->site_instance());
3473 }
3474
Rakina Zata Amnid605d462022-06-01 10:17:033475 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3476 pending_entry_ && pending_entry_->IsRestored());
3477 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3478 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3479 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3480 pending_entry_index_);
3481 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3482 last_committed_entry_index_);
3483 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3484 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3485 pending_entry_ && pending_entry_->IsInitialEntry());
3486 SCOPED_CRASH_KEY_BOOL(
3487 "nav_reentrancy", "pending_entry_initial2",
3488 pending_entry_ &&
3489 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3490 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3491 IsInitialNavigation());
3492 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3493 IsInitialBlankNavigation());
3494 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3495 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3496 (int)pending_reload_);
3497
Charlie Reisd3e4fef2025-05-20 02:04:173498 // Ensure that no re-entrant calls or discards of the pending entry occur
3499 // while calling `Navigator::Navigate` for a pending entry.
3500 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3501 weak_factory_.GetSafeRef());
creis4e2ecb72015-06-20 00:46:303502
Rakina Zata Amnid605d462022-06-01 10:17:033503 // If the navigation-reentrancy is caused by calling
3504 // NavigateToExistingPendingEntry twice, this will note the previous call's
3505 // pending entry's ID.
3506 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3507 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3508
Nate Chapin154b14b2023-02-17 18:28:163509 // If there is a main-frame same-document history navigation, we may defer
3510 // the subframe history navigations in order to give JS in the main frame the
3511 // opportunity to cancel the entire traverse via the navigate event. In that
3512 // case, we need to stash the main frame request's navigation token on the
3513 // subframes, so they can look up the main frame request and defer themselves
3514 // until it completes.
3515 if (!same_document_loads.empty() &&
3516 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3517 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3518 // The token will only be returned in cases where deferring the navigation
3519 // is necessary.
3520 if (auto main_frame_same_document_token =
3521 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3522 for (auto& item : same_document_loads) {
3523 if (item.get() != main_frame_request) {
3524 item->set_main_frame_same_document_history_token(
3525 main_frame_same_document_token);
3526 }
3527 }
3528 for (auto& item : different_document_loads) {
3529 item->set_main_frame_same_document_history_token(
3530 main_frame_same_document_token);
3531 }
3532 }
3533 }
3534
William Liu122754942024-01-18 22:34:393535 if (!initiator_rfh) {
3536 // A browser-initiated navigation won't have a `initiator_rfh`.
3537 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3538 different_document_loads, same_document_loads);
3539 }
3540
William Liu62ae26c2024-08-08 14:28:163541 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3542 all_requests.reserve(same_document_loads.size() +
3543 different_document_loads.size());
3544 bool seen_primary_main_frame_request = false;
3545
creis4e2ecb72015-06-20 00:46:303546 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023547 for (auto& item : same_document_loads) {
3548 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273549 // The request could be destroyed before `navigator().Navigate()` returns.
3550 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053551 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163552 if (request) {
3553 // Can only have one primary main frame request.
3554 CHECK(!seen_primary_main_frame_request ||
3555 !request->IsInPrimaryMainFrame());
3556 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3557 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273558 }
creis4e2ecb72015-06-20 00:46:303559 }
clamy3cb9bea92018-07-10 12:42:023560 for (auto& item : different_document_loads) {
3561 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273562 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053563 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163564 if (request) {
3565 // Can only have one primary main frame request.
3566 CHECK(!seen_primary_main_frame_request ||
3567 !request->IsInPrimaryMainFrame());
3568 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3569 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273570 }
creis4e2ecb72015-06-20 00:46:303571 }
clamy3cb9bea92018-07-10 12:42:023572
William Liu62ae26c2024-08-08 14:28:163573 return all_requests;
Charlie Reisd3e4fef2025-05-20 02:04:173574 // `reentrancy_guard` deleted here.
creis4e2ecb72015-06-20 00:46:303575}
3576
Alex Moshchuk3a4e77a2020-05-29 21:32:573577NavigationControllerImpl::HistoryNavigationAction
3578NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303579 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573580 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423581 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583582 // Only active and prerendered documents are allowed to navigate in their
3583 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423584 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013585 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583586 // - If the document is in pending deletion, the browser already committed
3587 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3588 // - If the document is in back-forward cache, it's not allowed to navigate
3589 // as it should remain frozen. Ignore the request and evict the document
3590 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423591 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583592 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423593 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113594 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3595 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423596 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113597 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423598 }
arthursonzogni03f76152019-02-12 10:35:203599
Alex Moshchuk3a4e77a2020-05-29 21:32:573600 // Reloads should result in a different-document load. Note that reloads may
3601 // also happen via the |needs_reload_| mechanism where the reload_type is
3602 // NONE, so detect this by comparing whether we're going to the same
3603 // entry that we're currently on. Similarly to above, only main frames
3604 // should reach this. Note that subframes support reloads, but that's done
3605 // via a different path that doesn't involve FindFramesToNavigate (see
3606 // RenderFrameHost::Reload()).
3607 if (reload_type != ReloadType::NONE ||
3608 pending_entry_index_ == last_committed_entry_index_) {
3609 DCHECK(frame->IsMainFrame());
3610 return HistoryNavigationAction::kDifferentDocument;
3611 }
3612
Alex Moshchuk47d1a4bd2020-06-01 22:15:343613 // If there is no new FrameNavigationEntry for the frame, ignore the
3614 // load. For example, this may happen when going back to an entry before a
3615 // frame was created. Suppose we commit a same-document navigation that also
3616 // results in adding a new subframe somewhere in the tree. If we go back,
3617 // the new subframe will be missing a FrameNavigationEntry in the previous
3618 // NavigationEntry, but we shouldn't delete or change what's loaded in
3619 // it.
3620 //
Alex Moshchuke65c39272020-06-03 17:55:373621 // Note that in this case, there is no need to keep looking for navigations
3622 // in subframes, which would be missing FrameNavigationEntries as well.
3623 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343624 // It's important to check this before checking |old_item| below, since both
3625 // might be null, and in that case we still shouldn't change what's loaded in
3626 // this frame. Note that scheduling any loads assumes that |new_item| is
3627 // non-null. See https://crbug.com/1088354.
3628 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3629 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373630 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343631
Charlie Reisa474fb62022-03-17 02:31:363632 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3633 // which history item it is currently on, since this may be different than the
3634 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3635 // (e.g., if a history navigation is targeting multiple frames and only some
3636 // have committed so far).
creis4e2ecb72015-06-20 00:46:303637 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363638 frame->current_frame_host()->last_committed_frame_entry();
3639 if (!old_item) {
3640 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3641 // fall back to the last committed NavigationEntry's record for this frame.
3642 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583643 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363644 // accurate FrameNavigationEntry and eliminate this case.
3645 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3646 }
3647 // If neither approach finds a FrameNavigationEntry, schedule a
3648 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583649 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573650 if (!old_item)
3651 return HistoryNavigationAction::kDifferentDocument;
3652
Alex Moshchuk3a4e77a2020-05-29 21:32:573653 // If the new item is not in the same SiteInstance, schedule a
3654 // different-document load. Newly restored items may not have a SiteInstance
3655 // yet, in which case it will be assigned on first commit.
3656 if (new_item->site_instance() &&
3657 new_item->site_instance() != old_item->site_instance())
3658 return HistoryNavigationAction::kDifferentDocument;
3659
Charlie Reis71e4ae32025-01-29 21:37:573660 // If the origins of the new and old items are both present but don't match,
3661 // schedule a different document load even if the document sequence numbers
3662 // somehow match.
3663 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3664 // committed origin on `new_item`, and update the Blink DSN computation to
3665 // avoid a cross-origin DSN match when possible.
3666 if (new_item->committed_origin().has_value() &&
3667 old_item->committed_origin().has_value() &&
3668 !new_item->committed_origin()->IsSameOriginWith(
3669 old_item->committed_origin().value())) {
3670 return HistoryNavigationAction::kDifferentDocument;
3671 }
3672
Alex Moshchuk3a4e77a2020-05-29 21:32:573673 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313674 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3675 // that we do this even if the history navigation would not be modifying this
3676 // frame were it live.
3677 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573678 return HistoryNavigationAction::kDifferentDocument;
3679
3680 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313681 // Starting a navigation after a crash early-promotes the speculative
3682 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3683 // committed yet, so we can not possibly perform a same-document history
3684 // navigation. The frame would need to be reloaded with a cross-document
3685 // navigation.
3686 if (!frame->current_frame_host()->has_committed_any_navigation())
3687 return HistoryNavigationAction::kDifferentDocument;
3688
creis54131692016-08-12 18:32:253689 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493690 // sequence number but different item sequence number.
3691 if (new_item->document_sequence_number() ==
3692 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573693 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493694 }
avib48cb312016-05-05 21:35:003695
Alex Moshchuk3a4e77a2020-05-29 21:32:573696 // Otherwise, if both item and document sequence numbers differ, this
3697 // should be a different document load.
3698 return HistoryNavigationAction::kDifferentDocument;
3699 }
3700
3701 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373702 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573703 DCHECK_EQ(new_item->document_sequence_number(),
3704 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373705 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573706}
3707
3708void NavigationControllerImpl::FindFramesToNavigate(
3709 FrameTreeNode* frame,
3710 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373711 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333712 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373713 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133714 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493715 base::TimeTicks actual_navigation_start,
Alex Moshchuk3a4e77a2020-05-29 21:32:573716 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3717 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3718 DCHECK(pending_entry_);
3719 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3720
3721 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3722
3723 if (action == HistoryNavigationAction::kSameDocument) {
3724 std::unique_ptr<NavigationRequest> navigation_request =
3725 CreateNavigationRequestFromEntry(
3726 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133727 /*is_same_document_history_load=*/true,
3728 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333729 initiator_frame_token, initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:493730 actual_navigation_start, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573731 if (navigation_request) {
3732 // Only add the request if was properly created. It's possible for the
3733 // creation to fail in certain cases, e.g. when the URL is invalid.
3734 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303735 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573736 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473737 std::unique_ptr<NavigationRequest> navigation_request =
3738 CreateNavigationRequestFromEntry(
3739 frame, pending_entry_, new_item, reload_type,
3740 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433741 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493742 initiator_frame_token, initiator_process_id,
3743 actual_navigation_start);
Lei Zhang96031532019-10-10 19:05:473744 if (navigation_request) {
3745 // Only add the request if was properly created. It's possible for the
3746 // creation to fail in certain cases, e.g. when the URL is invalid.
3747 different_document_loads->push_back(std::move(navigation_request));
3748 }
3749 // For a different document, the subframes will be destroyed, so there's
3750 // no need to consider them.
3751 return;
Alex Moshchuke65c39272020-06-03 17:55:373752 } else if (action == HistoryNavigationAction::kStopLooking) {
3753 return;
creis4e2ecb72015-06-20 00:46:303754 }
3755
Yoav Weiss8c573952022-11-17 17:35:133756 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3757 // we currently only support soft navigation heuristics for the top level
3758 // frame.
creis4e2ecb72015-06-20 00:46:303759 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333760 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3761 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373762 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:493763 actual_navigation_start, same_document_loads,
3764 different_document_loads);
creis4e2ecb72015-06-20 00:46:303765 }
3766}
3767
Harkiran Bolariaba823e42021-05-21 18:30:363768base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
Charlie Reisf4d51f402025-05-23 18:00:493769 const LoadURLParams& params,
3770 base::TimeTicks actual_navigation_start) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553771 FrameTreeNode* node = GetTargetFrameTreeNodeForNavigation(params);
clamy21718cc22018-06-13 13:34:243772
Camille Lamy5193caa2018-10-12 11:59:423773 // Compute overrides to the LoadURLParams for |override_user_agent|,
3774 // |should_replace_current_entry| and |has_user_gesture| that will be used
3775 // both in the creation of the NavigationEntry and the NavigationRequest.
3776 // Ideally, the LoadURLParams themselves would be updated, but since they are
3777 // passed as a const reference, this is not possible.
3778 // TODO(clamy): When we only create a NavigationRequest, move this to
3779 // CreateNavigationRequestFromLoadURLParams.
3780 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3781 GetLastCommittedEntry());
3782
Rakina Zata Amnie2d31312022-11-18 03:38:453783 // An entry replacement must happen if the current browsing context should
3784 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333785 bool should_replace_current_entry =
3786 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453787 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423788
clamy21718cc22018-06-13 13:34:243789 // Javascript URLs should not create NavigationEntries. All other navigations
3790 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243791 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373792 std::unique_ptr<NavigationEntryImpl> entry =
3793 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3794 should_replace_current_entry,
3795 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243796 DiscardPendingEntry(false);
3797 SetPendingEntry(std::move(entry));
3798 }
3799
Tim Judkins59548192023-05-17 17:51:203800 // Renderer-debug URLs are sent to the current renderer process immediately
3801 // for processing and don't need to create a NavigationRequest. Note: this
3802 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243803 // renderer-debug URLs.
3804 // Note: we intentionally leave the pending entry in place for renderer debug
3805 // URLs, unlike the cases below where we clear it if the navigation doesn't
3806 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303807 if (blink::IsRendererDebugURL(params.url)) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553808 // Renderer-debug URLs won't go through NavigationThrottles so we have to
3809 // check them explicitly. See crbug.com/40605746.
Aaron Colwelle1908d982020-06-26 22:08:153810 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203811 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483812 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363813 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483814 }
3815
clamy21718cc22018-06-13 13:34:243816 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363817 return nullptr;
clamy21718cc22018-06-13 13:34:243818 }
3819
Antonio Sartori78a749f2020-11-30 12:03:393820 DCHECK(pending_entry_);
3821
clamy21718cc22018-06-13 13:34:243822 // Convert navigations to the current URL to a reload.
3823 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3824 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3825 // DevTools sometimes issues navigations to main frames that they do not
3826 // expect to see treated as reload, and it only works because they pass a
3827 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3828 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543829 ReloadType reload_type = params.reload_type;
3830 if (reload_type == ReloadType::NONE &&
3831 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043832 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243833 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243834 params.load_type ==
3835 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543836 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243837 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473838 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393839
3840 // If this is a reload of an existing FrameNavigationEntry and we had a
3841 // policy container for it, then we should copy it into the pending entry,
3842 // so that it is copied to the navigation request in
3843 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453844 FrameNavigationEntry* previous_frame_entry =
3845 GetLastCommittedEntry()->GetFrameEntry(node);
3846 if (previous_frame_entry &&
3847 previous_frame_entry->policy_container_policies()) {
3848 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3849 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393850 }
3851 }
3852
3853 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173854 // document, then we should copy the document polices from RenderFrameHost's
3855 // PolicyContainerHost. The NavigationRequest will create a new
3856 // PolicyContainerHost with the document policies from the |pending_entry_|,
3857 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3858 // the navigation. This way, we ensure that we keep enforcing the right
3859 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453860 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393861 if (node->current_frame_host() &&
3862 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193863 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163864 node->current_frame_host()
3865 ->policy_container_host()
3866 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233867 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393868 }
clamy21718cc22018-06-13 13:34:243869 }
3870
3871 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263872 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243873
Tsuyoshi Horo167ca6432022-03-09 05:16:393874 // This will be used to set the Navigation Timing API navigationStart
3875 // parameter for browser navigations in new tabs (intents, tabs opened through
3876 // "Open link in new tab"). If the navigation must wait on the current
3877 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3878 // will be updated when the BeforeUnload ack is received.
3879 const auto navigation_start_time = base::TimeTicks::Now();
Tsuyoshi Horo167ca6432022-03-09 05:16:393880
Camille Lamy5193caa2018-10-12 11:59:423881 std::unique_ptr<NavigationRequest> request =
3882 CreateNavigationRequestFromLoadParams(
3883 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143884 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393885 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
Charlie Reisf4d51f402025-05-23 18:00:493886 actual_navigation_start, navigation_start_time);
clamy21718cc22018-06-13 13:34:243887
3888 // If the navigation couldn't start, return immediately and discard the
3889 // pending NavigationEntry.
3890 if (!request) {
3891 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363892 return nullptr;
clamy21718cc22018-06-13 13:34:243893 }
3894
Camille Lamy5193caa2018-10-12 11:59:423895#if DCHECK_IS_ON()
3896 // Safety check that NavigationRequest and NavigationEntry match.
3897 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3898#endif
3899
Charlie Reisd3e4fef2025-05-20 02:04:173900 // Ensure that no re-entrant calls or discards of the pending entry occur
3901 // while calling `Navigator::Navigate` for a pending entry.
3902 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3903 weak_factory_.GetSafeRef());
arthursonzogni66f711c2019-10-08 14:40:363904
Harkiran Bolariaba823e42021-05-21 18:30:363905 base::WeakPtr<NavigationHandle> created_navigation_handle(
3906 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053907 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243908
Harkiran Bolariaba823e42021-05-21 18:30:363909 return created_navigation_handle;
Charlie Reisd3e4fef2025-05-20 02:04:173910 // `reentrancy_guard` deleted here.
clamy21718cc22018-06-13 13:34:243911}
3912
Emmanuel Arias Soto9e159652025-05-16 07:53:553913FrameTreeNode* NavigationControllerImpl::GetTargetFrameTreeNodeForNavigation(
3914 const LoadURLParams& params) {
3915 FrameTreeNode* node = nullptr;
3916 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3917 node = params.frame_tree_node_id
3918 ? frame_tree_->FindByID(params.frame_tree_node_id)
3919 : frame_tree_->FindByName(params.frame_name);
3920 DCHECK(!node || &node->frame_tree() == &frame_tree());
3921 if (!node && params.frame_tree_node_id) {
3922 // If the specified FrameTreeNode exists in another FrameTree, the caller
3923 // is using the wrong NavigationController.
3924 CHECK(!FrameTreeNode::GloballyFindByID(params.frame_tree_node_id),
3925 base::NotFatalUntil::M140);
3926 }
3927 }
3928
3929 // If no FrameTreeNode was specified, navigate the main frame.
3930 if (!node) {
3931 node = frame_tree_->root();
3932 }
3933 return node;
3934}
3935
clamyea99ea12018-05-28 13:54:233936void NavigationControllerImpl::HandleRendererDebugURL(
3937 FrameTreeNode* frame_tree_node,
3938 const GURL& url) {
3939 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243940 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3941 // the renderer process is not live, unless it is the initial navigation
3942 // of the tab.
clamyea99ea12018-05-28 13:54:233943 if (!IsInitialNavigation()) {
3944 DiscardNonCommittedEntries();
3945 return;
3946 }
Fergal Dalyecd3b0202020-06-25 01:57:373947 // The current frame is always a main frame. If IsInitialNavigation() is
3948 // true then there have been no navigations and any frames of this tab must
3949 // be in the same renderer process. If that has crashed then the only frame
3950 // that can be revived is the main frame.
3951 frame_tree_node->render_manager()
3952 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233953 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223954
3955 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3956 // notification, so set is loading to true here to properly surface it when
3957 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313958 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223959 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223960 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223961 }
clamyea99ea12018-05-28 13:54:233962 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3963}
3964
clamy21718cc22018-06-13 13:34:243965std::unique_ptr<NavigationEntryImpl>
3966NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3967 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423968 const LoadURLParams& params,
3969 bool override_user_agent,
3970 bool should_replace_current_entry,
3971 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393972 // Browser initiated navigations might not have a blob_url_loader_factory set
3973 // in params even if the navigation is to a blob URL. If that happens, lookup
3974 // the correct url loader factory to use here.
3975 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483976 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473977 // Resolve the blob URL in the storage partition associated with the target
3978 // frame. This is the storage partition the URL will be loaded in, and only
3979 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393980 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473981 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393982 }
3983
clamy21718cc22018-06-13 13:34:243984 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443985 // extra_headers in params are \n separated; navigation entries want \r\n.
3986 std::string extra_headers_crlf;
3987 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243988
3989 // For subframes, create a pending entry with a corresponding frame entry.
3990 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453991 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243992 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083993 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243994 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373995 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213996 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3997 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393998 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163999 // a conversion of a new navigation into a reload, we will set the right
4000 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:194001 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:244002 } else {
4003 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:174004 // If `node` is the outermost main frame, it rewrites a virtual url in order
4005 // to adjust the original input url if needed. For inner frames such as
4006 // fenced frames or subframes, they don't rewrite urls as the urls are not
4007 // input urls by users.
4008 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:324009 scoped_refptr<SiteInstance> source_site_instance =
4010 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:374011 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:324012 if (source_site_instance && source_site_instance->HasProcess()) {
4013 source_process_site_url =
4014 source_site_instance->GetProcess()->GetProcessLock().site_url();
4015 }
clamy21718cc22018-06-13 13:34:244016 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:064017 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:324018 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:214019 params.transition_type, params.is_renderer_initiated,
4020 extra_headers_crlf, browser_context_, blob_url_loader_factory,
4021 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:244022 entry->set_source_site_instance(
4023 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
4024 entry->SetRedirectChain(params.redirect_chain);
4025 }
4026
4027 // Set the FTN ID (only used in non-site-per-process, for tests).
4028 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:244029 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:424030 entry->SetIsOverridingUserAgent(override_user_agent);
4031 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:544032 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:244033
clamy21718cc22018-06-13 13:34:244034 switch (params.load_type) {
4035 case LOAD_TYPE_DEFAULT:
4036 break;
4037 case LOAD_TYPE_HTTP_POST:
4038 entry->SetHasPostData(true);
4039 entry->SetPostData(params.post_data);
4040 break;
4041 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:544042 // LoadDataWithBaseURL is a special case that needs to assign both a base
4043 // URL and a virtual URL, while loading the actual content from a data
4044 // URL.
clamy21718cc22018-06-13 13:34:244045 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:544046 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:284047#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:244048 entry->SetDataURLAsString(params.data_url_as_string);
4049#endif
4050 entry->SetCanLoadLocalResources(params.can_load_local_resources);
4051 break;
Shu Yang112ad492024-07-25 17:11:544052#if BUILDFLAG(IS_ANDROID)
4053 case LOAD_TYPE_PDF_ANDROID:
4054 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
4055 // internal URL is used for the navigation URL.
4056 entry->SetVirtualURL(params.virtual_url_for_special_cases);
4057 break;
4058#endif
clamy21718cc22018-06-13 13:34:244059 }
4060
4061 // TODO(clamy): NavigationEntry is meant for information that will be kept
4062 // after the navigation ended and therefore is not appropriate for
4063 // started_from_context_menu. Move started_from_context_menu to
4064 // NavigationUIData.
4065 entry->set_started_from_context_menu(params.started_from_context_menu);
4066
4067 return entry;
4068}
4069
clamyea99ea12018-05-28 13:54:234070std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:424071NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
4072 FrameTreeNode* node,
4073 const LoadURLParams& params,
4074 bool override_user_agent,
4075 bool should_replace_current_entry,
4076 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:144077 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:424078 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574079 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:394080 FrameNavigationEntry* frame_entry,
Charlie Reise1d9b8182025-04-02 04:32:124081 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:224082 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:494083 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:454084 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584085 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:344086 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:374087 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574088 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:524089
4090 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
4091 // subframes have FrameNavigationEntries associated with them. Until then,
4092 // there may be cases where a subframe navigation is missing `frame_entry`
4093 // (e.g., see https://crbug.com/358084015).
4094
Nasko Oskov3c2f9e252019-01-10 17:45:534095 // All renderer-initiated navigations must have an initiator_origin.
4096 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:514097
Camille Lamy5193caa2018-10-12 11:59:424098 GURL url_to_load;
4099 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:324100
Camille Lamy2baa8022018-10-19 16:43:174101 // For main frames, rewrite the URL if necessary and compute the virtual URL
4102 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:264103 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424104 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:174105 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424106 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:424107
Shu Yang112ad492024-07-25 17:11:544108 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
4109 // that need to define a virtual URL to display, which differs from the
4110 // navigation URL.
4111 if (params.load_type == LOAD_TYPE_DATA) {
4112 virtual_url = params.virtual_url_for_special_cases;
4113 }
4114#if BUILDFLAG(IS_ANDROID)
4115 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
4116 virtual_url = params.virtual_url_for_special_cases;
4117 }
4118#endif
Camille Lamy5193caa2018-10-12 11:59:424119
Camille Lamy2baa8022018-10-19 16:43:174120 if (virtual_url.is_empty())
4121 virtual_url = url_to_load;
4122
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574123 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:284124
Aran Gilman249eb122019-12-02 23:32:464125 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
4126 // behavior: it is possible for two calls to RewriteUrlForNavigation to
4127 // return different results, leading to a different URL in the
4128 // NavigationRequest and FrameEntry. This will be fixed once we remove the
4129 // pending NavigationEntry, as we'll only make one call to
4130 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:524131 if (frame_entry) {
4132 VLOG_IF(1, (url_to_load != frame_entry->url()))
4133 << "NavigationRequest and FrameEntry have different URLs: "
4134 << url_to_load << " vs " << frame_entry->url();
4135 }
Camille Lamyb9ed3c52018-11-19 15:34:284136
Camille Lamy2baa8022018-10-19 16:43:174137 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424138 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174139 // NavigationRequest.
4140 } else {
4141 url_to_load = params.url;
4142 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244143 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174144 }
Camille Lamy5193caa2018-10-12 11:59:424145
Ehsan Karamad44fc72112019-02-26 18:15:474146 if (node->render_manager()->is_attaching_inner_delegate()) {
4147 // Avoid starting any new navigations since this node is now preparing for
4148 // attaching an inner delegate.
4149 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204150 }
Camille Lamy5193caa2018-10-12 11:59:424151
Alex Moshchuk99242832023-05-22 17:21:444152 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424153 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444154 }
Camille Lamy5193caa2018-10-12 11:59:424155
danakjd83d706d2020-11-25 22:11:124156 // Look for a pending commit that is to another document in this
4157 // FrameTreeNode. If one exists, then the last committed URL will not be the
4158 // current URL by the time this navigation commits.
4159 bool has_pending_cross_document_commit =
4160 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214161 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124162
Minggang Wangb9f3fa92021-07-01 15:30:314163 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494164 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524165 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494166 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134167 /*is_same_document_history_load=*/false,
4168 is_embedder_initiated_fenced_frame_navigation,
4169 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424170
4171 // Create the NavigationParams based on |params|.
4172
Hiroki Nakagawa4ed61282021-06-18 05:37:234173 bool is_view_source_mode = entry->IsViewSourceMode();
4174 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294175
Antonio Sartori6984c742021-08-26 08:03:414176 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294177
Hiroki Nakagawa4ed61282021-06-18 05:37:234178 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294179 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254180 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294181
Charlie Reisf21cd182024-08-09 21:44:524182 std::string page_state_data =
4183 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4184
Minggang Wangb9f3fa92021-07-01 15:30:314185 blink::mojom::CommonNavigationParamsPtr common_params =
4186 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214187 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514188 blink::mojom::Referrer::New(params.referrer.url,
4189 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214190 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514191 should_replace_current_entry, params.base_url_for_data_url,
Charlie Reise1d9b8182025-04-02 04:32:124192 actual_navigation_start_time, navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514193 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144194 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414195 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274196 false /* has_text_fragment_token */,
4197 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4198 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514199 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054200 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424201
Minggang Wangb9f3fa92021-07-01 15:30:314202 blink::mojom::CommitNavigationParamsPtr commit_params =
4203 blink::mojom::CommitNavigationParams::New(
Diana Quae845bf2025-04-03 20:12:374204 url::Origin(),
Ari Chivukulac7533522024-05-14 21:52:344205 // The correct storage key will be computed before committing the
4206 // navigation.
4207 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324208 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504209 std::vector<net::RedirectInfo>(), params.post_content_type,
4210 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524211 params.can_load_local_resources, page_state_data,
4212 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134213 /*intended_as_new_entry=*/true,
Charlie Reis99b2eba22025-01-31 19:18:574214 /*pending_history_list_index=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144215 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4216 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134217 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314218 params.should_clear_history_list,
4219 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224220 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134221 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514222 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284223#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134224 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144225#endif
Yoav Weiss8c573952022-11-17 17:35:134226 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154227 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134228 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074229 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134230 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4231 /*origin_agent_cluster=*/false,
4232 /*origin_agent_cluster_left_as_default=*/true,
4233 /*enabled_client_hints=*/
4234 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264235 /*is_cross_site_cross_browsing_context_group=*/false,
4236 /*should_have_sticky_user_activation=*/false,
4237 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134238 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014239 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134240 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584241 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134242 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134243 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284244 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134245 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444246 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424247 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374248 /*view_transition_state=*/std::nullopt,
4249 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054250 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464251 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374252 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054253 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094254 /*load_with_storage_access=*/
4255 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374256 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374257 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484258 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314259 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164260 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174261 node->current_frame_host()->GetCachedPermissionStatuses(),
Charlie Reiscdb798342025-02-14 22:04:464262 /*should_skip_screentshot=*/false,
Alex Moshchukd0d759c22025-05-09 18:18:354263 /*force_new_document_sequence_number=*/false,
4264 /*navigation_metrics_token=*/base::UnguessableToken::Create());
Xiaohan Wang7f8052e02022-01-14 18:44:284265#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424266 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564267 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424268 }
4269#endif
4270
Lucas Furukawa Gadania9c45682019-07-31 22:05:144271 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074272 commit_params->navigation_timing->system_entropy_at_navigation_start =
4273 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4274 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424275
Camille Lamy5193caa2018-10-12 11:59:424276 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4277 std::string extra_headers_crlf;
4278 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094279
Alex Moshchuk9321e6a2022-12-07 21:58:314280 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144281 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084282 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094283 params.initiator_frame_token, params.initiator_process_id,
4284 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214285 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294286 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454287 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344288 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034289 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134290
4291 if (!navigation_request) {
4292 return nullptr;
4293 }
4294
Yao Xiaodc5ed102019-06-04 19:19:094295 navigation_request->set_from_download_cross_origin_redirect(
4296 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554297 navigation_request->set_force_new_browsing_instance(
4298 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514299 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434300 if (params.force_no_https_upgrade) {
4301 navigation_request->set_force_no_https_upgrade();
4302 }
Yao Xiaodc5ed102019-06-04 19:19:094303 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424304}
4305
4306std::unique_ptr<NavigationRequest>
4307NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234308 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574309 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234310 FrameNavigationEntry* frame_entry,
4311 ReloadType reload_type,
4312 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434313 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374314 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334315 int initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:494316 base::TimeTicks actual_navigation_start,
Arthur Sonzognic686e8f2024-01-11 08:36:374317 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134318 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344319 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234320 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434321 // We should never navigate to an existing initial NavigationEntry that is the
4322 // initial NavigationEntry for the initial empty document that hasn't been
4323 // overridden by the synchronous about:blank commit, to preserve previous
4324 // behavior where trying to reload when the main frame is on the initial empty
4325 // document won't result in a navigation.
4326 // See also https://crbug.com/1277414.
4327 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324328
clamyea99ea12018-05-28 13:54:234329 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234330
Ehsan Karamad44fc72112019-02-26 18:15:474331 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4332 // Avoid starting any new navigations since this node is now preparing for
4333 // attaching an inner delegate.
4334 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204335 }
4336
Alex Moshchuk99242832023-05-22 17:21:444337 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4338 dest_url)) {
clamyea99ea12018-05-28 13:54:234339 return nullptr;
4340 }
4341
clamyea99ea12018-05-28 13:54:234342 // This will be used to set the Navigation Timing API navigationStart
4343 // parameter for browser navigations in new tabs (intents, tabs opened through
4344 // "Open link in new tab"). If the navigation must wait on the current
4345 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4346 // will be updated when the BeforeUnload ack is received.
clamyea99ea12018-05-28 13:54:234347 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074348 const auto navigation_start_system_entropy =
4349 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4350 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234351
danakjd83d706d2020-11-25 22:11:124352 // Look for a pending commit that is to another document in this
4353 // FrameTreeNode. If one exists, then the last committed URL will not be the
4354 // current URL by the time this navigation commits.
4355 bool has_pending_cross_document_commit =
4356 frame_tree_node->render_manager()
4357 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494358 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214359 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124360
Minggang Wangb9f3fa92021-07-01 15:30:314361 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124362 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524363 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494364 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494365 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134366 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494367 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424368
4369 // A form submission may happen here if the navigation is a
4370 // back/forward/reload navigation that does a form resubmission.
4371 scoped_refptr<network::ResourceRequestBody> request_body;
4372 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394373 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504374 // entry. This way, it could be directly retrieved here. Right now, it is only
4375 // partially recovered when request.method == "POST" and request.body exists.
4376 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424377 if (frame_entry->method() == "POST") {
4378 request_body = frame_entry->GetPostData(&post_content_type);
4379 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304380 post_content_type = std::string(
4381 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504382 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424383 }
4384
4385 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314386 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514387 entry->ConstructCommonNavigationParams(
4388 *frame_entry, request_body, dest_url,
4389 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Charlie Reisf4d51f402025-05-23 18:00:494390 navigation_type, actual_navigation_start, navigation_start,
Charlie Reise1d9b8182025-04-02 04:32:124391 /*input_start=*/base::TimeTicks());
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514392 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554393 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424394
4395 // TODO(clamy): |intended_as_new_entry| below should always be false once
4396 // Reload no longer leads to this being called for a pending NavigationEntry
4397 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314398 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144399 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404400 *frame_entry, common_params->url, common_params->method,
4401 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144402 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534403 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484404 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134405 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074406 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144407 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074408 commit_params->navigation_timing->system_entropy_at_navigation_start =
4409 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4410 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164411 commit_params->initial_permission_statuses =
4412 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424413
W. James MacLeanb7d6092682022-10-05 15:23:264414 if (common_params->url.IsAboutSrcdoc()) {
4415 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4416 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594417 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264418 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334419 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314420 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144421 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434422 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334423 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4424 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374425 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294426 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4427 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474428 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234429}
4430
[email protected]d202a7c2012-01-04 07:53:474431void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214432 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274433 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404434
Takashi Toyoshimaea534ef22021-07-21 03:27:594435 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404436 // location bar will have up-to-date information about the security style
4437 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134438 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404439
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374440 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574441 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294442}
4443
initial.commit09911bf2008-07-26 23:55:294444// static
[email protected]d202a7c2012-01-04 07:53:474445size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234446 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154447 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214448 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234449}
4450
[email protected]d202a7c2012-01-04 07:53:474451void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224452 if (is_active && needs_reload_)
4453 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214454
4455 if (frame_tree_->is_primary();
4456 auto* cache = GetNavigationEntryScreenshotCache()) {
4457 cache->SetVisible(is_active);
4458 }
initial.commit09911bf2008-07-26 23:55:294459}
4460
[email protected]d202a7c2012-01-04 07:53:474461void NavigationControllerImpl::LoadIfNecessary() {
Charlie Reisf4d51f402025-05-23 18:00:494462 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:034463 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4464 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294465 if (!needs_reload_)
4466 return;
4467
Bo Liucdfa4b12018-11-06 00:21:444468 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4469 needs_reload_type_);
4470
initial.commit09911bf2008-07-26 23:55:294471 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004472 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294473 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004474 if (entry_replaced_by_post_commit_error_) {
4475 // If the current entry is a post commit error, we reload the entry it
4476 // replaced instead. We leave the error entry in place until a commit
4477 // replaces it, but the pending entry points to the original entry in the
4478 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4479 // case that pending_entry_ != entries_[pending_entry_index_].
4480 // Note that this handling is similar to
4481 // `NavigationControllerImpl::Reload()`.
4482 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4483 pending_entry_index_ = GetCurrentEntryIndex();
4484 NavigateToExistingPendingEntry(
4485 ReloadType::NONE,
4486 /*initiator_rfh=*/nullptr,
4487 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494488 /*navigation_api_key=*/nullptr, actual_navigation_start);
Xinghui Lue4e50be2024-05-15 21:46:004489 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134490 NavigateToExistingPendingEntry(
4491 ReloadType::NONE,
4492 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374493 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494494 /*navigation_api_key=*/nullptr, actual_navigation_start);
Rakina Zata Amnie2d31312022-11-18 03:38:454495 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434496 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274497 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344498 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134499 NavigateToExistingPendingEntry(
4500 ReloadType::NONE,
4501 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374502 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494503 /*navigation_api_key=*/nullptr, actual_navigation_start);
avicc872d7242015-08-19 21:26:344504 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434505 // We should never navigate to an existing initial NavigationEntry that is
4506 // the initial NavigationEntry for the initial empty document that hasn't
4507 // been overridden by the synchronous about:blank commit, to preserve
4508 // legacy behavior where trying to reload when the main frame is on the
4509 // initial empty document won't result in a navigation. See also
4510 // https://crbug.com/1277414. If there is something to reload, the
4511 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4512 // it here.
avicc872d7242015-08-19 21:26:344513 needs_reload_ = false;
4514 }
initial.commit09911bf2008-07-26 23:55:294515}
4516
Kevin McNeeccca6172021-10-19 17:11:144517base::WeakPtr<NavigationHandle>
4518NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364519 RenderFrameHost* render_frame_host,
4520 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364521 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134522 RenderFrameHostImpl* rfhi =
4523 static_cast<RenderFrameHostImpl*>(render_frame_host);
Andrew Verge754c70a2025-04-17 17:19:194524 std::unique_ptr<NavigationRequest> navigation_request =
4525 CreateNavigationRequestForErrorPage(rfhi, url, error_page_html,
4526 /*is_post_commit_error_page=*/true);
4527 if (!navigation_request) {
Kevin McNeeccca6172021-10-19 17:11:144528 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114529 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584530
Rakina Zata Amni919b7922020-12-11 09:03:134531 FrameTreeNode* node = rfhi->frame_tree_node();
Charlie Reis09952ee2022-12-08 16:35:074532 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414533 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144534
Andrew Verge754c70a2025-04-17 17:19:194535 // TODO(crbug.com/406729265): LoadPostCommitErrorPage() does not initiate a
4536 // navigation via Navigator::Navigate(). We should fix that, so that
4537 // post-commit error page navigations don't bypass other important checks in
4538 // this function.
Kevin McNeeccca6172021-10-19 17:11:144539 // Calling BeginNavigation may destroy the NavigationRequest.
4540 base::WeakPtr<NavigationRequest> created_navigation_request(
4541 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414542 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144543 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414544}
4545
Andrew Verge754c70a2025-04-17 17:19:194546void NavigationControllerImpl::NavigateFrameToErrorPage(
4547 RenderFrameHostImpl* render_frame_host_impl,
4548 const GURL& url,
4549 const std::string& error_page_html) {
4550 // For now, this function can only be used for fenced frame roots. In the
4551 // future, it will be updated to work for any frame.
4552 // TODO(crbug.com/406729265): Implement this method for all types of frames,
4553 // including main frames and other subframe types.
4554 CHECK(render_frame_host_impl->IsFencedFrameRoot());
4555
4556 std::unique_ptr<NavigationRequest> navigation_request =
4557 CreateNavigationRequestForErrorPage(render_frame_host_impl, url,
4558 error_page_html,
4559 /*is_post_commit_error_page=*/false);
4560 if (!navigation_request) {
4561 return;
4562 }
4563
4564 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
4565 node->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
4566}
4567
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574568void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214569 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094570 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154571 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144572 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294573}
4574
[email protected]d202a7c2012-01-04 07:53:474575void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364576 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584577 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474578 // represent a no-committed-entry state.
4579 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364580 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584581 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474582 // if `entries_` contains pre-existing entries from the NavigationController
4583 // before restore, which would not be removed and will be at the front of the
4584 // entries list, causing the index to be off by the amount of pre-existing
4585 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294586 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294587}
[email protected]765b35502008-08-21 00:51:204588
arthursonzogni69a6a1b2019-09-17 09:23:004589void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004590 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4591}
4592
4593void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4594 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474595 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104596 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4597 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294598 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474599 return;
Michael Thiessenc5676d22019-09-25 22:32:104600 }
avi45a72532015-04-07 21:01:454601 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314602
4603 if (!delegate_)
4604 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374605 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484606}
4607
avi7c6f35e2015-05-08 17:52:384608int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4609 int nav_entry_id) const {
4610 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4611 if (entries_[i]->GetUniqueID() == nav_entry_id)
4612 return i;
4613 }
4614 return -1;
4615}
4616
[email protected]d202a7c2012-01-04 07:53:474617void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574618 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254619 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574620 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594621 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254622 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374623 // Normally, cloning a NavigationEntryImpl results in sharing
4624 // FrameNavigationEntries between the original and the clone. However, when
4625 // cloning from a different NavigationControllerImpl, we want to fork the
4626 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374627 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594628 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254629 }
Rakina Zata Amnie2d31312022-11-18 03:38:454630 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274631 DCHECK(pending_entry_index_ == -1 ||
4632 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254633}
[email protected]c5b88d82012-10-06 17:03:334634
4635void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184636 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334637 get_timestamp_callback_ = get_timestamp_callback;
4638}
[email protected]8ff00d72012-10-23 19:12:214639
Shivani Sharmaffb32b82019-04-09 16:58:474640// History manipulation intervention:
4641void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474642 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564643 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404644 bool is_renderer_initiated,
4645 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564646 // Note that for a subframe,
4647 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454648 // gesture happened in any subframe (propagated to main frame) or in the main
4649 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564650 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274651 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474652 return;
4653 }
4654 if (last_committed_entry_index_ == -1)
4655 return;
4656
Shivani Sharmac4cc8922019-04-18 03:11:174657 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474658
Alexander Timine3ec4192020-04-20 16:39:404659 // Log UKM with the URL we are navigating away from.
4660 ukm::builders::HistoryManipulationIntervention(
4661 previous_page_load_ukm_source_id)
4662 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474663}
4664
Shivani Sharmac4cc8922019-04-18 03:11:174665void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4666 int reference_index,
4667 bool skippable) {
4668 auto* reference_entry = GetEntryAtIndex(reference_index);
4669 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4670
4671 int64_t document_sequence_number =
4672 reference_entry->root_node()->frame_entry->document_sequence_number();
4673 for (int index = 0; index < GetEntryCount(); index++) {
4674 auto* entry = GetEntryAtIndex(index);
4675 if (entry->root_node()->frame_entry->document_sequence_number() ==
4676 document_sequence_number) {
4677 entry->set_should_skip_on_back_forward_ui(skippable);
4678 }
4679 }
4680}
4681
arthursonzogni66f711c2019-10-08 14:40:364682std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4683NavigationControllerImpl::ReferencePendingEntry() {
4684 DCHECK(pending_entry_);
4685 auto pending_entry_ref =
4686 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4687 pending_entry_refs_.insert(pending_entry_ref.get());
4688 return pending_entry_ref;
4689}
4690
4691void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4692 // Ignore refs that don't correspond to the current pending entry.
4693 auto it = pending_entry_refs_.find(ref);
4694 if (it == pending_entry_refs_.end())
4695 return;
4696 pending_entry_refs_.erase(it);
4697
4698 if (!pending_entry_refs_.empty())
4699 return;
4700
4701 // The pending entry may be deleted before the last PendingEntryRef.
4702 if (!pending_entry_)
4703 return;
4704
4705 // We usually clear the pending entry when the matching NavigationRequest
4706 // fails, so that an arbitrary URL isn't left visible above a committed page.
4707 //
4708 // However, we do preserve the pending entry in some cases, such as on the
4709 // initial navigation of an unmodified blank tab. We also allow the delegate
4710 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4711 // user edit the URL and try again. This may be useful in cases that the
4712 // committed page cannot be attacker-controlled. In these cases, we still
4713 // allow the view to clear the pending entry and typed URL if the user
4714 // requests (e.g., hitting Escape with focus in the address bar).
4715 //
4716 // Do not leave the pending entry visible if it has an invalid URL, since this
4717 // might be formatted in an unexpected or unsafe way.
4718 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364719 bool should_preserve_entry =
4720 (pending_entry_ == GetVisibleEntry()) &&
4721 pending_entry_->GetURL().is_valid() &&
4722 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4723 if (should_preserve_entry)
4724 return;
4725
4726 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374727 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364728}
4729
Titouan Rigoudy6ec70402021-02-02 15:42:194730std::unique_ptr<PolicyContainerPolicies>
4731NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394732 RenderFrameHostImpl* rfh,
4733 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214734 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174735 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214736 if (navigation_encountered_error) {
4737 // We should never reload the policy container of an error page from
4738 // history, see https://crbug.com/364773822.
4739 return nullptr;
4740 }
4741
Antonio Sartori78a749f2020-11-30 12:03:394742 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454743 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394744 FrameNavigationEntry* previous_frame_entry =
4745 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4746
Alison Gale770f3fc2024-04-27 00:39:584747 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394748 // ensure we always have a FrameNavigationEntry here.
4749 if (!previous_frame_entry)
4750 return nullptr;
4751
Titouan Rigoudy6ec70402021-02-02 15:42:194752 const PolicyContainerPolicies* previous_policies =
4753 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394754
Titouan Rigoudy6ec70402021-02-02 15:42:194755 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394756 return nullptr;
4757
4758 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234759 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394760 }
4761
Titouan Rigoudy72f892d2022-05-02 18:21:234762 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394763}
4764
Charlie Reis99b2eba22025-01-31 19:18:574765void NavigationControllerImpl::BroadcastHistoryIndexAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504766 OPTIONAL_TRACE_EVENT2(
Charlie Reis99b2eba22025-01-31 19:18:574767 "content", "NavigationControllerImpl::BroadcastHistoryIndexAndLength",
4768 "history_index", GetLastCommittedEntryIndex(), "history_length",
Hayato Ito2c8c08d02021-06-23 03:38:434769 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504770
Charlie Reis99b2eba22025-01-31 19:18:574771 int history_index = GetLastCommittedEntryIndex();
Kevin McNee7705fe82024-11-07 18:56:314772 int history_length = GetEntryCount();
Charlie Reis99b2eba22025-01-31 19:18:574773 auto callback = [history_index, history_length](RenderViewHostImpl* rvh) {
Kevin McNee7705fe82024-11-07 18:56:314774 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
Charlie Reis99b2eba22025-01-31 19:18:574775 broadcast->SetHistoryIndexAndLength(history_index, history_length);
Kevin McNee7705fe82024-11-07 18:56:314776 }
4777 };
Ali Hijazid87307d2022-11-07 20:15:034778 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504779}
4780
4781void NavigationControllerImpl::DidAccessInitialMainDocument() {
4782 // We may have left a failed browser-initiated navigation in the address bar
4783 // to let the user edit it and try again. Clear it now that content might
4784 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034785 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504786 DiscardPendingEntry(false);
4787
4788 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374789 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504790}
4791
4792void NavigationControllerImpl::UpdateStateForFrame(
4793 RenderFrameHostImpl* rfhi,
4794 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564795 OPTIONAL_TRACE_EVENT1("content",
4796 "NavigationControllerImpl::UpdateStateForFrame",
4797 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504798 // The state update affects the last NavigationEntry associated with the given
4799 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4800 // in the case of an UpdateState from a frame being swapped out). We track
4801 // which entry this is in the RenderFrameHost's nav_entry_id.
4802 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4803 if (!entry)
4804 return;
4805
4806 FrameNavigationEntry* frame_entry =
4807 entry->GetFrameEntry(rfhi->frame_tree_node());
4808 if (!frame_entry)
4809 return;
4810
4811 // The SiteInstance might not match if we do a cross-process navigation with
4812 // replacement (e.g., auto-subframe), in which case the swap out of the old
4813 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4814 // has already been replaced and destroyed.
4815 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4816 return;
4817
4818 if (page_state == frame_entry->page_state())
4819 return; // Nothing to update.
4820
4821 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4822
4823 // The document_sequence_number and item_sequence_number recorded in the
4824 // FrameNavigationEntry should not differ from the one coming with the update,
4825 // since it must come from the same document. Do not update it if a difference
4826 // is detected, as this indicates that |frame_entry| is not the correct one.
4827 blink::ExplodedPageState exploded_state;
4828 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4829 return;
4830
4831 if (exploded_state.top.document_sequence_number !=
4832 frame_entry->document_sequence_number() ||
4833 exploded_state.top.item_sequence_number !=
4834 frame_entry->item_sequence_number()) {
4835 return;
4836 }
4837
4838 frame_entry->SetPageState(page_state);
4839 NotifyEntryChanged(entry);
4840}
4841
Nate Chapina2c881f52023-11-07 17:02:094842namespace {
4843
4844// The caller is responsible for ensuring the entry is same-origin to the
4845// origin to be committed.
4846blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4847 FrameNavigationEntry* frame_entry,
4848 int64_t pending_document_sequence_number) {
4849 blink::ExplodedPageState exploded_state;
4850 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4851 &exploded_state)) {
4852 return nullptr;
4853 }
4854 blink::ExplodedFrameState frame_state = exploded_state.top;
4855
4856 // If the document represented by this FNE hid its full url from appearing in
4857 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4858 // in the navigation API as well (unless we're navigating to that document).
4859 std::u16string url;
4860 if (pending_document_sequence_number ==
4861 frame_entry->document_sequence_number() ||
4862 !frame_entry->protect_url_in_navigation_api()) {
4863 url = frame_state.url_string.value_or(std::u16string());
4864 }
4865
4866 return blink::mojom::NavigationApiHistoryEntry::New(
4867 frame_state.navigation_api_key.value_or(std::u16string()),
4868 frame_state.navigation_api_id.value_or(std::u16string()), url,
4869 frame_state.item_sequence_number, frame_state.document_sequence_number,
4870 frame_state.navigation_api_state);
4871}
4872
4873} // namespace
4874
Domenic Denicolacd30f5f82022-03-16 21:48:014875std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4876NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574877 Direction direction,
4878 int entry_index,
4879 const url::Origin& pending_origin,
4880 FrameTreeNode* node,
4881 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304882 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094883 int64_t pending_document_sequence_number,
4884 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014885 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454886 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174887 // Don't process the initial entry.
4888 DCHECK_EQ(GetEntryCount(), 1);
4889 return entries;
4890 }
Nate Chapind1fe3612021-04-16 20:45:574891 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304892 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574893 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4894 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094895 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574896 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414897 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574898 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014899 // An entry should only appear in the navigation API entries if it is for
4900 // the same origin as the document being committed. Check the committed
4901 // origin, or if that is not available (during restore), check against the
4902 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584903 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094904 // once we can be sure that entries with the same ISN will never be
4905 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414906 url::Origin frame_entry_origin =
4907 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4908 frame_entry->url(),
4909 frame_entry->initiator_origin().value_or(url::Origin())));
4910 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574911 break;
4912 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4913 continue;
Nate Chapina2c881f52023-11-07 17:02:094914 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4915 ToNavigationApiHistoryEntry(frame_entry,
4916 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304917 DCHECK(entry->url.empty() ||
4918 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574919 entries.push_back(std::move(entry));
4920 previous_item_sequence_number = frame_entry->item_sequence_number();
4921 }
4922 }
4923 // If |entries| was constructed by iterating backwards from
4924 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4925 // earliest-at-the-front. Reverse it.
4926 if (direction == Direction::kBack)
4927 std::reverse(entries.begin(), entries.end());
4928 return entries;
4929}
4930
Domenic Denicolacd30f5f82022-03-16 21:48:014931blink::mojom::NavigationApiHistoryEntryArraysPtr
4932NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554933 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574934 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404935 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444936 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404937 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574938
Nate Chapind1fe3612021-04-16 20:45:574939 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554940 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574941
Nate Chapine82339d02022-05-03 23:48:254942 // NOTE: |entry_index| is the index where this entry will commit if no
4943 // modifications are made between now and DidCommitNavigation. This is used to
4944 // walk |entries_| and determine which entries should be exposed by the
4945 // navigation API. It is important to calculate this correctly, because blink
4946 // will cancel a same-document history commit if it's not present in the
4947 // entries blink knows about.
4948 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574949 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304950 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254951 bool will_create_new_entry = false;
4952 if (GetPendingEntryIndex() != -1) {
4953 entry_index = GetPendingEntryIndex();
4954 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4955 pending_item_sequence_number = frame_entry->item_sequence_number();
4956 pending_document_sequence_number =
4957 frame_entry->document_sequence_number();
4958 }
4959 } else if (request &&
4960 !NavigationTypeUtils::IsReload(
4961 request->common_params().navigation_type) &&
4962 !NavigationTypeUtils::IsHistory(
4963 request->common_params().navigation_type) &&
4964 !request->common_params().should_replace_current_entry &&
4965 !request->common_params()
4966 .is_history_navigation_in_new_child_frame) {
4967 will_create_new_entry = true;
4968 entry_index = GetLastCommittedEntryIndex() + 1;
4969 // Don't set pending_item_sequence_number or
4970 // pending_document_sequence_number in this case - a new unique isn/dsn will
4971 // be calculated in the renderer later.
4972 } else if (GetLastCommittedEntryIndex() != -1) {
4973 entry_index = GetLastCommittedEntryIndex();
4974 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574975 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304976 pending_document_sequence_number =
4977 frame_entry->document_sequence_number();
4978 }
Nate Chapind1fe3612021-04-16 20:45:574979 }
4980
Domenic Denicolacd30f5f82022-03-16 21:48:014981 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254982 if (entry_index == -1) {
4983 // TODO(rakina): Exit early when there is no last committed entry.
4984 // Remove when InitialNavigationEntry ships.
4985 return entry_arrays;
4986 }
4987
Nate Chapina2c881f52023-11-07 17:02:094988 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014989 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574990 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094991 pending_item_sequence_number, pending_document_sequence_number,
4992 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574993
4994 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094995 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574996 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014997 entry_arrays->forward_entries =
4998 PopulateSingleNavigationApiHistoryEntryVector(
4999 Direction::kForward, entry_index, pending_origin, node,
5000 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:095001 pending_document_sequence_number, forwardmost_index);
5002 }
5003
5004 // If the previous entry is within the block of contiguous entries being
5005 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:255006 FrameNavigationEntry* previous_entry = nullptr;
5007 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:055008 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
5009 .initiator_frame_tree_node_id();
5010 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:255011 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
5012 previous_entry = initiator_node->frame_tree()
5013 .controller()
5014 .GetLastCommittedEntry()
5015 ->GetFrameEntry(initiator_node);
5016 }
5017 } else if (GetLastCommittedEntryIndex() != -1 &&
5018 GetLastCommittedEntryIndex() >= backmost_index &&
5019 GetLastCommittedEntryIndex() <= forwardmost_index) {
5020 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
5021 }
5022 if (previous_entry) {
5023 url::Origin previous_entry_origin =
5024 previous_entry->committed_origin().value_or(url::Origin::Resolve(
5025 previous_entry->url(),
5026 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:585027 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:255028 // once we can be sure that entries with the same ISN will never be
5029 // cross-origin.
5030 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
5031 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
5032 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:095033 }
Nate Chapind1fe3612021-04-16 20:45:575034 }
Nate Chapinc06cf80a2023-11-18 01:12:255035
Nate Chapin4e657a472022-02-06 03:38:375036 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:575037}
5038
Nate Chapinfbfe5af2021-06-10 17:22:085039NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:575040NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085041 FrameNavigationEntry* current_entry,
5042 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:575043 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:085044 if (!target_entry || !target_entry->committed_origin())
5045 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:085046 if (!current_entry->committed_origin()->IsSameOriginWith(
5047 *target_entry->committed_origin())) {
5048 return HistoryNavigationAction::kStopLooking;
5049 }
5050
5051 // NOTE: We don't actually care between kSameDocument and
5052 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:575053 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:085054 return HistoryNavigationAction::kDifferentDocument;
5055 return HistoryNavigationAction::kKeepLooking;
5056}
5057
Domenic Denicolacc094fb2022-03-16 23:40:575058void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:205059 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:375060 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:145061 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:495062 const std::string& key,
5063 base::TimeTicks actual_navigation_start) {
Nate Chapinbf682fa32022-09-26 22:41:205064 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:085065 FrameNavigationEntry* current_entry =
5066 GetLastCommittedEntry()->GetFrameEntry(node);
Nate Chapin0dbc93af2025-03-28 17:02:525067 if (!current_entry || !current_entry->committed_origin()) {
Nate Chapinfbfe5af2021-06-10 17:22:085068 return;
Nate Chapin0dbc93af2025-03-28 17:02:525069 }
Nate Chapinfbfe5af2021-06-10 17:22:085070
Alison Gale47d1537d2024-04-19 21:31:465071 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:135072 // when `navigation.traverseTo()` is called.
5073
Nate Chapinfbfe5af2021-06-10 17:22:085074 // We want to find the nearest matching entry that is contiguously
5075 // same-instance and same-origin. Check back first, then forward.
5076 // TODO(japhet): Link spec here once it exists.
5077 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:575078 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085079 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5080 if (result == HistoryNavigationAction::kStopLooking)
5081 break;
5082 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495083 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5084 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085085 return;
5086 }
5087 }
5088 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:575089 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085090 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5091 if (result == HistoryNavigationAction::kStopLooking)
5092 break;
5093 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495094 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5095 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085096 return;
5097 }
5098 }
Nate Chapinbf682fa32022-09-26 22:41:205099
5100 // If we fall through to here, a matching NavigationEntry couldn't be found.
5101 // Notify the renderer that the navigation was cancelled.
5102 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
5103 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:085104}
5105
Domenic Denicolacc094fb2022-03-16 23:40:575106bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:305107 network::mojom::ReferrerPolicy referrer_policy) {
5108 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
5109 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
5110}
5111
shivanigithubf405bf0d2021-11-05 17:58:335112bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
5113 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:315114 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:335115 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:545116 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:465117 // The preview mode appears as prerendered page in renderers, and
5118 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:035119 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:515120 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:335121 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:545122}
5123
Julie Jeongeun Kim0e242242022-11-30 10:45:095124void NavigationControllerImpl::DidChangeReferrerPolicy(
5125 FrameTreeNode* node,
5126 network::mojom::ReferrerPolicy referrer_policy) {
5127 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
5128 if (!entry)
5129 return;
5130
5131 // The FrameNavigationEntry may want to change whether to protect its url
5132 // in the navigation API when the referrer policy changes.
5133 entry->set_protect_url_in_navigation_api(
5134 ShouldProtectUrlInNavigationApi(referrer_policy));
5135}
5136
Minoru Chikamune646eba42025-04-14 01:25:035137void NavigationControllerImpl::CheckPotentialNavigationReentrancy() {
Minoru Chikamune13ab4de2025-05-14 21:54:075138 if (can_be_in_navigate_to_pending_entry_) {
Minoru Chikamune646eba42025-04-14 01:25:035139 // This DumpWithoutCrashing is an investigation code for
5140 // https://crbug.com/396998476.
5141 base::debug::DumpWithoutCrashing();
5142 }
5143}
5144
Andrew Verge754c70a2025-04-17 17:19:195145std::unique_ptr<NavigationRequest>
5146NavigationControllerImpl::CreateNavigationRequestForErrorPage(
5147 RenderFrameHostImpl* render_frame_host_impl,
5148 const GURL& url,
5149 const std::string& error_page_html,
5150 bool is_post_commit_error_page) {
5151 // Only active documents can load error pages:
5152 // - If the document is in pending deletion, the browser already committed to
5153 // destroying this RenderFrameHost so ignore loading the error page.
5154 // - If the document is in back-forward cache, it's not allowed to navigate as
5155 // it should remain frozen. Ignore the request and evict the document from
5156 // back-forward cache.
5157 // - If the document is prerendering, it can navigate but when loading error
5158 // pages, cancel prerendering.
5159 if (render_frame_host_impl->IsInactiveAndDisallowActivation(
5160 is_post_commit_error_page
5161 ? DisallowActivationReasonId::kLoadPostCommitErrorPage
5162 : DisallowActivationReasonId::kBrowserInitiatedErrorPage)) {
5163 return nullptr;
5164 }
5165
5166 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
5167
5168 blink::mojom::CommonNavigationParamsPtr common_params =
5169 blink::CreateCommonNavigationParams();
5170 // |url| might be empty, such as when this method is called before
5171 // the frame actually committed (e.g. iframe with "src" set to a
5172 // slow-responding URL). We should rewrite the URL to about:blank in this
5173 // case, as the renderer will only think a page is an error page if it has a
5174 // non-empty unreachable URL.
5175 common_params->url = url.is_empty() ? GURL("about:blank") : url;
5176
5177 // Loading an error page via LoadPostCommitErrorPage() performs a temporary
5178 // replacement of the entire NavigationEntry and swaps it back in later.
5179 // All other error page types should permanently replace the current entry.
5180 if (!is_post_commit_error_page) {
5181 common_params->should_replace_current_entry = true;
5182 }
5183
5184 blink::mojom::CommitNavigationParamsPtr commit_params =
5185 blink::CreateCommitNavigationParams();
5186 commit_params->original_url = common_params->url;
5187
5188 commit_params->navigation_timing->system_entropy_at_navigation_start =
5189 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
5190 node, blink::mojom::SystemEntropy::kNormal);
5191
5192 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
5193 // error pages.
5194 commit_params->frame_policy = node->pending_frame_policy();
5195
5196 std::unique_ptr<NavigationRequest> navigation_request =
5197 NavigationRequest::CreateBrowserInitiated(
5198 node, std::move(common_params), std::move(commit_params),
5199 false /* was_opener_suppressed */, "" /* extra_headers */,
5200 nullptr /* frame_entry */, nullptr /* entry */,
5201 false /* is_form_submission */, nullptr /* navigation_ui_data */,
5202 std::nullopt /* impression */, false /* is_pdf */);
5203 if (is_post_commit_error_page) {
5204 navigation_request->set_browser_initiated_error_navigation_type(
5205 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit);
5206 } else {
5207 navigation_request->set_browser_initiated_error_navigation_type(
5208 NavigationRequest::BrowserInitiatedErrorNavigationType::kRegular);
5209 }
5210 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
5211 navigation_request->set_error_page_html(error_page_html);
5212 return navigation_request;
5213}
5214
[email protected]8ff00d72012-10-23 19:12:215215} // namespace content