blob: 0e4bd1b98ce4128c1407ea5fc9ccc61c86d3ebcb [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"
[email protected]74ebfb12013-06-07 20:48:0052#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3753#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0054#include "base/trace_event/optional_trace_event.h"
ssid3e765612015-01-28 04:03:4255#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0856#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5957#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2858#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1859#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3960#include "content/browser/blob_storage/chrome_blob_storage_context.h"
William Liu055a3542023-04-02 17:21:1961#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3162#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4163#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0464#include "content/browser/dom_storage/session_storage_namespace_impl.h"
Nate Chapinc06cf80a2023-11-18 01:12:2565#include "content/browser/preloading/prerender/prerender_host.h"
Sharon Yang242ef822023-05-15 21:07:3266#include "content/browser/process_lock.h"
Mingyu Lei68f34412023-08-21 07:31:3767#include "content/browser/renderer_host/back_forward_cache_impl.h"
danakjc492bf82020-09-09 20:02:4468#include "content/browser/renderer_host/debug_urls.h"
69#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0070#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3371#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4472#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5773#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4474#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1975#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
76#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
Khushal Sagar94ea2dc2024-08-06 17:15:2677#include "content/browser/renderer_host/navigation_transitions/navigation_transition_config.h"
danakjc492bf82020-09-09 20:02:4478#include "content/browser/renderer_host/navigator.h"
Takashi Toyoshima4dad2c12023-11-13 10:04:4679#include "content/browser/renderer_host/page_delegate.h"
danakjc492bf82020-09-09 20:02:4480#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0081#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0782#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3283#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3384#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4285#include "content/common/content_constants_internal.h"
Rakina Zata Amni84a859df2024-06-07 15:56:3286#include "content/common/content_navigation_policy.h"
Nate Chapind1fe3612021-04-16 20:45:5787#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5188#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1189#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1990#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1191#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4692#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0093#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4794#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5895#include "content/public/browser/render_widget_host.h"
96#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1097#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3498#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1999#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:38100#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:10101#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47102#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43103#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59104#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36105#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57106#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18107#include "services/metrics/public/cpp/ukm_builders.h"
108#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17109#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37110#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44111#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58112#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39113#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30114#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21115#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06116#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43117#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50118#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31119#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51120#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46121#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26122#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29123
[email protected]8ff00d72012-10-23 19:12:21124namespace content {
[email protected]e9ba4472008-09-14 15:42:43125namespace {
126
Charlie Reis655c8f02025-05-15 01:16:17127// Feature to skip a redundant NavigationRequest creation for bfcache
128// activations, per https://crbug.com/417251428.
Charlie Reis3696ab62025-05-28 07:02:30129// TODO(crbug.com/420275259): Diagnose crashes and enable by default.
Charlie Reis655c8f02025-05-15 01:16:17130BASE_FEATURE(kSkipExtraBfcacheNavigationRequest,
131 "SkipExtraBfcacheNavigationRequest",
Charlie Reis3696ab62025-05-28 07:02:30132 base::FEATURE_DISABLED_BY_DEFAULT);
Charlie Reis655c8f02025-05-15 01:16:17133
[email protected]e9ba4472008-09-14 15:42:43134// Invoked when entries have been pruned, or removed. For example, if the
135// current entries are [google, digg, yahoo], with the current entry google,
136// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47137void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50138 int index,
[email protected]c12bf1a12008-09-17 16:28:49139 int count) {
[email protected]8ff00d72012-10-23 19:12:21140 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50141 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49142 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14143 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43144}
145
[email protected]e9ba4472008-09-14 15:42:43146// Configure all the NavigationEntries in entries for restore. This resets
147// the transition type to reload and makes sure the content state isn't empty.
148void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57149 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48150 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47151 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43152 // Use a transition type of reload so that we don't incorrectly increase
153 // the typed count.
Lei Zhang96031532019-10-10 19:05:47154 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
155 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43156 }
157}
158
[email protected]bf70edce2012-06-20 22:32:22159// Determines whether or not we should be carrying over a user agent override
160// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57161bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22162 return last_entry && last_entry->GetIsOverridingUserAgent();
163}
164
Camille Lamy5193caa2018-10-12 11:59:42165// Determines whether to override user agent for a navigation.
166bool ShouldOverrideUserAgent(
167 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57168 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42169 switch (override_user_agent) {
170 case NavigationController::UA_OVERRIDE_INHERIT:
171 return ShouldKeepOverride(last_committed_entry);
172 case NavigationController::UA_OVERRIDE_TRUE:
173 return true;
174 case NavigationController::UA_OVERRIDE_FALSE:
175 return false;
Camille Lamy5193caa2018-10-12 11:59:42176 }
Peter Boströmfc7ddc182024-10-31 19:37:21177 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42178}
179
Rakina Zata Amni312822d72021-06-04 16:13:37180// Returns true if this navigation should be treated as a reload. For e.g.
Liang Zhao0351d762024-11-13 00:10:07181// clicking on a link which results in a navigation to the last committed URL
182// (but wasn't converted to do a replacement navigation in the renderer), etc.
183// This intentionally excludes navigating to the last committed URL via the
184// address bar, so that the current scroll position is not restored.
Fergal Daly766177d2020-07-07 07:54:04185// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
186// |base_url_for_data_url|, |transition_type| correspond to the new navigation
187// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
188// navigation that committed.
189bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
190 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57191 const GURL& virtual_url,
192 const GURL& base_url_for_data_url,
193 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57194 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37195 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57196 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37197 // Navigations intended to do a replacement shouldn't be converted to do a
198 // reload.
199 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28200 return false;
clamy0a656e42018-02-06 18:18:28201 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45202 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55203 return false;
204
arthursonzogni7a8243682017-12-14 16:41:42205 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28206 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42207 return false;
208
Liang Zhao0351d762024-11-13 00:10:07209 // Same URL navigations from the address bar should only be treated as reloads
210 // if PAGE_TRANSITION_RELOAD is set (not for PAGE_TRANSITION_TYPED or
211 // PAGE_TRANSITION_LINK). In non-address-bar cases, PAGE_TRANSITION_TYPED
212 // and PAGE_TRANSITION_LINK can be treated as reloads.
clamy0a656e42018-02-06 18:18:28213 bool transition_type_can_be_converted = false;
Liang Zhao0351d762024-11-13 00:10:07214 if (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
215 if (ui::PageTransitionCoreTypeIs(transition_type,
216 ui::PAGE_TRANSITION_RELOAD)) {
217 transition_type_can_be_converted = true;
218 }
219 } else {
220 if (ui::PageTransitionCoreTypeIs(transition_type,
221 ui::PAGE_TRANSITION_TYPED) ||
222 ui::PageTransitionCoreTypeIs(transition_type,
223 ui::PAGE_TRANSITION_LINK)) {
224 transition_type_can_be_converted = true;
225 }
ananta3bdd8ae2016-12-22 17:11:55226 }
clamy0a656e42018-02-06 18:18:28227 if (!transition_type_can_be_converted)
228 return false;
229
230 // This check is required for cases like view-source:, etc. Here the URL of
231 // the navigation entry would contain the url of the page, while the virtual
232 // URL contains the full URL including the view-source prefix.
233 if (virtual_url != last_committed_entry->GetVirtualURL())
234 return false;
235
Fergal Daly766177d2020-07-07 07:54:04236 // Check that the URLs match.
237 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
238 // If there's no frame entry then by definition the URLs don't match.
239 if (!frame_entry)
240 return false;
241
242 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28243 return false;
244
245 // This check is required for Android WebView loadDataWithBaseURL. Apps
246 // can pass in anything in the base URL and we need to ensure that these
247 // match before classifying it as a reload.
248 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
249 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
250 return false;
ananta3bdd8ae2016-12-22 17:11:55251 }
252
clamy0a656e42018-02-06 18:18:28253 // Skip entries with SSL errors.
254 if (last_committed_entry->ssl_error())
255 return false;
256
257 // Don't convert to a reload when the last navigation was a POST or the new
258 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04259 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28260 return false;
261
262 return true;
ananta3bdd8ae2016-12-22 17:11:55263}
264
Arthur Sonzognic686e8f2024-01-11 08:36:37265std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12266 const mojom::DidCommitProvisionalLoadParams& params,
267 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32268 // Error pages commit in an opaque origin, yet have the real URL that resulted
269 // in an error as the |params.url|. Since successful reload of an error page
270 // should commit in the correct origin, setting the opaque origin on the
271 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17272 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37273 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32274
Arthur Sonzognic686e8f2024-01-11 08:36:37275 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32276}
277
Alex Moshchuk99242832023-05-22 17:21:44278bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42279 const GURL& virtual_url,
280 const GURL& dest_url) {
281 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44282 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
283 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42284 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
285 << virtual_url.possibly_invalid_spec();
286 return false;
287 }
288
289 // Don't attempt to navigate to non-empty invalid URLs.
290 if (!dest_url.is_valid() && !dest_url.is_empty()) {
291 LOG(WARNING) << "Refusing to load invalid URL: "
292 << dest_url.possibly_invalid_spec();
293 return false;
294 }
295
296 // The renderer will reject IPC messages with URLs longer than
297 // this limit, so don't attempt to navigate with a longer URL.
298 if (dest_url.spec().size() > url::kMaxURLChars) {
299 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
300 << " characters.";
301 return false;
302 }
303
Aaron Colwell33109c592020-04-21 21:31:19304 // Reject renderer debug URLs because they should have been handled before
305 // we get to this point. This check handles renderer debug URLs
306 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
307 // provides defense-in-depth if a renderer debug URL manages to get here via
308 // some other path. We want to reject the navigation here so it doesn't
309 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30310 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19311 LOG(WARNING) << "Refusing to load renderer debug URL: "
312 << dest_url.possibly_invalid_spec();
313 return false;
314 }
315
Alex Moshchuk99242832023-05-22 17:21:44316 // Guests only support navigations to known-safe schemes. This check already
317 // exists in the extensions layer, where it also dispatches proper events to
318 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
319 // for defense-in-depth to ensure that no other places in the codebase
320 // accidentally navigate guests to schemes such as WebUI, which is not
321 // supported. See https://crbug.com/1444221.
322 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
323 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
324 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
325 !dest_url.SchemeIs(url::kAboutScheme)) {
326 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
327 << dest_url.possibly_invalid_spec();
328 return false;
329 }
330 }
331
Camille Lamy5193caa2018-10-12 11:59:42332 return true;
333}
334
Mikel Astizba9cf2fd2017-12-17 10:38:10335// See replaced_navigation_entry_data.h for details: this information is meant
336// to ensure |*output_entry| keeps track of its original URL (landing page in
337// case of server redirects) as it gets replaced (e.g. history.replaceState()),
338// without overwriting it later, for main frames.
339void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57340 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10341 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17342 if (output_entry->GetReplacedEntryData().has_value() ||
343 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10344 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17345 }
Mikel Astizba9cf2fd2017-12-17 10:38:10346
347 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57348 data.first_committed_url = replaced_entry->GetURL();
349 data.first_timestamp = replaced_entry->GetTimestamp();
350 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29351 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10352}
353
Minggang Wangb9f3fa92021-07-01 15:30:31354blink::mojom::NavigationType GetNavigationType(
355 const GURL& old_url,
356 const GURL& new_url,
357 ReloadType reload_type,
358 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52359 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31360 bool has_pending_cross_document_commit,
361 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49362 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13363 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49364 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23365 // Reload navigations
366 switch (reload_type) {
367 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31368 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23369 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31370 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23371 case ReloadType::NONE:
372 break; // Fall through to rest of function.
373 }
374
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08375 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31376 return entry->GetHasPostData()
377 ? blink::mojom::NavigationType::RESTORE_WITH_POST
378 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23379 }
380
danakjb952ef12021-01-14 19:58:49381 const bool can_be_same_document =
382 // A pending cross-document commit means this navigation will not occur in
383 // the current document, as that document would end up being replaced in
384 // the meantime.
385 !has_pending_cross_document_commit &&
386 // If the current document is an error page, we should always treat it as
387 // a different-document navigation so that we'll attempt to load the
388 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49389 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13390 // If the navigation is an embedder-initiated navigation of a fenced
391 // frame root (i.e. enters a fenced frame tree from outside),
392 // same-document navigations should be disabled because we don't want to
393 // allow information to be joined across multiple embedder-initiated
394 // fenced frame navigations (which may contain separate cross-site data).
395 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49396 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
397 // same-document navigations should be disabled because we want to force
398 // the creation of a new browsing context group.
399 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12400
clamyea99ea12018-05-28 13:54:23401 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52402 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12403 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31404 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
405 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23406 }
407 DCHECK(!is_same_document_history_load);
408
409 // A same-document fragment-navigation happens when the only part of the url
410 // that is modified is after the '#' character.
411 //
412 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12413 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23414 //
415 // Note: this check is only valid for navigations that are not history
416 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
417 // history navigation from 'A#foo' to 'A#bar' is not a same-document
418 // navigation, but a different-document one. This is why history navigation
419 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47420 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52421 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12422
423 // The one case where we do the wrong thing here and incorrectly choose
424 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
425 // the renderer is a frameset. All frameset navigations should be
426 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
427 // navigation would do the right thing, as it would send it to the browser and
428 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
429 // into this method). But since we can't tell that case here for browser-
430 // initiated navigations, we have to get the renderer involved. In that case
431 // the navigation would be restarted due to the renderer spending a reply of
432 // mojom::CommitResult::RestartCrossDocument.
433
434 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31435 ? blink::mojom::NavigationType::SAME_DOCUMENT
436 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23437}
438
Camille Lamy5193caa2018-10-12 11:59:42439// Adjusts the original input URL if needed, to get the URL to actually load and
440// the virtual URL, which may differ.
441void RewriteUrlForNavigation(const GURL& original_url,
442 BrowserContext* browser_context,
443 GURL* url_to_load,
444 GURL* virtual_url,
445 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42446 // Allow the browser URL handler to rewrite the URL. This will, for example,
447 // remove "view-source:" from the beginning of the URL to get the URL that
448 // will actually be loaded. This real URL won't be shown to the user, just
449 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31450 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42451 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
452 url_to_load, browser_context, reverse_on_redirect);
453}
454
455#if DCHECK_IS_ON()
456// Helper sanity check function used in debug mode.
457void ValidateRequestMatchesEntry(NavigationRequest* request,
458 NavigationEntryImpl* entry) {
459 if (request->frame_tree_node()->IsMainFrame()) {
460 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
461 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31462 ui::PageTransitionFromInt(request->common_params().transition),
463 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42464 }
Nasko Oskovc36327d2019-01-03 23:23:04465 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42466 entry->should_clear_history_list());
467 DCHECK_EQ(request->common_params().has_user_gesture,
468 entry->has_user_gesture());
469 DCHECK_EQ(request->common_params().base_url_for_data_url,
470 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04471 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42472 entry->GetCanLoadLocalResources());
473 DCHECK_EQ(request->common_params().started_from_context_menu,
474 entry->has_started_from_context_menu());
475
476 FrameNavigationEntry* frame_entry =
477 entry->GetFrameEntry(request->frame_tree_node());
478 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52479 // TODO(https://crbug.com/40467594): This case should be unreachable once
480 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42481 return;
482 }
483
Camille Lamy5193caa2018-10-12 11:59:42484 DCHECK_EQ(request->common_params().method, frame_entry->method());
485
Nasko Oskovc36327d2019-01-03 23:23:04486 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42487 if (redirect_size == frame_entry->redirect_chain().size()) {
488 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04489 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42490 frame_entry->redirect_chain()[i]);
491 }
492 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21493 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42494 }
495}
496#endif // DCHECK_IS_ON()
497
Dave Tapuska8bfd84c2019-03-26 20:47:16498// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20499// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16500bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20501 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16502 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20503 DCHECK(sandboxed_initiator_rfh);
504 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
505 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16506 for (auto& item : navigations) {
507 bool within_subtree = false;
508 // Check whether this NavigationRequest affects a frame within the
509 // sandboxed frame's subtree by walking up the tree looking for the
510 // sandboxed frame.
511 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03512 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20513 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16514 within_subtree = true;
515 break;
516 }
517 }
518 if (!within_subtree)
519 return false;
520 }
521 return true;
522}
523
William Liu122754942024-01-18 22:34:39524// Used for "Navigation.SessionHistoryCount" histogram.
525enum class HistoryNavTypeForHistogram {
526 // A same-doc or cross-doc navigation of the main frame. We can only have one
527 // main frame request per `NavigationController::GoToIndex()`.
528 kMainFrame = 0,
529 // `NavigationController::GoToIndex()` creates one main frame request and
530 // one or more subframe requests.
531 kMainFrameAndSubframe,
532 // `NavigationController::GoToIndex()` creates one or more subframe requests.
533 kSubframe,
534 // Used for histogram boundary.
535 kCount
536};
537
538void CountRequests(
539 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
540 int& mutable_main_frame_cnt,
541 int& mutable_subframe_cnt) {
542 for (const auto& req : requests) {
543 if (req->IsInPrimaryMainFrame()) {
544 // We can only have one main frame navigation at a time.
545 CHECK_EQ(mutable_main_frame_cnt, 0);
546 ++mutable_main_frame_cnt;
547 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
548 ++mutable_subframe_cnt;
549 }
550 }
551}
552
553// Record the number of different types of navigations as histograms. See
554// `HistoryNavTypeForHistogram` for the types.
555void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
556 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
557 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
558 // We must have one request.
559 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
560
561 int main_frame_cnt = 0;
562 int subframe_cnt = 0;
563 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
564 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
565
566 std::optional<HistoryNavTypeForHistogram> history_nav_type;
567 if (main_frame_cnt > 0) {
568 if (subframe_cnt == 0) {
569 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
570 } else {
571 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
572 }
573 } else if (subframe_cnt > 0) {
574 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
575 }
576 if (history_nav_type.has_value()) {
577 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
578 history_nav_type.value(),
579 HistoryNavTypeForHistogram::kCount);
580 }
581}
582
[email protected]e9ba4472008-09-14 15:42:43583} // namespace
584
arthursonzogni66f711c2019-10-08 14:40:36585// NavigationControllerImpl::PendingEntryRef------------------------------------
586
587NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
588 base::WeakPtr<NavigationControllerImpl> controller)
589 : controller_(controller) {}
590
591NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
592 if (!controller_) // Can be null with interstitials.
593 return;
594
595 controller_->PendingEntryRefDeleted(this);
596}
597
Charlie Reisd3e4fef2025-05-20 02:04:17598// NavigationControllerImpl::ScopedPendingEntryReentrancyGuard------------------
599
600NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
601 ScopedPendingEntryReentrancyGuard(
602 base::SafeRef<NavigationControllerImpl> controller)
603 : controller_(controller) {
604 // Navigations that involve pending entries do not support re-entrancy.
605 // Encountering this CHECK failure means the caller is attempting to start
606 // another navigation while a navigation to an existing pending entry is on
607 // the stack. In most cases, the new navigation should be done from a posted
608 // task instead. See http://crbug.com/40353566 for context.
609 CHECK(!controller->in_navigate_to_pending_entry_);
610
611 controller->in_navigate_to_pending_entry_ = true;
612 controller->CheckPotentialNavigationReentrancy();
613
614 // It must not be possible to delete the pending NavigationEntry while
615 // navigating to it. Grab a reference to delay potential deletion until
616 // this scoped object is deleted at the end of the relevant function call.
617 pending_entry_ref_ = controller->ReferencePendingEntry();
618}
619
620NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
621 ~ScopedPendingEntryReentrancyGuard() {
622 controller_->in_navigate_to_pending_entry_ = false;
623}
624
[email protected]d202a7c2012-01-04 07:53:47625// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29626
[email protected]23a918b2014-07-15 09:51:36627const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23628
[email protected]765b35502008-08-21 00:51:20629// static
[email protected]d202a7c2012-01-04 07:53:47630size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23631 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20632
[email protected]e6fec472013-05-14 05:29:02633// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20634// when testing.
635static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29636
[email protected]71fde352011-12-29 03:29:56637// static
dcheng9bfa5162016-04-09 01:00:57638std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
639 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10640 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37641 std::optional<url::Origin> initiator_origin,
642 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10643 ui::PageTransition transition,
644 bool is_renderer_initiated,
645 const std::string& extra_headers,
646 BrowserContext* browser_context,
647 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
648 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21649 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37650 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32651 is_renderer_initiated, extra_headers, browser_context,
652 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10653}
654
655// static
656std::unique_ptr<NavigationEntryImpl>
657NavigationControllerImpl::CreateNavigationEntry(
658 const GURL& url,
659 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37660 std::optional<url::Origin> initiator_origin,
661 std::optional<GURL> initiator_base_url,
662 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57663 ui::PageTransition transition,
664 bool is_renderer_initiated,
665 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09666 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17667 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
668 bool rewrite_virtual_urls) {
669 GURL url_to_load = url;
670 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56671 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17672 if (rewrite_virtual_urls) {
673 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
674 &reverse_on_redirect);
675 }
Lukasz Anforowicz641234d52019-11-07 21:07:10676 // Let the NTP override the navigation params and pretend that this is a
677 // browser-initiated, bookmark-like navigation.
678 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32679 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21680 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10681
Patrick Monettef507e982019-06-19 20:18:06682 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28683 nullptr, // The site instance for tabs is sent on navigation
684 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21685 url_to_load, referrer, initiator_origin, initiator_base_url,
686 std::u16string(), transition, is_renderer_initiated,
687 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17688 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42689 entry->SetVirtualURL(virtual_url);
690 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56691 entry->set_update_virtual_url_with_url(reverse_on_redirect);
692 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06693 return entry;
[email protected]71fde352011-12-29 03:29:56694}
695
[email protected]cdcb1dee2012-01-04 00:46:20696// static
697void NavigationController::DisablePromptOnRepost() {
698 g_check_for_repost = false;
699}
700
[email protected]c5b88d82012-10-06 17:03:33701base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
702 base::Time t) {
703 // If |t| is between the water marks, we're in a run of duplicates
704 // or just getting out of it, so increase the high-water mark to get
705 // a time that probably hasn't been used before and return it.
706 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35707 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33708 return high_water_mark_;
709 }
710
711 // Otherwise, we're clear of the last duplicate run, so reset the
712 // water marks.
713 low_water_mark_ = high_water_mark_ = t;
714 return t;
715}
716
ckitagawa0faa5e42020-06-17 17:30:54717NavigationControllerImpl::ScopedShowRepostDialogForTesting::
718 ScopedShowRepostDialogForTesting()
719 : was_disallowed_(g_check_for_repost) {
720 g_check_for_repost = true;
721}
722
723NavigationControllerImpl::ScopedShowRepostDialogForTesting::
724 ~ScopedShowRepostDialogForTesting() {
725 g_check_for_repost = was_disallowed_;
726}
727
Nate Chapin9eb16be72022-09-23 22:54:31728NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
729 base::SafeRef<NavigationControllerImpl> controller)
730 : controller_(controller) {
731 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
732 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
733 frame_tree_node_id_to_keys_.insert(
734 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
735 if (auto* frame_entry = frame_tree_node->current_frame_host()
736 ->last_committed_frame_entry()) {
737 frame_tree_node_id_to_doc_seq_nos_.insert(
738 {frame_tree_node->frame_tree_node_id(),
739 frame_entry->document_sequence_number()});
740 }
741 }
742 PopulateKeySet(Direction::kBack);
743 PopulateKeySet(Direction::kForward);
744}
745
746void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
747 Direction direction) {
748 // Keep track of which FrameTreeNodes may still have relevant API keys in
749 // additional FrameNavigationEntries.
750 std::set<FrameTreeNode*> nodes_to_process;
751 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
752 nodes_to_process.insert(node);
753 }
754
755 const int offset = direction == Direction::kForward ? 1 : -1;
756 const int start = direction == Direction::kForward
757 ? controller_->GetLastCommittedEntryIndex()
758 : controller_->GetLastCommittedEntryIndex() - 1;
759 for (int i = start;
760 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
761 i += offset) {
762 std::set<FrameTreeNode*> nodes_to_continue_processing;
763
764 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
765 entry->ForEachFrameEntry([this, &nodes_to_process,
766 &nodes_to_continue_processing,
767 &entry](FrameNavigationEntry* frame_entry) {
768 // Find the |node| that matches |frame_entry|, if any.
769 FrameTreeNode* node = nullptr;
770 if (frame_entry == entry->root_node()->frame_entry) {
771 node = controller_->frame_tree().root();
772 } else {
773 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
774 if (it == names_to_nodes_.end())
775 return;
776 node = it->second;
777 }
778
779 // Skip this node if a previous step determine there are no longer
780 // relevant navigation API keys in this direction.
781 if (nodes_to_process.find(node) == nodes_to_process.end())
782 return;
783
784 // Stop processing |node| if we reach a point where it's cross-origin.
785 // See also PopulateSingleNavigationApiHistoryEntryVector().
786 url::Origin frame_entry_origin =
787 frame_entry->committed_origin().value_or(url::Origin::Resolve(
788 frame_entry->url(),
789 frame_entry->initiator_origin().value_or(url::Origin())));
790 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
791 return;
792
793 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
794 frame_entry->navigation_api_key());
795 // Mark |node| as needing more processing for the next entry.
796 nodes_to_continue_processing.insert(node);
797
798 // Check whether |node| went cross-document. If so, its children are
799 // no longer the same conceptual iframe as the current one, and
800 // should no longer be processed. This check is intentionally done
801 // after processing the current |node|, which may still have relevant
802 // discarded API keys.
803 if (frame_entry->document_sequence_number() !=
804 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50805 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31806 nodes_to_process.erase(descendant);
807 }
808 });
809
810 nodes_to_process.swap(nodes_to_continue_processing);
811 }
812}
813
814NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
815 std::set<std::string> all_keys;
816 // Find all remaining navigation API keys after some entries have been
817 // removed.
818 for (auto& entry : controller_->entries_) {
819 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
820 all_keys.insert(frame_entry->navigation_api_key());
821 });
822 }
823
824 // Notify each frame in the renderer of any disposed navigation API keys.
825 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
826 std::vector<std::string> disposed_keys;
827 for (const auto& key : id_to_keys.second) {
828 if (all_keys.find(key) == all_keys.end())
829 disposed_keys.push_back(key);
830 }
831 if (disposed_keys.empty())
832 continue;
833
834 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
835 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
836 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
837 }
838}
839
[email protected]d202a7c2012-01-04 07:53:47840NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00841 BrowserContext* browser_context,
842 FrameTree& frame_tree,
843 NavigationControllerDelegate* delegate)
844 : frame_tree_(frame_tree),
845 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57846 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22847 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37848 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
849 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37850 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29851}
852
[email protected]d202a7c2012-01-04 07:53:47853NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00854 // The NavigationControllerImpl might be called inside its delegate
855 // destructor. Calling it is not valid anymore.
856 delegate_ = nullptr;
857 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29858}
859
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57860BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55861 return browser_context_;
862}
863
[email protected]d202a7c2012-01-04 07:53:47864void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30865 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36866 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57867 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47868 // Note that it's possible for `entries_` to contain multiple entries at this
869 // point, as Restore() might be called on a NavigationController that is
870 // already used (e.g. due to WebView's restoreState() API), not only for fresh
871 // NavigationControllers. These entries are not cleared to preserve legacy
872 // behavior and also because `pending_entry_` might point to one of the
873 // pre-existing entries. An exception for this is when `entries_` contains
874 // only the initial NavigationEntry, which must be removed.
875
876 // Do not proceed if selected_navigation will be out of bounds for the updated
877 // entries_ list, since it will be assigned to last_committed_entry_index_ and
878 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58879 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47880 // is empty, since there should be no work to do (rather than marking the
881 // existing entries as needing reload). Also consider returning early if the
882 // selected index is -1, which represents a no-committed-entry state.
883 if (selected_navigation < -1 ||
884 selected_navigation >=
885 base::checked_cast<int>(entries->size() + entries_.size())) {
886 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24887 }
Charlie Reis23c26da2022-01-29 00:57:47888
Rakina Zata Amni46087a12022-11-11 08:28:38889 // There will always be at least one entry (new NavigationControllers will
890 // have the initial NavigationEntry).
891 if (selected_navigation == -1)
892 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47893
Rakina Zata Amni46087a12022-11-11 08:28:38894 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
895 // If we are on the initial NavigationEntry, it must be the only entry in
896 // the list. Since it's impossible to do a history navigation to the
897 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
898 // `pending_entry` might be set for a new non-history navigation).
899 // Note that we should not clear `entries_` if `entries` is empty (when
900 // InitialNavigationEntry mode is enabled), since that would leave us
901 // without any NavigationEntry.
902 CHECK_EQ(1, GetEntryCount());
903 CHECK_EQ(-1, pending_entry_index_);
904 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47905 }
[email protected]ce3fa3c2009-04-20 19:55:57906
[email protected]ce3fa3c2009-04-20 19:55:57907 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44908 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03909 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47910 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43911 if (entry->GetURL().is_empty()) {
912 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01913 // persisting the initial NavigationEntry [which is no longer possible but
914 // some old persisted sessions might still contain it] or when the
915 // serializer failed to write the URL because it's too long). Trying to
916 // restore and navigate to an entry with an empty URL will result in
917 // crashes, so change the URL to about:blank. See also
918 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43919 entry->SetURL(GURL(url::kAboutBlankURL));
920 }
dcheng36b6aec92015-12-26 06:16:36921 entries_.push_back(
922 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47923 }
avif16f85a72015-11-13 18:25:03924
925 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
926 // cleared out safely.
927 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57928
929 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36930 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57931}
932
toyoshim6142d96f2016-12-19 09:07:25933void NavigationControllerImpl::Reload(ReloadType reload_type,
934 bool check_for_repost) {
Charlie Reisf4d51f402025-05-23 18:00:49935 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:03936 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
937 (int)reload_type);
938 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
939 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28940 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28941 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32942 int current_index = -1;
943
Carlos IL42b416592019-10-07 23:10:36944 if (entry_replaced_by_post_commit_error_) {
945 // If there is an entry that was replaced by a currently active post-commit
946 // error navigation, this can't be the initial navigation.
947 DCHECK(!IsInitialNavigation());
948 // If the current entry is a post commit error, we reload the entry it
949 // replaced instead. We leave the error entry in place until a commit
950 // replaces it, but the pending entry points to the original entry in the
951 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
952 // case that pending_entry_ != entries_[pending_entry_index_].
953 entry = entry_replaced_by_post_commit_error_.get();
954 current_index = GetCurrentEntryIndex();
955 } else if (IsInitialNavigation() && pending_entry_) {
956 // If we are reloading the initial navigation, just use the current
957 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32958 entry = pending_entry_;
959 // The pending entry might be in entries_ (e.g., after a Clone), so we
960 // should also update the current_index.
961 current_index = pending_entry_index_;
962 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00963 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32964 current_index = GetCurrentEntryIndex();
965 if (current_index != -1) {
creis3da03872015-02-20 21:12:32966 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32967 }
[email protected]979a4bc2013-04-24 01:27:15968 }
[email protected]241db352013-04-22 18:04:05969
[email protected]59167c22013-06-03 18:07:32970 // If we are no where, then we can't reload. TODO(darin): We should add a
971 // CanReload method.
972 if (!entry)
973 return;
974
Rakina Zata Amnif297a802022-01-18 03:53:43975 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
976 // We should never navigate to an existing initial NavigationEntry that is
977 // the initial NavigationEntry for the initial empty document that hasn't
978 // been overridden by the synchronous about:blank commit, to preserve
979 // legacy behavior where trying to reload when the main frame is on the
980 // initial empty document won't result in a navigation. See also
981 // https://crbug.com/1277414.
982 return;
983 }
984
Aran Gilman37d11632019-10-08 23:07:15985 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30986 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07987 // they really want to do this. If they do, the dialog will call us back
988 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57989 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02990
[email protected]106a0812010-03-18 00:15:12991 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57992 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47993 return;
initial.commit09911bf2008-07-26 23:55:29994 }
Lei Zhang96031532019-10-10 19:05:47995
Wang Huia25efabc2022-09-24 17:27:22996 // Set ReloadType for |entry|.
997 entry->set_reload_type(reload_type);
998
Lei Zhang96031532019-10-10 19:05:47999 if (!IsInitialNavigation())
1000 DiscardNonCommittedEntries();
1001
1002 pending_entry_ = entry;
1003 pending_entry_index_ = current_index;
1004 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
1005
Nate Chapin45f620582021-09-30 17:45:431006 // location.reload() goes through BeginNavigation, so all reloads triggered
1007 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:131008 NavigateToExistingPendingEntry(
1009 reload_type,
1010 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371011 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491012 /*navigation_api_key=*/nullptr, actual_navigation_start);
initial.commit09911bf2008-07-26 23:55:291013}
1014
[email protected]d202a7c2012-01-04 07:53:471015void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:481016 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121017}
1018
[email protected]d202a7c2012-01-04 07:53:471019void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:491020 // If the pending reload type has been cleared by another navigation
1021 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:481022 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:491023 return;
[email protected]106a0812010-03-18 00:15:121024 }
Wang Hui96ab1012022-10-11 02:05:491025 Reload(pending_reload_, false);
1026 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121027}
1028
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571029bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:091030 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:111031}
1032
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571033bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:381034 // Check that we're on the initial NavigationEntry and that this is not a
1035 // cloned tab.
1036 return IsInitialNavigation() && GetEntryCount() == 1 &&
1037 GetLastCommittedEntry()->IsInitialEntry() &&
1038 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401039}
1040
Aran Gilman37d11632019-10-08 23:07:151041NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1042 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581043 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031044 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581045}
1046
Adithya Srinivasan9b0c99c2021-08-10 15:19:451047NavigationEntryImpl*
1048NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1049 int nav_entry_id) const {
1050 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1051 if (entry)
1052 return entry;
1053 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521054 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451055 : nullptr;
1056}
1057
W. James MacLeanc07dc41b2022-07-25 18:52:161058void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571059 const url::Origin& origin) {
1060 for (int i = 0; i < GetEntryCount(); i++) {
1061 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161062 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571063 }
1064 if (entry_replaced_by_post_commit_error_) {
1065 // It's possible we could come back to this entry if the error
1066 // page/interstitial goes away.
1067 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161068 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571069 }
W. James MacLean1c40862c2020-04-27 21:05:571070}
1071
avi25764702015-06-23 15:43:371072void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571073 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001074 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371075 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271076 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201077}
1078
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571079NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471080 if (pending_entry_)
1081 return pending_entry_;
1082 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201083}
1084
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571085NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321086 // The pending entry is safe to return for new (non-history), browser-
1087 // initiated navigations. Most renderer-initiated navigations should not
1088 // show the pending entry, to prevent URL spoof attacks.
1089 //
1090 // We make an exception for renderer-initiated navigations in new tabs, as
1091 // long as no other page has tried to access the initial empty document in
1092 // the new tab. If another page modifies this blank page, a URL spoof is
1093 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321094 bool safe_to_show_pending =
1095 pending_entry_ &&
1096 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091097 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321098 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461099 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321100
1101 // Also allow showing the pending entry for history navigations in a new tab,
1102 // such as Ctrl+Back. In this case, no existing page is visible and no one
1103 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151104 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1105 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321106 safe_to_show_pending = true;
1107
1108 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191109 return pending_entry_;
1110 return GetLastCommittedEntry();
1111}
1112
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571113int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201114 if (pending_entry_index_ != -1)
1115 return pending_entry_index_;
1116 return last_committed_entry_index_;
1117}
1118
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571119NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381120 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031121 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201122}
1123
Elad Alon32044f532025-03-04 22:16:031124const NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry()
1125 const {
1126 CHECK_NE(last_committed_entry_index_, -1);
1127 return entries_[last_committed_entry_index_].get();
1128}
1129
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571130bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351131 const std::string& mime_type = frame_tree_->root()
1132 ->current_frame_host()
1133 ->GetPage()
1134 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531135 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1136 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271137 NavigationEntry* visible_entry = GetVisibleEntry();
1138 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391139 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161140}
1141
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571142int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271143 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451144 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271145 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551146 return last_committed_entry_index_;
1147}
1148
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571149int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451150 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291151 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551152 return static_cast<int>(entries_.size());
1153}
1154
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571155NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371156 if (index < 0 || index >= GetEntryCount())
1157 return nullptr;
1158
avif16f85a72015-11-13 18:25:031159 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251160}
1161
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571162NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471163 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201164}
1165
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571166int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461167 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031168}
1169
Arthur Sonzognic686e8f2024-01-11 08:36:371170std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031171 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591172 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1173 return index;
1174 }
Shivani Sharma298d12852019-01-22 20:04:031175 }
Arthur Sonzognic686e8f2024-01-11 08:36:371176 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591177}
1178
1179bool NavigationControllerImpl::CanGoBack() {
1180 return GetIndexForGoBack().has_value();
1181}
1182
Arthur Sonzognic686e8f2024-01-11 08:36:371183std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591184 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1185 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1186 return index;
1187 }
1188 }
Arthur Sonzognic686e8f2024-01-11 08:36:371189 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201190}
1191
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571192bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591193 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201194}
1195
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571196bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031197 int index = GetIndexForOffset(offset);
1198 return index >= 0 && index < GetEntryCount();
1199}
1200
Xiaohan Wang7f8052e02022-01-14 18:44:281201#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151202bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151203 if (offset == 0)
1204 return true;
1205 int increment = offset > 0 ? 1 : -1;
1206 int non_skippable_entries = 0;
1207 for (int index = GetIndexForOffset(increment);
1208 index >= 0 && index < GetEntryCount(); index += increment) {
1209 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1210 non_skippable_entries++;
1211
1212 if (non_skippable_entries == std::abs(offset))
1213 return true;
1214 }
1215 return false;
1216}
1217#endif
1218
David Bokanb8e0df02025-05-14 22:03:481219NavigationController::WeakNavigationHandleVector
1220NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371221 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061222
Kevin McNeeedc481c2023-04-27 22:30:581223 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211224
David Bokanb8e0df02025-05-14 22:03:481225 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201226}
1227
David Bokanb8e0df02025-05-14 22:03:481228NavigationController::WeakNavigationHandleVector
1229NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161230 // Note that at least one entry (the last one) will be non-skippable since
1231 // entries are marked skippable only when they add another entry because of
1232 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371233 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591234
Kevin McNeeedc481c2023-04-27 22:30:581235 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591236
David Bokanb8e0df02025-05-14 22:03:481237 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201238}
1239
David Bokanb8e0df02025-05-14 22:03:481240NavigationController::WeakNavigationHandleVector
1241NavigationControllerImpl::GoToIndex(int index) {
1242 std::vector<base::WeakPtr<NavigationRequest>> requests =
1243 GoToIndex(index, /*initiator_rfh=*/nullptr,
1244 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491245 /*navigation_api_key=*/nullptr,
1246 /*actual_navigation_start=*/base::TimeTicks::Now());
David Bokanb8e0df02025-05-14 22:03:481247 std::vector<base::WeakPtr<NavigationHandle>> handles;
1248 std::ranges::move(requests, std::back_inserter(handles));
1249 return handles;
Dave Tapuska8bfd84c2019-03-26 20:47:161250}
1251
William Liu62ae26c2024-08-08 14:28:161252std::vector<base::WeakPtr<NavigationRequest>>
1253NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201254 int index,
1255 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371256 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131257 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491258 const std::string* navigation_api_key,
1259 base::TimeTicks actual_navigation_start) {
sunjian30574a62017-03-21 21:39:441260 TRACE_EVENT0("browser,navigation,benchmark",
1261 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501262 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1263 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1264 entries_.size());
1265 // Indices should have have been validated by the caller.
1266 CHECK_GE(index, 0);
1267 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201268
Rakina Zata Amnif297a802022-01-18 03:53:431269 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1270 // We should never navigate to an existing initial NavigationEntry that is
1271 // the initial NavigationEntry for the initial empty document that hasn't
1272 // been overridden by the synchronous about:blank commit, to preserve
1273 // legacy behavior where trying to reload when the main frame is on the
1274 // initial empty document won't result in a navigation. See also
1275 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161276 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431277 }
1278
[email protected]cbab76d2008-10-13 22:42:471279 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201280
arthursonzogni5c4c202d2017-04-25 23:41:271281 DCHECK_EQ(nullptr, pending_entry_);
1282 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431283
arthursonzogni5c4c202d2017-04-25 23:41:271284 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201285 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271286 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1287 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Charlie Reisf4d51f402025-05-23 18:00:491288 return NavigateToExistingPendingEntry(
1289 ReloadType::NONE, initiator_rfh, soft_navigation_heuristics_task_id,
1290 navigation_api_key, actual_navigation_start);
[email protected]765b35502008-08-21 00:51:201291}
1292
[email protected]d202a7c2012-01-04 07:53:471293void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121294 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031295 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201296 return;
1297
[email protected]9ba14052012-06-22 23:50:031298 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201299}
1300
Nate Chapinbf682fa32022-09-26 22:41:201301void NavigationControllerImpl::GoToOffsetFromRenderer(
1302 int offset,
Yoav Weiss8c573952022-11-17 17:35:131303 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371304 std::optional<blink::scheduler::TaskAttributionId>
Charlie Reisf4d51f402025-05-23 18:00:491305 soft_navigation_heuristics_task_id,
1306 base::TimeTicks actual_navigation_start) {
Nate Chapinbb74c5a52023-07-21 23:13:351307 // Note: This is actually reached in unit tests.
1308 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431309 return;
1310
Nate Chapinbf682fa32022-09-26 22:41:201311 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131312 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491313 /*navigation_api_key=*/nullptr, actual_navigation_start);
Nate Chapin45f620582021-09-30 17:45:431314}
1315
William Liu62ae26c2024-08-08 14:28:161316std::vector<base::WeakPtr<NavigationRequest>>
1317NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271318 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1319 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491320 /*navigation_api_key=*/nullptr,
1321 /*actual_navigation_start=*/base::TimeTicks::Now());
William Liuec04e382024-05-23 18:03:271322}
1323
Xiaohan Wang7f8052e02022-01-14 18:44:281324#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151325void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1326 // Note: This is actually reached in unit tests.
1327 if (!CanGoToOffsetWithSkipping(offset))
1328 return;
1329
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421330 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151331 GoToIndex(GetIndexForOffset(offset));
1332 return;
1333 }
1334 int increment = offset > 0 ? 1 : -1;
1335 // Find the offset without counting skippable entries.
1336 int target_index = GetIndexForOffset(increment);
1337 int non_skippable_entries = 0;
1338 for (int index = target_index; index >= 0 && index < GetEntryCount();
1339 index += increment) {
1340 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1341 non_skippable_entries++;
1342
1343 if (non_skippable_entries == std::abs(offset)) {
1344 target_index = index;
1345 break;
1346 }
1347 }
1348
1349 GoToIndex(target_index);
1350}
1351#endif
1352
[email protected]41374f12013-07-24 02:49:281353bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151354 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281355 return false;
[email protected]6a13a6c2011-12-20 21:47:121356
[email protected]43032342011-03-21 14:10:311357 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281358 return true;
[email protected]cbab76d2008-10-13 22:42:471359}
1360
Michael Thiessen9b14d512019-09-23 21:19:471361void NavigationControllerImpl::PruneForwardEntries() {
1362 DiscardNonCommittedEntries();
1363 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471364 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471365 if (num_removed <= 0)
1366 return;
Nate Chapin9eb16be72022-09-23 22:54:311367 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471368 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1369 NotifyPrunedEntries(this, remove_start_index /* start index */,
1370 num_removed /* count */);
1371}
1372
Aran Gilman37d11632019-10-08 23:07:151373void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1374 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321375 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311376 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511377 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1378 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321379 }
1380}
1381
Harkiran Bolariaba823e42021-05-21 18:30:361382base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1383 const GURL& url,
1384 const Referrer& referrer,
1385 ui::PageTransition transition,
1386 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471387 LoadURLParams params(url);
1388 params.referrer = referrer;
1389 params.transition_type = transition;
1390 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361391 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471392}
1393
Harkiran Bolariaba823e42021-05-21 18:30:361394base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1395 const LoadURLParams& params) {
Charlie Reisf4d51f402025-05-23 18:00:491396 // For now, treat this as the actual navigation start time, even though a fair
1397 // amount of work is done in the browser process between the various ways to
1398 // start a navigation and reaching here (e.g., sending OpenURLParams through
1399 // the embedder and converting them to LoadURLParams). Note that this may be
1400 // used for some renderer-initiated navigations that go through
1401 // RenderFrameHostImpl::OpenURL as well.
1402 // TODO(crbug.com/385170155): Consider whether tracking this earlier work with
1403 // an earlier start time is worthwhile for metrics.
1404 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
1405
Lukasz Anforowicz435bcb582019-07-12 20:50:061406 if (params.is_renderer_initiated)
1407 DCHECK(params.initiator_origin.has_value());
1408
naskob8744d22014-08-28 17:07:431409 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151410 "NavigationControllerImpl::LoadURLWithParams", "url",
1411 params.url.possibly_invalid_spec());
Emmanuel Arias Soto9e159652025-05-16 07:53:551412
1413 if (IsDebugURL(params.url)) {
1414 // Browser-debug URLs won't go through NavigationThrottles so we have to
1415 // check them explicitly. See crbug.com/40605746.
1416 ContentBrowserClient* client = GetContentClient()->browser();
1417 if (client->ShouldBlockRendererDebugURL(
1418 params.url, browser_context_,
1419 GetTargetFrameTreeNodeForNavigation(params)
1420 ->current_frame_host())) {
1421 DiscardPendingEntry(false);
1422 return nullptr;
1423 }
1424 HandleDebugURL(params.url, params.transition_type,
1425 client->IsExplicitNavigation(params.transition_type));
[email protected]47752982014-07-29 08:01:431426 // If Telemetry is running, allow the URL load to proceed as if it's
1427 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491428 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181429 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361430 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181431 }
[email protected]47752982014-07-29 08:01:431432 }
[email protected]8bf1048012012-02-08 01:22:181433
[email protected]cf002332012-08-14 19:17:471434 // Checks based on params.load_type.
1435 switch (params.load_type) {
1436 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431437 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541438#if BUILDFLAG(IS_ANDROID)
1439 case LOAD_TYPE_PDF_ANDROID:
1440#endif
[email protected]cf002332012-08-14 19:17:471441 break;
1442 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261443 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211444 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471445 }
1446 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461447 }
[email protected]e47ae9472011-10-13 19:48:341448
[email protected]e47ae9472011-10-13 19:48:341449 // The user initiated a load, we don't need to reload anymore.
1450 needs_reload_ = false;
1451
Charlie Reisf4d51f402025-05-23 18:00:491452 return NavigateWithoutEntry(params, actual_navigation_start);
[email protected]132e281a2012-07-31 18:32:441453}
1454
Charlie Reis4c53a962023-06-21 23:17:531455void NavigationControllerImpl::LoadOriginalRequestURL() {
1456 // If the original request URL is not valid, matches the current URL, or
1457 // involves POST data, then simply reload. The POST check avoids issues with
1458 // sending data to the wrong page.
1459 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1460 const GURL& original_request_url =
1461 GetLastCommittedEntry()->GetOriginalRequestURL();
1462 if (!original_request_url.is_valid() ||
1463 original_request_url == last_committed_url ||
1464 GetLastCommittedEntry()->GetHasPostData()) {
1465 Reload(ReloadType::NORMAL, true);
1466 return;
1467 }
1468
1469 // Otherwise, attempt to load the original request URL without any of the
1470 // other data from the current NavigationEntry, replacing the current entry.
1471 // Loading the original URL is useful in cases such as modifying the user
1472 // agent.
1473 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1474 std::make_unique<NavigationController::LoadURLParams>(
1475 original_request_url);
1476 load_params->should_replace_current_entry = true;
1477 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1478 LoadURLWithParams(*load_params.get());
1479}
1480
Mohamed Abdelhalim833de902019-09-16 17:41:451481bool NavigationControllerImpl::PendingEntryMatchesRequest(
1482 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191483 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451484 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191485}
1486
[email protected]d202a7c2012-01-04 07:53:471487bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321488 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071489 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331490 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441491 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251492 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561493 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131494 NavigationRequest* navigation_request) {
1495 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331496
1497 // Note: validation checks and renderer kills due to invalid commit messages
1498 // must happen before getting here, in
1499 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1500 // effects of the navigation have already occurred.
1501
[email protected]cd2e15742013-03-08 04:08:311502 is_initial_navigation_ = false;
1503
Wang Hui96ab1012022-10-11 02:05:491504 // Any pending request to repost a form submission is no longer valid, since a
1505 // different NavigationEntry is committing.
1506 pending_reload_ = ReloadType::NONE;
1507
[email protected]0e8db942008-09-24 21:21:481508 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431509 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451510 if (entry_replaced_by_post_commit_error_) {
1511 // Same document navigation events with a post-commit error should already
1512 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1513 // reaching here.
1514 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331515
Xinghui Lub9e86a352024-05-17 16:29:421516 if (pending_entry_) {
1517 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1518 // `pending_entry_` isn't pointing to the last committed entry.
1519 // Instead, all reload approaches (e.g., in `Reload` and
1520 // `LoadIfNecessary`) should attempt to load the
1521 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1522 // entry itself.
1523 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1524 << "Incorrectly reloading the post commit error page entry.";
1525 }
Xinghui Lue4e50be2024-05-15 21:46:001526
Rakina Zata Amnie2d31312022-11-18 03:38:451527 // Any commit while a post-commit error page is showing should put the
1528 // original entry back, replacing the error page's entry. This includes
1529 // reloads, where the original entry was used as the pending entry and
1530 // should now be at the correct index at commit time.
1531 entries_[last_committed_entry_index_] =
1532 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481533 }
Rakina Zata Amnie2d31312022-11-18 03:38:451534 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1535 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001536 // Must honor user agent overrides in the |navigation_request|, such as
1537 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1538 // result, besides comparing |pending_entry_|'s user agent against
1539 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1540 // agent against LastCommittedEntry's.
1541 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541542 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1543 (PendingEntryMatchesRequest(navigation_request) &&
1544 pending_entry_->GetIsOverridingUserAgent() !=
1545 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001546 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451547 }
[email protected]ecd9d8702008-08-28 22:10:171548
Dave Tapuskaa2ab4f252021-07-08 21:31:281549 bool is_main_frame_navigation = !rfh->GetParent();
1550
Alexander Timind2f2e4f22019-04-02 20:04:531551 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1552 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281553 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141554 // BackForwardCacheMetrics to be associated with the new navigation's
1555 // NavigationEntry, by either creating a new object or reusing the previous
1556 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281557 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211558 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141559 back_forward_cache_metrics = BackForwardCacheMetrics::
1560 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281561 GetLastCommittedEntry(), is_main_frame_navigation,
1562 params.document_sequence_number);
1563 }
Yuzu Saijo29f96ca92022-12-08 04:54:121564
Alexander Timind2f2e4f22019-04-02 20:04:531565 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281566 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451567 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1568 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531569 }
1570 }
1571
Rakina Zata Amnifd8370b2022-11-14 13:32:251572 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1573 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091574 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251575 details->did_replace_entry =
1576 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091577
fdegans9caf66a2015-07-30 21:10:421578 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111579 // except for restored entries. This should be true even if the current commit
1580 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291581 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481582 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081583 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111584
1585 // Only make changes based on the pending entry if the NavigationRequest
1586 // matches it. Otherwise, the pending entry may be for a different request
1587 // (e.g., if a slow history navigation is pending while an auto-subframe
1588 // commit occurs).
1589 if (PendingEntryMatchesRequest(navigation_request)) {
1590 // It is no longer necessary to consider the pending entry as restored.
1591 if (pending_entry_->IsRestored()) {
1592 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1593 was_restored = true;
1594 }
[email protected]e9ba4472008-09-14 15:42:431595
Charlie Reisf8cde712022-10-20 16:25:091596 // If the SiteInstance has changed from the matching pending entry, this
1597 // must be treated as a new navigation with replacement. Set the replacement
1598 // bit here and ClassifyNavigation will identify this case and return
1599 // NEW_ENTRY.
1600 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1601 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1602 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251603 // TODO(nasko,creis,rakina): Move this to happen before committing the
1604 // navigation. This is a bit complicated because we don't currently
1605 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091606 details->did_replace_entry = true;
1607 }
Nasko Oskovaee2f862018-06-15 00:05:521608 }
[email protected]bcd904482012-02-01 01:54:221609
[email protected]e9ba4472008-09-14 15:42:431610 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101611 NavigationType navigation_type =
1612 ClassifyNavigation(rfh, params, navigation_request);
1613 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451614
Rakina Zata Amnie2d31312022-11-18 03:38:451615 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451616 // Ensure that this navigation does not add a navigation entry, since
1617 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1618 // beyond the last committed one. Therefore, `should_replace_current_entry`
1619 // should be set, which replaces the current entry, or this should be a
1620 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251621 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331622 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451623 }
1624
Rakina Zata Amnie2d31312022-11-18 03:38:451625 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551626 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241627 // This is a subframe navigation on the initial empty document, which used
1628 // to not have a NavigationEntry to attach to. Now it can attach to the
1629 // initial NavigationEntry, and we must ensure that its NavigationEntry
1630 // will keep the "initial NavigationEntry" status and won't append a new
1631 // NavigationEntry (it should always do replacement instead).
1632 // See also https://crbug.com/1277414.
1633 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551634 // Subframe navigation on initial NavigationEntry must not append a new
1635 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1636 // means every subframe navigation that happens while we're on the initial
1637 // NavigationEntry will always reuse the existing NavigationEntry and
1638 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101639 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1640 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551641 // This is a navigation that modifies the initial NavigationEntry, either
1642 // for a replacement or a reload. The initial NavigationEntry should
1643 // retain its "initial NavigationEntry" status in this case.
1644 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241645 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251646 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1647 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241648 // This is a synchronous about:blank navigation on the main frame, which
1649 // used to not create a NavigationEntry when we have no NavigationEntry on
1650 // FrameTree creation. We now have the initial NavigationEntry and are on
1651 // the initial NavigationEntry. To preserve old behavior, we should still
1652 // keep the "initial" status for the new NavigationEntry that we will
1653 // create for this navigation, so that subframe navigations under the
1654 // synchronously committed about:blank document will never append new
1655 // NavigationEntry, and instead will just reuse the initial
1656 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1657 // See also https://crbug.com/1277414.
1658 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551659 }
1660 }
1661 DCHECK(!details->should_stay_as_initial_entry ||
1662 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201663
eugenebutee08663a2017-04-27 17:43:121664 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441665 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121666
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071667 details->is_prerender_activation =
1668 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241669 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1670 ->GetOutermostMainFrame()
1671 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071672
Peter Boströmd7592132019-01-30 04:50:311673 // Make sure we do not discard the pending entry for a different ongoing
1674 // navigation when a same document commit comes in unexpectedly from the
1675 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1676 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581677 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061678 bool keep_pending_entry =
1679 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101680 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061681 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311682
Miyoung Shin3299cbf2022-11-22 01:41:101683 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061684 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491685 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051686 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561687 previous_document_had_history_intervention_activation,
1688 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431689 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061690 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491691 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1692 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001693 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431694 break;
[email protected]8ff00d72012-10-23 19:12:211695 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471696 RendererDidNavigateNewSubframe(
1697 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561698 previous_document_had_history_intervention_activation,
1699 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431700 break;
[email protected]8ff00d72012-10-23 19:12:211701 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391702 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251703 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001704 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081705 // We don't send a notification about auto-subframe PageState during
1706 // UpdateStateForFrame, since it looks like nothing has changed. Send
1707 // it here at commit time instead.
1708 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431709 return false;
creis59d5a47cb2016-08-24 23:57:191710 }
[email protected]e9ba4472008-09-14 15:42:431711 break;
Aran Gilman37d11632019-10-08 23:07:151712 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211713 NOTREACHED();
[email protected]765b35502008-08-21 00:51:201714 }
1715
[email protected]688aa65c62012-09-28 04:32:221716 // At this point, we know that the navigation has just completed, so
1717 // record the time.
1718 //
1719 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261720 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331721 base::Time timestamp =
1722 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1723 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131724 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221725
Peter Boströmd7592132019-01-30 04:50:311726 // If we aren't keeping the pending entry, there shouldn't be one at this
1727 // point. Clear it again in case any error cases above forgot to do so.
1728 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1729 // been cleared instead of protecting against it.
1730 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551731 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141732
[email protected]e9ba4472008-09-14 15:42:431733 // All committed entries should have nonempty content state so WebKit doesn't
1734 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471735 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321736 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221737 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441738 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141739
Alexander Timind2f2e4f22019-04-02 20:04:531740 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1741 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281742 if (back_forward_cache_metrics &&
1743 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531744 active_entry->set_back_forward_cache_metrics(
1745 std::move(back_forward_cache_metrics));
1746 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281747
1748 // `back_forward_cache_metrics()` may return null as we do not record
1749 // back-forward cache metrics for navigations in non-primary frame trees.
1750 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581751 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141752 // These are both only available from details at this point, so we capture
1753 // them here.
1754 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101755 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141756 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1757 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281758 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1759 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321760 IsBackForwardCacheEnabled() &&
1761 rfh->delegate()->IsBackForwardCacheSupported() &&
1762 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281763 }
naskoc7533512016-05-06 17:01:121764
Charles Reisc0507202017-09-21 00:40:021765 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1766 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1767 // A mismatch can occur if the renderer lies or due to a unique name collision
1768 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121769 FrameNavigationEntry* frame_entry =
1770 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021771 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1772 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031773 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081774 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1775 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031776 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201777
1778 // Remember the bindings the renderer process has at this point, so that
1779 // we do not grant this entry additional bindings if we come back to it.
1780 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301781 }
[email protected]132e281a2012-07-31 18:32:441782
[email protected]97d8f0d2013-10-29 16:49:211783 // Once it is committed, we no longer need to track several pieces of state on
1784 // the entry.
naskoc7533512016-05-06 17:01:121785 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131786
[email protected]49bd30e62011-03-22 20:12:591787 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221788 // TODO(creis): This check won't pass for subframes until we create entries
1789 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001790 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421791 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591792
[email protected]e9ba4472008-09-14 15:42:431793 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001794 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001795 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311796 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531797
arthursonzogni7ddc6542021-04-09 09:16:501798 active_entry->SetIsOverridingUserAgent(
1799 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031800
[email protected]93f230e02011-06-01 14:40:001801 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291802
aelias100c9192017-01-13 00:01:431803 if (overriding_user_agent_changed)
1804 delegate_->UpdateOverridingUserAgent();
1805
creis03b48002015-11-04 00:54:561806 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1807 // one knows the latest NavigationEntry it is showing (whether it has
1808 // committed anything in this navigation or not). This allows things like
1809 // state and title updates from RenderFrames to apply to the latest relevant
1810 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381811 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031812 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381813 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431814
1815 if (navigation_request->IsPrerenderedPageActivation()) {
Charlie Reis99b2eba22025-01-31 19:18:571816 BroadcastHistoryIndexAndLength();
Alison Gale47d1537d2024-04-19 21:31:461817 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431818 // is activated. As a result, a "prerenderingchange" event listener sees the
1819 // history.length which is not updated yet. We should guarantee that
Charlie Reis99b2eba22025-01-31 19:18:571820 // history's length and index should be updated before a
Hayato Ito2c8c08d02021-06-23 03:38:431821 // "prerenderingchange" event listener runs. One possible approach is to use
1822 // the same IPC which "prerenderingchange" uses, and propagate history's
Charlie Reis99b2eba22025-01-31 19:18:571823 // length and index together with that.
Hayato Ito2c8c08d02021-06-23 03:38:431824 }
1825
[email protected]e9ba4472008-09-14 15:42:431826 return true;
initial.commit09911bf2008-07-26 23:55:291827}
1828
[email protected]8ff00d72012-10-23 19:12:211829NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321830 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101831 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241832 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591833 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511834 "ClassifyNavigation");
1835
avi7c6f35e2015-05-08 17:52:381836 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241837 // A new entry. We may or may not have a corresponding pending entry, and
1838 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001839 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491840 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061841 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381842 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241843 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511844 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381845 return NAVIGATION_TYPE_NEW_SUBFRAME;
1846 }
1847
Charlie Reisc0f17d2d2021-01-12 18:52:491848 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381849 DCHECK(!params.history_list_was_cleared);
1850
avi39c1edd32015-06-04 20:06:001851 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381852 // All manual subframes would be did_create_new_entry and handled above, so
1853 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081854 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1855 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381856 }
1857
Rakina Zata Amnif6950d552020-11-24 03:26:101858 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1859 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381860 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1861 // create a new page.
1862
Hayato Ito2ae49442021-07-02 02:59:251863 // This main frame navigation is not a history navigation (since
1864 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1865 // reload or a replacement navigation, which will modify the existing entry.
1866 //
Nasko Oskov332593c2018-08-16 17:21:341867 // TODO(nasko): With error page isolation, reloading an existing session
1868 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491869 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341870 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511871 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491872 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061873 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381874 }
1875
Charlie Reisf8cde712022-10-20 16:25:091876 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521877 // If the SiteInstance of the |pending_entry_| does not match the
1878 // SiteInstance that got committed, treat this as a new navigation with
1879 // replacement. This can happen if back/forward/reload encounters a server
1880 // redirect to a different site or an isolated error page gets successfully
1881 // reloaded into a different SiteInstance.
1882 if (pending_entry_->site_instance() &&
1883 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491884 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061885 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521886 }
creis77c9aa32015-09-25 19:59:421887
Nasko Oskovaee2f862018-06-15 00:05:521888 if (pending_entry_index_ == -1) {
1889 // In this case, we have a pending entry for a load of a new URL but Blink
1890 // didn't do a new navigation (params.did_create_new_entry). First check
1891 // to make sure Blink didn't treat a new cross-process navigation as
1892 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161893 // we must treat it as NEW rather than the converted reload case below,
1894 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451895 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161896 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061897 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521898 }
1899
1900 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161901 // We will create a pending entry, but NavigateWithoutEntry will convert
1902 // it to a reload since it's the same page and not create a new entry for
1903 // it. (The user doesn't want to have a new back/forward entry when they
1904 // do this.) Therefore we want to just ignore the pending entry and go
1905 // back to where we were (the "existing entry").
1906 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061907 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521908 }
avi7c6f35e2015-05-08 17:52:381909 }
1910
Rakina Zata Amni153d5702021-09-13 22:48:001911 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381912 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491913 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1914 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161915 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061916 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381917 }
1918
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121919 if (navigation_request->DidEncounterError() &&
1920 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101921 nav_entry_id == failed_pending_entry_id_) {
Charlie Reisb5f39cf2024-11-12 16:55:011922 // If the renderer was going to a pending entry that got cleared because of
1923 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511924 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491925 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061926 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381927 }
1928
Charlie Reisc0f17d2d2021-01-12 18:52:491929 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101930 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511931 trace_return.traced_value()->SetInteger("existing_entry_index",
1932 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381933 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441934 // The renderer has committed a navigation to an entry that no longer
1935 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491936 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061937 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381938 }
1939
avi7c6f35e2015-05-08 17:52:381940 // Since we weeded out "new" navigations above, we know this is an existing
1941 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491942 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061943 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381944}
1945
Rakina Zata Amni3460d382021-10-29 00:43:371946void NavigationControllerImpl::UpdateNavigationEntryDetails(
1947 NavigationEntryImpl* entry,
1948 RenderFrameHostImpl* rfh,
1949 const mojom::DidCommitProvisionalLoadParams& params,
1950 NavigationRequest* request,
1951 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001952 bool is_new_entry,
1953 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371954 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171955 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371956 entry->AddOrUpdateFrameEntry(
1957 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571958 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371959 rfh->GetSiteInstance(), nullptr, params.url,
1960 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171961 Referrer(*params.referrer),
1962 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371963 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171964 request ? request->GetRedirectChain() : redirects, params.page_state,
1965 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371966 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171967 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211968 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171969 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371970
1971 if (rfh->GetParent()) {
1972 // Only modify the NavigationEntry for main frame navigations.
1973 return;
1974 }
1975 if (entry->update_virtual_url_with_url())
1976 UpdateVirtualURLToURL(entry, params.url);
1977 // Don't use the page type from the pending entry. Some interstitial page
1978 // may have set the type to interstitial. Once we commit, however, the page
1979 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171980 entry->set_page_type((request && request->DidEncounterError())
1981 ? PAGE_TYPE_ERROR
1982 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431983 if (commit_details && commit_details->should_stay_as_initial_entry) {
1984 // Retain the "initial NavigationEntry" status.
1985 if (request->IsSameDocument()) {
1986 // If this is for a same-document navigation, the NavigationEntry must be
1987 // reused and should already be marked as the initial NavigationEntry.
1988 DCHECK(entry->IsInitialEntry());
1989 } else {
1990 // If this is for a cross-document navigation, it can be caused by a
1991 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1992 // "for synchronous about:blank" in the latter case, and also when it is
1993 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1994 // is not for a synchronous about:blank commit.
1995 NavigationEntryImpl::InitialNavigationEntryState new_state =
1996 NavigationEntryImpl::InitialNavigationEntryState::
1997 kInitialNotForSynchronousAboutBlank;
1998 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1999 request->is_synchronous_renderer_commit()) {
2000 new_state = NavigationEntryImpl::InitialNavigationEntryState::
2001 kInitialForSynchronousAboutBlank;
2002 }
2003 entry->set_initial_navigation_entry_state(new_state);
2004 }
2005 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
2006 // Remove the "initial NavigationEntry" status.
2007 entry->set_initial_navigation_entry_state(
2008 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:002009 }
Rakina Zata Amniddf10502022-01-15 02:56:552010
Rakina Zata Amni3460d382021-10-29 00:43:372011 if (is_new_entry) {
2012 // Some properties of the NavigationEntry are only set when the entry is
2013 // new (we aren't reusing it).
2014 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:172015 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:402016 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:012017 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
2018 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:372019 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
2020 } else {
2021 // We are reusing the NavigationEntry. The site instance will normally be
2022 // the same except for a few cases:
2023 // 1) session restore, when no site instance will be assigned or
2024 // 2) redirect, when the site instance is reset.
2025 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
2026 entry->site_instance() == rfh->GetSiteInstance());
2027 }
2028}
2029
Rakina Zata Amniafd3c6582021-11-30 06:19:172030void NavigationControllerImpl::CreateInitialEntry() {
2031 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:032032 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:172033 auto params = mojom::DidCommitProvisionalLoadParams::New();
2034 // The initial NavigationEntry's URL is the empty URL. This preserves the old
2035 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
2036 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:402037 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:172038 params->http_status_code = 0;
2039 params->url_is_unreachable = false;
2040 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:172041 params->post_id = -1;
2042 params->embedding_token = base::UnguessableToken::Create();
2043 params->navigation_token = base::UnguessableToken::Create();
2044 params->did_create_new_entry = true;
2045 params->origin = rfh->GetLastCommittedOrigin();
2046 params->should_update_history = true;
2047 params->item_sequence_number = 0;
2048 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:152049 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:172050 params->transition = is_in_fenced_frame_tree
2051 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
2052 : ui::PAGE_TRANSITION_LINK;
2053 params->referrer = blink::mojom::Referrer::New();
2054
Rakina Zata Amniafd3c6582021-11-30 06:19:172055 auto new_entry = std::make_unique<NavigationEntryImpl>(
2056 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:382057 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:212058 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
2059 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
2060 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172061 UpdateNavigationEntryDetails(
2062 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:002063 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
2064 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172065
2066 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
2067 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:002068 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172069}
2070
Charlie Reisc0f17d2d2021-01-12 18:52:492071void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:322072 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072073 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362074 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442075 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562076 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002077 NavigationRequest* request,
2078 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572079 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372080 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452081 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372082 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522083 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2084 initiator_base_url = request->common_params().initiator_base_url;
2085 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062086
creisf49dfc92016-07-26 17:05:182087 // First check if this is an in-page navigation. If so, clone the current
2088 // entry instead of looking at the pending entry, because the pending entry
2089 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452090 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302091 FrameNavigationEntry* previous_frame_entry =
2092 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452093 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482094 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572095 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082096 rfh->GetSiteInstance(), nullptr, params.url,
2097 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212098 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092099 request->GetRedirectChain(), params.page_state, params.method,
2100 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392101 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302102 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572103 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302104 // FrameNavigationEntry.
2105 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572106 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032107
creisf49dfc92016-07-26 17:05:182108 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032109 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522110 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2111 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572112 // TODO(jam): we had one report of this with a URL that was redirecting to
2113 // only tildes. Until we understand that better, don't copy the cert in
2114 // this case.
2115 new_entry->GetSSL() = SSLStatus();
2116 }
creisf49dfc92016-07-26 17:05:182117
Patrick Monette50e8bd82019-06-13 22:40:452118 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2119 // that |frame_entry| should now have a reference count of exactly 2: one
2120 // due to the local variable |frame_entry|, and another due to |new_entry|
2121 // also retaining one. This should never fail, because it's the main frame.
2122 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182123 }
2124
Harkiran Bolaria59290d62021-03-17 01:53:012125 // If this is an activation navigation from a prerendered page, transfer the
2126 // new entry from an entry already created and stored in the
2127 // NavigationRequest. |new_entry| will not have been set prior to this as
2128 // |is_same_document| is mutually exclusive with
2129 // |IsPrerenderedPageActivation|.
2130 if (request->IsPrerenderedPageActivation()) {
2131 DCHECK(!is_same_document);
2132 DCHECK(!new_entry);
2133 new_entry = request->TakePrerenderNavigationEntry();
2134 DCHECK(new_entry);
2135 }
2136
Charlie Reisc0f17d2d2021-01-12 18:52:492137 // Only make a copy of the pending entry if it is appropriate for the new
2138 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452139 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042140 // 1. The SiteInstance hasn't been assigned to something else.
2141 // 2. The pending entry was intended as a new entry, rather than being a
2142 // history navigation that was interrupted by an unrelated,
2143 // renderer-initiated navigation.
2144 // TODO(csharrison): Investigate whether we can remove some of the coarser
2145 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452146 if (!new_entry && PendingEntryMatchesRequest(request) &&
2147 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342148 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432149 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352150 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432151
Camille Lamy62b826012019-02-26 09:15:472152 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452153 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182154 }
2155
Charlie Reisc0f17d2d2021-01-12 18:52:492156 // For cross-document commits with no matching pending entry, create a new
2157 // entry.
creisf49dfc92016-07-26 17:05:182158 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062159 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072160 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212161 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582162 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452163 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172164 nullptr, // blob_url_loader_factory
2165 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242166
2167 // Find out whether the new entry needs to update its virtual URL on URL
2168 // change and set up the entry accordingly. This is needed to correctly
2169 // update the virtual URL when replaceState is called after a pushState.
2170 GURL url = params.url;
2171 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492172 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412173 // update the virtual URL based on the new URL. For example, this is needed
2174 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2175 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372176 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2177 &url, browser_context_, &needs_update);
2178 new_entry->set_update_virtual_url_with_url(needs_update);
2179
Camille Lamy62b826012019-02-26 09:15:472180 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452181 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432182 }
2183
Alison Gale770f3fc2024-04-27 00:39:582184 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2185 // set for prerendered contents, if any. This is because
2186 // prerendering/activation technically won't be creating a new document.
2187 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2188 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012189 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372190 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2191 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002192 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082193
Harkiran Bolaria59290d62021-03-17 01:53:012194 // history.pushState() is classified as a navigation to a new page, but sets
2195 // is_same_document to true. In this case, we already have the title and
2196 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452197 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012198 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2199 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2200 }
[email protected]3a868f212014-08-09 10:41:192201 }
[email protected]ff64b3e2014-05-31 04:07:332202
[email protected]60d6cca2013-04-30 08:47:132203 DCHECK(!params.history_list_was_cleared || !replace_entry);
2204 // The browser requested to clear the session history when it initiated the
2205 // navigation. Now we know that the renderer has updated its state accordingly
2206 // and it is safe to also clear the browser side history.
2207 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552208 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132209 entries_.clear();
2210 last_committed_entry_index_ = -1;
2211 }
2212
Nasko Oskovaee2f862018-06-15 00:05:522213 // If this is a new navigation with replacement and there is a
2214 // pending_entry_ which matches the navigation reported by the renderer
2215 // process, then it should be the one replaced, so update the
2216 // last_committed_entry_index_ to use it.
2217 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092218 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522219 last_committed_entry_index_ = pending_entry_index_;
2220 }
2221
Alexander Timine3ec4192020-04-20 16:39:402222 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562223 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402224 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052225
Yuzu Saijoa725585f2022-11-28 04:14:032226 // If this is a history navigation and the old entry has an existing
2227 // back/forward cache metrics object, keep using the old one so that the
2228 // reasons logged from the last time the page navigated gets preserved.
2229 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2230 request)) {
2231 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2232 // because some tests do not have a pending entry.
2233 NavigationEntryImpl* entry =
2234 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2235 if (entry && entry->back_forward_cache_metrics()) {
2236 scoped_refptr<BackForwardCacheMetrics> metrics =
2237 entry->TakeBackForwardCacheMetrics();
2238 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2239 }
2240 }
2241
Andrew Verge754c70a2025-04-17 17:19:192242 bool was_post_commit_error =
2243 request->browser_initiated_error_navigation_type() ==
2244 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit;
2245
Carlos IL42b416592019-10-07 23:10:362246 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Andrew Verge754c70a2025-04-17 17:19:192247 was_post_commit_error, rfh->IsNestedWithinFencedFrame(),
2248 commit_details);
[email protected]e9ba4472008-09-14 15:42:432249}
2250
Charlie Reisc0f17d2d2021-01-12 18:52:492251void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322252 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072253 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362254 bool is_same_document,
jam48cea9082017-02-15 06:13:292255 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452256 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002257 bool keep_pending_entry,
2258 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562259 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2260 << "that a last committed entry exists.";
2261
[email protected]e9ba4472008-09-14 15:42:432262 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002263 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432264
Charlie Reis7e2cb6d2021-01-26 01:27:162265 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002266 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162267 // We're guaranteed to have a last committed entry if intended_as_new_entry
2268 // is true.
avicbdc4c12015-07-01 16:07:112269 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162270
2271 // If the NavigationRequest matches a new pending entry and is classified as
2272 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2273 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092274 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162275 // Note: The pending entry will usually have a real ReloadType here, but
2276 // it can still be ReloadType::NONE in cases that
2277 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2278
2279 // If we classified this correctly, the SiteInstance should not have
2280 // changed.
2281 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2282
2283 // For converted reloads, we assign the entry's unique ID to be that of
2284 // the new one. Since this is always the result of a user action, we want
2285 // to dismiss infobars, etc. like a regular user-initiated navigation.
2286 entry->set_unique_id(pending_entry_->GetUniqueID());
2287
2288 // The extra headers may have changed due to reloading with different
2289 // headers.
2290 entry->set_extra_headers(pending_entry_->extra_headers());
2291 }
2292 // Otherwise, this was intended as a new entry but the pending entry was
2293 // lost in the meantime and no new entry was created. We are stuck at the
2294 // last committed entry.
2295
2296 // Even if this is a converted reload from pressing enter in the omnibox,
2297 // the server could redirect, requiring an update to the SSL status. If this
2298 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452299 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162300 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472301 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452302 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162303 }
Rakina Zata Amnif6950d552020-11-24 03:26:102304 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112305 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102306 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162307
eugenebut604866f2017-05-10 21:35:362308 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452309 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362310 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2311 // this was a restored same document navigation entry, then it won't have
2312 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2313 // navigated it.
jam48cea9082017-02-15 06:13:292314 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522315 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2316 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292317 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2318 was_restored) {
2319 entry->GetSSL() = last_entry->GetSSL();
2320 }
2321 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452322 // In rapid back/forward navigations |request| sometimes won't have a cert
2323 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192324 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452325 if (request->GetSSLInfo().has_value() &&
2326 request->GetSSLInfo()->is_valid()) {
2327 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522328 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2329 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192330 entry->GetSSL() = SSLStatus();
2331 }
jam48cea9082017-02-15 06:13:292332 }
avicbdc4c12015-07-01 16:07:112333 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272334 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572335 // navigations that are EXISTING_ENTRY are same-document navigations that
2336 // result in replacement (e.g. history.replaceState(), location.replace(),
2337 // forced replacements for trivial session history contexts). For these
2338 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112339 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102340
Alison Gale81f4f2c72024-04-22 19:33:312341 // TODO(crbug.com/40532777): Set page transition type to
2342 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2343 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2344 // well as to fix the inconsistency with what we report to observers
2345 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102346
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572347 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102348
eugenebut604866f2017-05-10 21:35:362349 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452350 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362351 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472352 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452353 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112354 }
2355 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432356
Rakina Zata Amni3460d382021-10-29 00:43:372357 UpdateNavigationEntryDetails(entry, rfh, params, request,
2358 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002359 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302360
[email protected]5ccd4dc2012-10-24 02:28:142361 // The redirected to page should not inherit the favicon from the previous
2362 // page.
eugenebut604866f2017-05-10 21:35:362363 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482364 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142365
Charlie Reis951f43372023-05-05 00:30:072366 // Update the last committed index to reflect the committed entry. Do this
2367 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2368 // delegate sees the correct committed index when notified of navigation
2369 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2370 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212371 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072372
Peter Boströmd7592132019-01-30 04:50:312373 // We should also usually discard the pending entry if it corresponds to a
2374 // different navigation, since that one is now likely canceled. In rare
2375 // cases, we leave the pending entry for another navigation in place when we
2376 // know it is still ongoing, to avoid a flicker in the omnibox (see
2377 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432378 //
2379 // Note that we need to use the "internal" version since we don't want to
2380 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312381 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002382 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432383}
2384
[email protected]d202a7c2012-01-04 07:53:472385void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322386 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072387 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362388 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472389 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562390 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002391 NavigationRequest* request,
2392 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262393 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2394 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552395 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2396 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112397
[email protected]e9ba4472008-09-14 15:42:432398 // Manual subframe navigations just get the current entry cloned so the user
2399 // can go back or forward to it. The actual subframe information will be
2400 // stored in the page state for each of those entries. This happens out of
2401 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092402 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2403 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382404
Mikel Astizba9cf2fd2017-12-17 10:38:102405 // The DCHECK below documents the fact that we don't know of any situation
2406 // where |replace_entry| is true for subframe navigations. This simplifies
2407 // reasoning about the replacement struct for subframes (see
2408 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2409 DCHECK(!replace_entry);
2410
Patrick Monette50e8bd82019-06-13 22:40:452411 // This FrameNavigationEntry might not end up being used in the
2412 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372413 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452414 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372415 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522416 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2417 initiator_base_url = request->common_params().initiator_base_url;
2418 }
Nate Chapin63db0d12022-01-20 22:03:302419 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2420 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212421 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302422 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572423 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302424 if (is_same_document) {
2425 FrameNavigationEntry* previous_frame_entry =
2426 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572427 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302428 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572429 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302430 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572431 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302432 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572433 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302434 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572435 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302436 policy_container_policies->referrer_policy);
2437 }
2438
Patrick Monette50e8bd82019-06-13 22:40:452439 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482440 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572441 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082442 rfh->GetSiteInstance(), nullptr, params.url,
2443 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212444 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2445 request->GetRedirectChain(), params.page_state, params.method,
2446 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572447 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032448
creisce0ef3572017-01-26 17:53:082449 std::unique_ptr<NavigationEntryImpl> new_entry =
2450 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452451 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032452 frame_tree_->root());
creise062d542015-08-25 02:01:552453
Alexander Timine3ec4192020-04-20 16:39:402454 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562455 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402456 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472457
creisce0ef3572017-01-26 17:53:082458 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452459 // to replace, which can happen due to a unique name change. See
2460 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2461 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382462
Dave Tapuska87696ae2021-11-18 18:48:312463 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152464 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432465}
2466
[email protected]d202a7c2012-01-04 07:53:472467bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322468 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072469 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392470 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252471 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002472 NavigationRequest* request,
2473 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292474 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2475 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2476
[email protected]e9ba4472008-09-14 15:42:432477 // We're guaranteed to have a previously committed entry, and we now need to
2478 // handle navigation inside of a subframe in it without creating a new entry.
2479 DCHECK(GetLastCommittedEntry());
2480
creis913c63ce2016-07-16 19:52:522481 // For newly created subframes, we don't need to send a commit notification.
2482 // This is only necessary for history navigations in subframes.
2483 bool send_commit_notification = false;
2484
Rakina Zata Amnif6950d552020-11-24 03:26:102485 // If |nav_entry_id| is non-zero and matches an existing entry, this
2486 // is a history navigation. Update the last committed index accordingly. If
2487 // we don't recognize the |nav_entry_id|, it might be a recently
2488 // pruned entry. We'll handle it below.
2489 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2490 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472491 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062492 // Make sure that a subframe commit isn't changing the main frame's
2493 // origin. Otherwise the renderer process may be confused, leading to a
2494 // URL spoof. We can't check the path since that may change
2495 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572496 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2497 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242498 // We should use checks similar to RenderFrameHostImpl's
2499 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2500 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572501 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2502 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2503 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2504 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522505 current_top_url.DeprecatedGetOriginAsURL() !=
2506 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442507 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512508 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062509 }
creis3cdc3b02015-05-29 23:00:472510
creis913c63ce2016-07-16 19:52:522511 // We only need to discard the pending entry in this history navigation
2512 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062513 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002514 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522515
2516 // History navigations should send a commit notification.
2517 send_commit_notification = true;
avi98405c22015-05-21 20:47:062518 }
[email protected]e9ba4472008-09-14 15:42:432519 }
[email protected]f233e4232013-02-23 00:55:142520
creisce0ef3572017-01-26 17:53:082521 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2522 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372523 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2524 // exists), or we may want to clobber it and create a new one. We update in
2525 // cases where the corresponding FrameNavigationEntry is conceptually similar
2526 // to the document described by the commit params: same-document
2527 // navigations, history traversal to an existing entry, and reloads (including
2528 // a "soft reload" where we navigate to the same url without flagging it as a
2529 // reload). But in the case of a different document that is not logically
2530 // related to the committed FrameNavigationEntry's document (cross-document,
2531 // not same url, not a reload, not a history traversal), we replace rather
2532 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252533 //
Nate Chapin9f169072021-06-09 19:32:372534 // In the case where we update, the FrameNavigationEntry will potentially be
2535 // shared across multiple NavigationEntries, and any updates will be reflected
2536 // in all of those NavigationEntries. In the replace case, any existing
2537 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252538 //
2539 // When navigating away from the initial empty document, we also update rather
2540 // than replace. Either update or replace will overwrite the initial empty
2541 // document state for |last_committed|, but if the FrameNavigationEntry for
2542 // the initial empty document is shared across multiple NavigationEntries (due
2543 // to a navigation in another frame), we want to make sure we overwrite the
2544 // initial empty document state everywhere this FrameNavigationEntry is used,
2545 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452546 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372547 FrameNavigationEntry* last_committed_frame_entry =
2548 last_committed->GetFrameEntry(rfh->frame_tree_node());
2549 NavigationEntryImpl::UpdatePolicy update_policy =
2550 NavigationEntryImpl::UpdatePolicy::kUpdate;
2551 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312552 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372553 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252554 last_committed_frame_entry->url() != params.url &&
2555 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372556 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2557 }
2558
Rakina Zata Amni3460d382021-10-29 00:43:372559 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002560 update_policy, false /* is_new_entry */,
2561 commit_details);
creis625a0c7d2015-03-24 23:17:122562
creis913c63ce2016-07-16 19:52:522563 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432564}
2565
[email protected]d202a7c2012-01-04 07:53:472566int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232567 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032568 for (size_t i = 0; i < entries_.size(); ++i) {
2569 if (entries_[i].get() == entry)
2570 return i;
2571 }
2572 return -1;
[email protected]765b35502008-08-21 00:51:202573}
2574
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572575void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242576 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572577 NavigationControllerImpl* source =
2578 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572579 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382580 DCHECK_EQ(1, GetEntryCount());
2581 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472582 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172583 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572584
Francois Dorayeaace782017-06-21 16:37:242585 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442586 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572587 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572588
Fergal Dalya1d569972021-03-16 03:24:532589 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302590 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532591 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2592 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302593 }
[email protected]4e6419c2010-01-15 04:50:342594
Lukasz Anforowicz0de0f452020-12-02 19:57:152595 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572596}
2597
[email protected]79368982013-11-13 01:11:012598bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022599 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162600 if (last_committed_entry_index_ == -1)
2601 return false;
[email protected]9350602e2013-02-26 23:27:442602
[email protected]474f8512013-05-31 22:31:162603 // We cannot prune if there is a pending entry at an existing entry index.
2604 // It may not commit, so we have to keep the last committed entry, and thus
2605 // there is no sensible place to keep the pending entry. It is ok to have
2606 // a new pending entry, which can optionally commit as a new navigation.
2607 if (pending_entry_index_ != -1)
2608 return false;
2609
[email protected]474f8512013-05-31 22:31:162610 return true;
2611}
2612
[email protected]79368982013-11-13 01:11:012613void NavigationControllerImpl::PruneAllButLastCommitted() {
2614 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162615
avi2b177592014-12-10 02:08:022616 DCHECK_EQ(0, last_committed_entry_index_);
2617 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442618
Charlie Reis99b2eba22025-01-31 19:18:572619 BroadcastHistoryIndexAndLength();
[email protected]9350602e2013-02-26 23:27:442620}
2621
[email protected]79368982013-11-13 01:11:012622void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162623 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012624 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262625
Nate Chapin9eb16be72022-09-23 22:54:312626 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2627
[email protected]474f8512013-05-31 22:31:162628 // Erase all entries but the last committed entry. There may still be a
2629 // new pending entry after this.
2630 entries_.erase(entries_.begin(),
2631 entries_.begin() + last_committed_entry_index_);
2632 entries_.erase(entries_.begin() + 1, entries_.end());
2633 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262634}
2635
Christian Dullweber1af31e62018-02-22 11:49:482636void NavigationControllerImpl::DeleteNavigationEntries(
2637 const DeletionPredicate& deletionPredicate) {
2638 // It is up to callers to check the invariants before calling this.
2639 CHECK(CanPruneAllButLastCommitted());
2640 std::vector<int> delete_indices;
2641 for (size_t i = 0; i < entries_.size(); i++) {
2642 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572643 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482644 delete_indices.push_back(i);
2645 }
2646 }
2647 if (delete_indices.empty())
2648 return;
2649
2650 if (delete_indices.size() == GetEntryCount() - 1U) {
2651 PruneAllButLastCommitted();
2652 } else {
2653 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382654 for (const auto& index : base::Reversed(delete_indices)) {
2655 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482656 }
Charlie Reis99b2eba22025-01-31 19:18:572657 BroadcastHistoryIndexAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482658 }
2659 delegate()->NotifyNavigationEntriesDeleted();
2660}
2661
Carlos Caballero35ce710c2019-09-19 10:59:452662BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2663 return back_forward_cache_;
2664}
2665
William Liu055a3542023-04-02 17:21:192666NavigationEntryScreenshotCache*
2667NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212668 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262669 if (!nav_entry_screenshot_cache_ &&
2670 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192671 nav_entry_screenshot_cache_ =
2672 std::make_unique<NavigationEntryScreenshotCache>(
2673 BrowserContextImpl::From(browser_context_)
2674 ->GetNavigationEntryScreenshotManager()
2675 ->GetSafeRef(),
2676 this);
2677 }
2678 return nav_entry_screenshot_cache_.get();
2679}
2680
clamy987a3752018-05-03 17:36:262681void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2682 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2683 // progress, since this will cause a use-after-free. (We only allow this
2684 // when the tab is being destroyed for shutdown, since it won't return to
2685 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032686 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
Minoru Chikamune13ab4de2025-05-14 21:54:072687 // If `was_failure` is true, it means that the pending entry was discarded by
2688 // a `PendingEntryRefDeleted` call within `OnRequestFailedInternal`, in
2689 // response to a navigation request failure. This case is not at risk for
2690 // re-entrancy when `can_be_in_navigate_to_pending_entry_` is true, because
2691 // that code also creates another `PendingEntryRef` that would prevent the
2692 // `DiscardPendingEntry` call if the PostTask were skipped. See
2693 // https://crbug.com/411855273.
2694 if (!was_failure && can_be_in_navigate_to_pending_entry_ &&
Minoru Chikamune646eba42025-04-14 01:25:032695 !frame_tree_->IsBeingDestroyed()) {
2696 CheckPotentialNavigationReentrancy();
2697 }
clamy987a3752018-05-03 17:36:262698
2699 if (was_failure && pending_entry_) {
2700 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2701 } else {
2702 failed_pending_entry_id_ = 0;
2703 }
2704
2705 if (pending_entry_) {
2706 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332707 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262708 pending_entry_index_ = -1;
2709 pending_entry_ = nullptr;
2710 }
arthursonzogni66f711c2019-10-08 14:40:362711
2712 // Ensure any refs to the current pending entry are ignored if they get
2713 // deleted, by clearing the set of known refs. All future pending entries will
2714 // only be affected by new refs.
2715 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262716}
2717
2718void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2719 if (pending_entry_)
2720 pending_entry_->set_ssl_error(error);
2721}
2722
Xiaohan Wang7f8052e02022-01-14 18:44:282723#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422724// static
2725bool NavigationControllerImpl::ValidateDataURLAsString(
2726 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2727 if (!data_url_as_string)
2728 return false;
2729
2730 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2731 return false;
2732
2733 // The number of characters that is enough for validating a data: URI.
2734 // From the GURL's POV, the only important part here is scheme, it doesn't
2735 // check the actual content. Thus we can take only the prefix of the url, to
2736 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562737 constexpr size_t kDataUriPrefixMaxLen = 64;
2738 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2739 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422740 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2741 return false;
2742
2743 return true;
2744}
2745#endif
2746
Shivani Sharma194877032019-03-07 17:52:472747void NavigationControllerImpl::NotifyUserActivation() {
2748 // When a user activation occurs, ensure that all adjacent entries for the
2749 // same document clear their skippable bit, so that the history manipulation
2750 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012751 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172752 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012753 // If the value of CanGoBack changes as a result of making some entries
2754 // non-skippable, then we must let the delegate know to update its UI state.
2755 // See https://crbug.com/1477784.
2756 if (!can_go_back && CanGoBack()) {
2757 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2758 }
Shivani Sharma194877032019-03-07 17:52:472759}
2760
clamy987a3752018-05-03 17:36:262761bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2762 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332763 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2764 blink::LocalFrameToken initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492765 int initiator_process_id,
2766 base::TimeTicks actual_navigation_start) {
clamy987a3752018-05-03 17:36:262767 NavigationEntryImpl* entry =
2768 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2769 if (!entry)
2770 return false;
2771
2772 FrameNavigationEntry* frame_entry =
2773 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2774 if (!frame_entry)
2775 return false;
2776
Camille Lamy5193caa2018-10-12 11:59:422777 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572778 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232779 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332780 true /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492781 initiator_process_id, actual_navigation_start);
clamyea99ea12018-05-28 13:54:232782
2783 if (!request)
2784 return false;
2785
arthursonzognif046d4a2019-12-12 19:08:102786 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412787
Rakina Zata Amni1c83b082023-02-08 01:09:002788 SCOPED_CRASH_KEY_STRING256(
2789 "Bug1400009", "req_url",
2790 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2791 SCOPED_CRASH_KEY_NUMBER(
2792 "Bug1400009", "nav_entry_si",
2793 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2794 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2795 frame_entry->site_instance()
2796 ? ((int)frame_entry->site_instance()->GetId())
2797 : -1);
2798 bool has_sig =
2799 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2800 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2801 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2802 has_sig ? (!!frame_tree_->GetRenderViewHost(
2803 frame_entry->site_instance()->group()))
2804 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052805 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2806 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232807
2808 return true;
clamy987a3752018-05-03 17:36:262809}
2810
Tsuyoshi Horo52fd08e2020-07-07 07:03:452811bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
Charlie Reisf4d51f402025-05-23 18:00:492812 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Tsuyoshi Horo52fd08e2020-07-07 07:03:452813 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2814 if (!entry)
2815 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432816
2817 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2818 // We should never navigate to an existing initial NavigationEntry that is
2819 // the initial NavigationEntry for the initial empty document that hasn't
2820 // been overridden by the synchronous about:blank commit, to preserve
2821 // legacy behavior where trying to reload when the main frame is on the
2822 // initial empty document won't result in a navigation. See also
2823 // https://crbug.com/1277414.
2824 return false;
2825 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452826 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2827 if (!frame_entry)
2828 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142829 ReloadType reload_type = ReloadType::NORMAL;
2830 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452831 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142832 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452833 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432834 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372835 std::nullopt /* initiator_frame_token */,
Charlie Reisf4d51f402025-05-23 18:00:492836 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
2837 actual_navigation_start);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452838 if (!request)
2839 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052840 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452841 return true;
2842}
2843
clamy987a3752018-05-03 17:36:262844void NavigationControllerImpl::NavigateFromFrameProxy(
2845 RenderFrameHostImpl* render_frame_host,
2846 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022847 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452848 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372849 const std::optional<url::Origin>& initiator_origin,
2850 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262851 bool is_renderer_initiated,
2852 SiteInstance* source_site_instance,
2853 const Referrer& referrer,
2854 ui::PageTransition page_transition,
2855 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252856 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262857 const std::string& method,
2858 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092859 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142860 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212861 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502862 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372863 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292864 blink::mojom::NavigationInitiatorActivationAndAdStatus
2865 initiator_activation_and_ad_status,
Charlie Reise1d9b8182025-04-02 04:32:122866 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:222867 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492868 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462869 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452870 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582871 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032872 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342873 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372874 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582875 if (is_renderer_initiated)
2876 DCHECK(initiator_origin.has_value());
2877
clamy987a3752018-05-03 17:36:262878 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582879
Rakina Zata Amni2322f4f82022-01-24 13:24:242880 // Don't allow an entry replacement if there is no entry to replace.
2881 // http://crbug.com/457149
2882 if (GetEntryCount() == 0)
2883 should_replace_current_entry = false;
2884
clamy987a3752018-05-03 17:36:262885 // Create a NavigationEntry for the transfer, without making it the pending
2886 // entry. Subframe transfers should have a clone of the last committed entry
2887 // with a FrameNavigationEntry for the target frame. Main frame transfers
2888 // should have a new NavigationEntry.
2889 // TODO(creis): Make this unnecessary by creating (and validating) the params
2890 // directly, passing them to the destination RenderFrameHost. See
2891 // https://crbug.com/536906.
2892 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262893 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262894 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452895 DCHECK(GetLastCommittedEntry());
2896 entry = GetLastCommittedEntry()->Clone();
2897 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172898 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2899 // Renderer-initiated navigation that target a remote frame are currently
2900 // classified as browser-initiated when this one has already navigated.
2901 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372902 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2903 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2904 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2905 // same-document navigation), they will still be present in the
2906 // committed NavigationEntry that will be referenced to construct the new
2907 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262908 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082909 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582910 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372911 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212912 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152913 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262914 } else {
2915 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172916 // If `node` is the outermost main frame, it rewrites a virtual url in order
2917 // to adjust the original input url if needed. For inner frames such as
2918 // fenced frames or subframes, they don't rewrite urls as the urls are not
2919 // input urls by users.
2920 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372921 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322922 if (source_site_instance && source_site_instance->HasProcess()) {
2923 source_process_site_url =
2924 source_site_instance->GetProcess()->GetProcessLock().site_url();
2925 }
clamy987a3752018-05-03 17:36:262926 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212927 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322928 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212929 extra_headers, browser_context_, blob_url_loader_factory,
2930 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262931 entry->root_node()->frame_entry->set_source_site_instance(
2932 static_cast<SiteInstanceImpl*>(source_site_instance));
2933 entry->root_node()->frame_entry->set_method(method);
2934 }
clamy987a3752018-05-03 17:36:262935
Camille Lamy5193caa2018-10-12 11:59:422936 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452937 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262938 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422939 override_user_agent = true;
clamy987a3752018-05-03 17:36:262940 }
2941 // TODO(creis): Set user gesture and intent received timestamp on Android.
2942
2943 // We may not have successfully added the FrameNavigationEntry to |entry|
2944 // above (per https://crbug.com/608402), in which case we create it from
2945 // scratch. This works because we do not depend on |frame_entry| being inside
2946 // |entry| during NavigateToEntry. This will go away when we shortcut this
2947 // further in https://crbug.com/536906.
2948 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2949 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452950 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082951 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582952 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372953 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212954 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152955 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572956 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262957 }
2958
Camille Lamy5193caa2018-10-12 11:59:422959 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022960 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452961 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292962 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212963 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422964 params.source_site_instance = source_site_instance;
2965 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2966 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032967 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422968 params.referrer = referrer;
2969 /* params.redirect_chain: skip */
2970 params.extra_headers = extra_headers;
2971 params.is_renderer_initiated = is_renderer_initiated;
2972 params.override_user_agent = UA_OVERRIDE_INHERIT;
2973 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542974 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422975 /* params.data_url_as_string: skip */
2976 params.post_data = post_body;
2977 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582978 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422979 /* params.frame_name: skip */
2980 // TODO(clamy): See if user gesture should be propagated to this function.
2981 params.has_user_gesture = false;
2982 params.should_clear_history_list = false;
2983 params.started_from_context_menu = false;
2984 /* params.navigation_ui_data: skip */
2985 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222986 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542987 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212988 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412989 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502990 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292991 params.initiator_activation_and_ad_status =
2992 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032993 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422994
2995 std::unique_ptr<NavigationRequest> request =
2996 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032997 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142998 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392999 ReloadType::NONE, entry.get(), frame_entry.get(),
Charlie Reise1d9b8182025-04-02 04:32:123000 actual_navigation_start_time, navigation_start_time,
3001 is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583002 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343003 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:233004
3005 if (!request)
3006 return;
3007
Garrett Tanzerbb8db412022-09-27 21:59:463008 // Force the navigation to take place in a new browsing instance.
3009 // This is used by _unfencedTop in fenced frames to ensure that navigations
3010 // leaving the fenced context create a new browsing instance.
3011 if (force_new_browsing_instance) {
3012 request->coop_status().ForceBrowsingInstanceSwap();
3013 }
3014
Arthur Hemery948742762019-09-18 10:06:243015 // At this stage we are proceeding with this navigation. If this was renderer
3016 // initiated with user gesture, we need to make sure we clear up potential
3017 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
3018 DiscardNonCommittedEntries();
3019
Lukasz Anforowicz9ee83c272020-12-01 20:14:053020 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:263021}
3022
[email protected]d1198fd2012-08-13 22:50:193023void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253024 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:213025 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:193026 if (!session_storage_namespace)
3027 return;
3028
3029 // We can't overwrite an existing SessionStorage without violating spec.
3030 // Attempts to do so may give a tab access to another tab's session storage
3031 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:153032 bool successful_insert =
3033 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:253034 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:053035 static_cast<SessionStorageNamespaceImpl*>(
3036 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:303037 .second;
3038 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:193039}
3040
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573041bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:453042 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:033043 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:463044}
3045
Aran Gilman37d11632019-10-08 23:07:153046SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253047 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:303048 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:253049 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:033050 DOMStorageContextWrapper* context_wrapper =
3051 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
3052
3053 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:253054 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:033055 if (it != session_storage_namespace_map_.end()) {
3056 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:153057 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
3058 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:473059
michaelnbacbcbd2016-02-09 00:32:033060 return it->second.get();
3061 }
3062
3063 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:103064 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
3065 SessionStorageNamespaceImpl::Create(context_wrapper);
3066 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
3067 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:253068 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:103069 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:303070
Daniel Murphy31bbb8b12018-02-07 21:44:103071 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:303072}
3073
3074SessionStorageNamespace*
3075NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:253076 return GetSessionStorageNamespace(
3077 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:303078}
3079
3080const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573081NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303082 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553083}
[email protected]d202a7c2012-01-04 07:53:473084
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573085bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563086 return needs_reload_;
3087}
[email protected]a26023822011-12-29 00:23:553088
[email protected]46bb5e9c2013-10-03 22:16:473089void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413090 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3091}
3092
3093void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473094 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413095 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543096
3097 if (last_committed_entry_index_ != -1) {
3098 entries_[last_committed_entry_index_]->SetTransitionType(
3099 ui::PAGE_TRANSITION_RELOAD);
3100 }
[email protected]46bb5e9c2013-10-03 22:16:473101}
3102
[email protected]d202a7c2012-01-04 07:53:473103void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573104 DCHECK_LT(index, GetEntryCount());
3105 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313106 DiscardNonCommittedEntries();
3107
Nate Chapin9eb16be72022-09-23 22:54:313108 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313109 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123110 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313111 last_committed_entry_index_--;
3112}
3113
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573114NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273115 // If there is no pending_entry_, there should be no pending_entry_index_.
3116 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3117
3118 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363119 // at that index. An exception is while a reload of a post commit error page
3120 // is ongoing; in that case pending entry will point to the entry replaced
3121 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273122 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363123 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3124 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273125
[email protected]022af742011-12-28 18:37:253126 return pending_entry_;
3127}
3128
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573129int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273130 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273131 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553132 return pending_entry_index_;
3133}
3134
avi25764702015-06-23 15:43:373135void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573136 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363137 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313138 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003139 bool in_fenced_frame_tree,
3140 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313141 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3142 // set because:
3143 // 1) They don't influence the history of the outer page.
3144 // 2) They are always replace only navigation (there is always only one entry
3145 // in their history stack).
3146 // 3) Are not top level navigations and appear similar to iframes.
3147 // Navigations of the fenced frame might create a new NavigationEntry, which
3148 // will call this function. Non fenced frame navigations will never have
3149 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3150 // InsertOrReplaceEntry.
3151 DCHECK_EQ(in_fenced_frame_tree,
3152 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3153 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203154
avi5cad4912015-06-19 05:25:443155 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3156 // need to keep continuity with the pending entry, so copy the pending entry's
3157 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3158 // then the renderer navigated on its own, independent of the pending entry,
3159 // so don't copy anything.
3160 if (pending_entry_ && pending_entry_index_ == -1)
3161 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203162
Rakina Zata Amnia4e27222021-12-22 01:05:003163 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203164
creisee17e932015-07-17 17:56:223165 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453166 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103167 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573168 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363169 // If the new entry is a post-commit error page, we store the current last
3170 // committed entry to the side so that we can put it back when navigating
3171 // away from the error.
3172 if (was_post_commit_error) {
3173 DCHECK(!entry_replaced_by_post_commit_error_);
3174 entry_replaced_by_post_commit_error_ =
3175 std::move(entries_[last_committed_entry_index_]);
3176 }
dcheng36b6aec92015-12-26 06:16:363177 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223178 return;
3179 }
[email protected]765b35502008-08-21 00:51:203180
creis37979a62015-08-04 19:48:183181 // We shouldn't see replace == true when there's no committed entries.
3182 DCHECK(!replace);
3183
Michael Thiessen9b14d512019-09-23 21:19:473184 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203185
Shivani Sharmad8c8d652019-02-13 17:27:573186 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203187
dcheng36b6aec92015-12-26 06:16:363188 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203189 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293190}
3191
Shivani Sharmad8c8d652019-02-13 17:27:573192void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163193 if (entries_.size() < max_entry_count())
3194 return;
3195
3196 DCHECK_EQ(max_entry_count(), entries_.size());
3197 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573198 CHECK_EQ(pending_entry_index_, -1);
3199
3200 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423201 // Retrieve the oldest skippable entry.
3202 for (; index < GetEntryCount(); index++) {
3203 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3204 break;
Shivani Sharmad8c8d652019-02-13 17:27:573205 }
3206
3207 // If there is no skippable entry or if it is the last committed entry then
3208 // fall back to pruning the oldest entry. It is not safe to prune the last
3209 // committed entry.
3210 if (index == GetEntryCount() || index == last_committed_entry_index_)
3211 index = 0;
3212
3213 bool should_succeed = RemoveEntryAtIndex(index);
3214 DCHECK_EQ(true, should_succeed);
3215
3216 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253217}
3218
William Liu62ae26c2024-08-08 14:28:163219std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273220NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163221 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203222 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373223 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133224 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493225 const std::string* navigation_api_key,
3226 base::TimeTicks actual_navigation_start) {
Alexander Timin3a92df72019-09-20 11:59:503227 TRACE_EVENT0("navigation",
3228 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273229 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023230 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363231 if (pending_entry_index_ != -1) {
3232 // The pending entry may not be in entries_ if a post-commit error page is
3233 // showing.
3234 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3235 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3236 }
Gyuyoung Kim107c2a02021-04-13 01:49:303237 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573238 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013239 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033240 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573241 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133242 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3243 // the same as the top level frame being navigated.
3244 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373245 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133246 }
Arthur Sonzogni620cec62018-12-13 13:08:573247
[email protected]83c2e232011-10-07 21:36:463248 // If we were navigating to a slow-to-commit page, and the user performs
3249 // a session history navigation to the last committed page, RenderViewHost
3250 // will force the throbber to start, but WebKit will essentially ignore the
3251 // navigation, and won't send a message to stop the throbber. To prevent this
3252 // from happening, we drop the navigation here and stop the slow-to-commit
3253 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023254 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083255 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273256 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033257 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123258
[email protected]83c2e232011-10-07 21:36:463259 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163260 return {};
[email protected]83c2e232011-10-07 21:36:463261 }
3262
Arthur Sonzognic686e8f2024-01-11 08:36:373263 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333264 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3265 if (initiator_rfh) {
3266 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543267 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333268 DCHECK(initiator_frame_token);
3269 }
3270
creisce0ef3572017-01-26 17:53:083271 // Compare FrameNavigationEntries to see which frames in the tree need to be
3272 // navigated.
clamy3cb9bea92018-07-10 12:42:023273 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3274 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333275 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3276 initiator_process_id, soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493277 actual_navigation_start, &same_document_loads,
3278 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303279
3280 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573281 // We were unable to match any frames to navigate. This can happen if a
3282 // history navigation targets a subframe that no longer exists
3283 // (https://crbug.com/705550). In this case, we need to update the current
3284 // history entry to the pending one but keep the main document loaded. We
3285 // also need to ensure that observers are informed about the updated
3286 // current history entry (e.g., for greying out back/forward buttons), and
Charlie Reis99b2eba22025-01-31 19:18:573287 // that renderer processes update their history indices. The easiest way
Alex Moshchuk3a4e77a2020-05-29 21:32:573288 // to do all that is to schedule a "redundant" same-document navigation in
3289 // the main frame.
3290 //
3291 // Note that we don't want to remove this history entry, as it might still
3292 // be valid later, since a frame that it's targeting may be recreated.
3293 //
3294 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3295 // need to repeat history navigations until finding the one that works.
3296 // Consider changing this behavior to keep looking for the first valid
3297 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023298 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423299 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573300 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573301 ReloadType::NONE /* reload_type */,
3302 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433303 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493304 initiator_frame_token, initiator_process_id,
3305 actual_navigation_start);
clamy3cb9bea92018-07-10 12:42:023306 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573307 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023308 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163309 return {};
clamy3cb9bea92018-07-10 12:42:023310 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573311 same_document_loads.push_back(std::move(navigation_request));
3312
3313 // Sanity check that we never take this branch for any kinds of reloads,
3314 // as those should've queued a different-document load in the main frame.
3315 DCHECK(!is_forced_reload);
3316 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303317 }
3318
Nate Chapinbf682fa32022-09-26 22:41:203319 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163320 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203321 if (initiator_rfh && initiator_rfh->IsSandboxed(
3322 network::mojom::WebSandboxFlags::kTopNavigation)) {
3323 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3324 initiator_rfh, same_document_loads) &&
3325 DoesSandboxNavigationStayWithinSubtree(
3326 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503327 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163328 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203329 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3330 initiator_rfh,
3331 navigates_inside_tree
3332 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3333 : blink::mojom::WebFeature::
3334 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523335
3336 // If the navigation occurred outside the tree discard it because
3337 // the sandboxed frame didn't have permission to navigate outside
3338 // its tree. If it is possible that the navigation is both inside and
3339 // outside the frame tree and we discard it entirely because we don't
3340 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143341 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203342 // If a |navigation_api_key| was provided, this navigation originated from
3343 // the navigation API. Notify the renderer that the navigation was
3344 // cancelled so the navigation API can fire an error event and reject the
3345 // relevant promise.
3346 if (navigation_api_key) {
3347 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3348 *navigation_api_key,
3349 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3350 }
Dave Tapuska855c1e12019-08-23 20:45:523351 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133352
3353 for (auto& unused_request : same_document_loads) {
3354 unused_request->set_navigation_discard_reason(
3355 NavigationDiscardReason::kNeverStarted);
3356 }
3357 for (auto& unused_request : different_document_loads) {
3358 unused_request->set_navigation_discard_reason(
3359 NavigationDiscardReason::kNeverStarted);
3360 }
William Liu62ae26c2024-08-08 14:28:163361 return {};
Dave Tapuska855c1e12019-08-23 20:45:523362 }
Dave Tapuska8bfd84c2019-03-26 20:47:163363 }
3364
Nate Chapin6c43c022023-02-13 23:32:423365 // If it is possible that this traverse may involve a same-document navigation
3366 // in the initiator and there is a Navigation API key involved, then we may
3367 // need to notify the initiator if it fails. (The early returns above either
3368 // do not involve these cases or already notify the initiator.)
3369 // The event only needs to fire for the initiator, and only if the initiator
3370 // itself is performing a same-document navigation (because the event will not
3371 // fire if it navigates cross-document).
3372 if (navigation_api_key) {
3373 for (auto& item : same_document_loads) {
3374 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3375 item->set_pending_navigation_api_key(*navigation_api_key);
3376 break;
3377 }
3378 }
3379 }
3380
Carlos Caballero539a421c2020-07-06 10:25:573381 // BackForwardCache:
3382 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563383 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573384 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
Charlie Reis3696ab62025-05-28 07:02:303385 // TODO(crbug.com/420275259): Diagnose failures and upgrade to a CHECK.
3386 DCHECK_EQ(reload_type, ReloadType::NONE);
Charlie Reis655c8f02025-05-15 01:16:173387 base::WeakPtr<NavigationRequest> request;
Rakina Zata Amni58681c62024-06-25 06:32:133388
Charlie Reis655c8f02025-05-15 01:16:173389 // Skip a redundant NavigationRequest creation, per
3390 // https://crbug.com/417251428.
3391 if (base::FeatureList::IsEnabled(kSkipExtraBfcacheNavigationRequest)) {
3392 // If the BackForwardCache can handle this request, it must be for a main
3393 // frame, cross-document, non-reload request. This means there is only one
3394 // item in `different_document_loads` and no `same_document_loads`.
3395 CHECK_EQ(different_document_loads.size(), 1u);
3396 CHECK(same_document_loads.empty());
3397 request = different_document_loads.at(0)->GetWeakPtr();
Charlie Reisd3e4fef2025-05-20 02:04:173398
3399 // Ensure that no re-entrant calls or discards of the pending entry occur
3400 // while calling `Navigator::Navigate` for a pending entry.
3401 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3402 weak_factory_.GetSafeRef());
3403
Charlie Reis655c8f02025-05-15 01:16:173404 root->navigator().Navigate(std::move(different_document_loads.at(0)),
3405 ReloadType::NONE);
Charlie Reisd3e4fef2025-05-20 02:04:173406
3407 // `reentrancy_guard` deleted here.
Charlie Reis655c8f02025-05-15 01:16:173408 } else {
3409 // The legacy approach creates a new NavigationRequest for the entry and
3410 // discards any previously created NavigationRequests, even though the new
3411 // request is identical to the sole existing request.
3412 // TODO(crbug.com/417251428): Remove this path once we measure the impact.
3413 auto navigation_request = CreateNavigationRequestFromEntry(
3414 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3415 ReloadType::NONE, false /* is_same_document_history_load */,
3416 false /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:493417 initiator_process_id, actual_navigation_start);
Charlie Reis655c8f02025-05-15 01:16:173418 request = navigation_request->GetWeakPtr();
3419 root->navigator().Navigate(std::move(navigation_request),
3420 ReloadType::NONE);
3421
3422 for (auto& unused_request : same_document_loads) {
3423 unused_request->set_navigation_discard_reason(
3424 NavigationDiscardReason::kNeverStarted);
3425 }
3426 for (auto& unused_request : different_document_loads) {
3427 unused_request->set_navigation_discard_reason(
3428 NavigationDiscardReason::kNeverStarted);
3429 }
Rakina Zata Amni58681c62024-06-25 06:32:133430 }
3431
Charlie Reis655c8f02025-05-15 01:16:173432 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_requests;
William Liu62ae26c2024-08-08 14:28:163433 if (request) {
Charlie Reis655c8f02025-05-15 01:16:173434 bf_cache_requests.push_back(std::move(request));
William Liu62ae26c2024-08-08 14:28:163435 }
Charlie Reis655c8f02025-05-15 01:16:173436 return bf_cache_requests;
Carlos Caballero539a421c2020-07-06 10:25:573437 }
3438
3439 // History navigation might try to reuse a specific BrowsingInstance, already
3440 // used by a page in the cache. To avoid having two different main frames that
3441 // live in the same BrowsingInstance, evict the all pages with this
3442 // BrowsingInstance from the cache.
3443 //
3444 // For example, take the following scenario:
3445 //
3446 // A1 = Some page on a.com
3447 // A2 = Some other page on a.com
3448 // B3 = An uncacheable page on b.com
3449 //
3450 // Then the following navigations occur:
3451 // A1->A2->B3->A1
3452 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3453 // take its place) and A1 will be created in the same BrowsingInstance (and
3454 // SiteInstance), as A2.
3455 //
3456 // If we didn't do anything, both A1 and A2 would remain alive in the same
3457 // BrowsingInstance/SiteInstance, which is unsupported by
3458 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3459 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483460 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3461 pending_entry_->site_instance()
3462 ? pending_entry_->site_instance()->GetId().value()
3463 : -1);
3464 SCOPED_CRASH_KEY_NUMBER(
3465 "rvh_double", "pending_entry_bi",
3466 pending_entry_->site_instance()
3467 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3468 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573469 if (pending_entry_->site_instance()) {
3470 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3471 pending_entry_->site_instance());
3472 }
3473
Rakina Zata Amnid605d462022-06-01 10:17:033474 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3475 pending_entry_ && pending_entry_->IsRestored());
3476 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3477 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3478 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3479 pending_entry_index_);
3480 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3481 last_committed_entry_index_);
3482 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3483 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3484 pending_entry_ && pending_entry_->IsInitialEntry());
3485 SCOPED_CRASH_KEY_BOOL(
3486 "nav_reentrancy", "pending_entry_initial2",
3487 pending_entry_ &&
3488 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3489 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3490 IsInitialNavigation());
3491 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3492 IsInitialBlankNavigation());
3493 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3494 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3495 (int)pending_reload_);
3496
Charlie Reisd3e4fef2025-05-20 02:04:173497 // Ensure that no re-entrant calls or discards of the pending entry occur
3498 // while calling `Navigator::Navigate` for a pending entry.
3499 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3500 weak_factory_.GetSafeRef());
creis4e2ecb72015-06-20 00:46:303501
Rakina Zata Amnid605d462022-06-01 10:17:033502 // If the navigation-reentrancy is caused by calling
3503 // NavigateToExistingPendingEntry twice, this will note the previous call's
3504 // pending entry's ID.
3505 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3506 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3507
Nate Chapin154b14b2023-02-17 18:28:163508 // If there is a main-frame same-document history navigation, we may defer
3509 // the subframe history navigations in order to give JS in the main frame the
3510 // opportunity to cancel the entire traverse via the navigate event. In that
3511 // case, we need to stash the main frame request's navigation token on the
3512 // subframes, so they can look up the main frame request and defer themselves
3513 // until it completes.
3514 if (!same_document_loads.empty() &&
3515 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3516 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3517 // The token will only be returned in cases where deferring the navigation
3518 // is necessary.
3519 if (auto main_frame_same_document_token =
3520 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3521 for (auto& item : same_document_loads) {
3522 if (item.get() != main_frame_request) {
3523 item->set_main_frame_same_document_history_token(
3524 main_frame_same_document_token);
3525 }
3526 }
3527 for (auto& item : different_document_loads) {
3528 item->set_main_frame_same_document_history_token(
3529 main_frame_same_document_token);
3530 }
3531 }
3532 }
3533
William Liu122754942024-01-18 22:34:393534 if (!initiator_rfh) {
3535 // A browser-initiated navigation won't have a `initiator_rfh`.
3536 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3537 different_document_loads, same_document_loads);
3538 }
3539
William Liu62ae26c2024-08-08 14:28:163540 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3541 all_requests.reserve(same_document_loads.size() +
3542 different_document_loads.size());
3543 bool seen_primary_main_frame_request = false;
3544
creis4e2ecb72015-06-20 00:46:303545 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023546 for (auto& item : same_document_loads) {
3547 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273548 // The request could be destroyed before `navigator().Navigate()` returns.
3549 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053550 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163551 if (request) {
3552 // Can only have one primary main frame request.
3553 CHECK(!seen_primary_main_frame_request ||
3554 !request->IsInPrimaryMainFrame());
3555 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3556 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273557 }
creis4e2ecb72015-06-20 00:46:303558 }
clamy3cb9bea92018-07-10 12:42:023559 for (auto& item : different_document_loads) {
3560 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273561 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053562 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163563 if (request) {
3564 // Can only have one primary main frame request.
3565 CHECK(!seen_primary_main_frame_request ||
3566 !request->IsInPrimaryMainFrame());
3567 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3568 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273569 }
creis4e2ecb72015-06-20 00:46:303570 }
clamy3cb9bea92018-07-10 12:42:023571
William Liu62ae26c2024-08-08 14:28:163572 return all_requests;
Charlie Reisd3e4fef2025-05-20 02:04:173573 // `reentrancy_guard` deleted here.
creis4e2ecb72015-06-20 00:46:303574}
3575
Alex Moshchuk3a4e77a2020-05-29 21:32:573576NavigationControllerImpl::HistoryNavigationAction
3577NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303578 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573579 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423580 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583581 // Only active and prerendered documents are allowed to navigate in their
3582 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423583 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013584 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583585 // - If the document is in pending deletion, the browser already committed
3586 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3587 // - If the document is in back-forward cache, it's not allowed to navigate
3588 // as it should remain frozen. Ignore the request and evict the document
3589 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423590 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583591 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423592 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113593 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3594 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423595 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113596 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423597 }
arthursonzogni03f76152019-02-12 10:35:203598
Alex Moshchuk3a4e77a2020-05-29 21:32:573599 // Reloads should result in a different-document load. Note that reloads may
3600 // also happen via the |needs_reload_| mechanism where the reload_type is
3601 // NONE, so detect this by comparing whether we're going to the same
3602 // entry that we're currently on. Similarly to above, only main frames
3603 // should reach this. Note that subframes support reloads, but that's done
3604 // via a different path that doesn't involve FindFramesToNavigate (see
3605 // RenderFrameHost::Reload()).
3606 if (reload_type != ReloadType::NONE ||
3607 pending_entry_index_ == last_committed_entry_index_) {
3608 DCHECK(frame->IsMainFrame());
3609 return HistoryNavigationAction::kDifferentDocument;
3610 }
3611
Alex Moshchuk47d1a4bd2020-06-01 22:15:343612 // If there is no new FrameNavigationEntry for the frame, ignore the
3613 // load. For example, this may happen when going back to an entry before a
3614 // frame was created. Suppose we commit a same-document navigation that also
3615 // results in adding a new subframe somewhere in the tree. If we go back,
3616 // the new subframe will be missing a FrameNavigationEntry in the previous
3617 // NavigationEntry, but we shouldn't delete or change what's loaded in
3618 // it.
3619 //
Alex Moshchuke65c39272020-06-03 17:55:373620 // Note that in this case, there is no need to keep looking for navigations
3621 // in subframes, which would be missing FrameNavigationEntries as well.
3622 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343623 // It's important to check this before checking |old_item| below, since both
3624 // might be null, and in that case we still shouldn't change what's loaded in
3625 // this frame. Note that scheduling any loads assumes that |new_item| is
3626 // non-null. See https://crbug.com/1088354.
3627 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3628 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373629 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343630
Charlie Reisa474fb62022-03-17 02:31:363631 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3632 // which history item it is currently on, since this may be different than the
3633 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3634 // (e.g., if a history navigation is targeting multiple frames and only some
3635 // have committed so far).
creis4e2ecb72015-06-20 00:46:303636 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363637 frame->current_frame_host()->last_committed_frame_entry();
3638 if (!old_item) {
3639 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3640 // fall back to the last committed NavigationEntry's record for this frame.
3641 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583642 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363643 // accurate FrameNavigationEntry and eliminate this case.
3644 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3645 }
3646 // If neither approach finds a FrameNavigationEntry, schedule a
3647 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583648 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573649 if (!old_item)
3650 return HistoryNavigationAction::kDifferentDocument;
3651
Alex Moshchuk3a4e77a2020-05-29 21:32:573652 // If the new item is not in the same SiteInstance, schedule a
3653 // different-document load. Newly restored items may not have a SiteInstance
3654 // yet, in which case it will be assigned on first commit.
3655 if (new_item->site_instance() &&
3656 new_item->site_instance() != old_item->site_instance())
3657 return HistoryNavigationAction::kDifferentDocument;
3658
Charlie Reis71e4ae32025-01-29 21:37:573659 // If the origins of the new and old items are both present but don't match,
3660 // schedule a different document load even if the document sequence numbers
3661 // somehow match.
3662 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3663 // committed origin on `new_item`, and update the Blink DSN computation to
3664 // avoid a cross-origin DSN match when possible.
3665 if (new_item->committed_origin().has_value() &&
3666 old_item->committed_origin().has_value() &&
3667 !new_item->committed_origin()->IsSameOriginWith(
3668 old_item->committed_origin().value())) {
3669 return HistoryNavigationAction::kDifferentDocument;
3670 }
3671
Alex Moshchuk3a4e77a2020-05-29 21:32:573672 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313673 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3674 // that we do this even if the history navigation would not be modifying this
3675 // frame were it live.
3676 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573677 return HistoryNavigationAction::kDifferentDocument;
3678
3679 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313680 // Starting a navigation after a crash early-promotes the speculative
3681 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3682 // committed yet, so we can not possibly perform a same-document history
3683 // navigation. The frame would need to be reloaded with a cross-document
3684 // navigation.
3685 if (!frame->current_frame_host()->has_committed_any_navigation())
3686 return HistoryNavigationAction::kDifferentDocument;
3687
creis54131692016-08-12 18:32:253688 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493689 // sequence number but different item sequence number.
3690 if (new_item->document_sequence_number() ==
3691 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573692 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493693 }
avib48cb312016-05-05 21:35:003694
Alex Moshchuk3a4e77a2020-05-29 21:32:573695 // Otherwise, if both item and document sequence numbers differ, this
3696 // should be a different document load.
3697 return HistoryNavigationAction::kDifferentDocument;
3698 }
3699
3700 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373701 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573702 DCHECK_EQ(new_item->document_sequence_number(),
3703 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373704 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573705}
3706
3707void NavigationControllerImpl::FindFramesToNavigate(
3708 FrameTreeNode* frame,
3709 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373710 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333711 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373712 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133713 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493714 base::TimeTicks actual_navigation_start,
Alex Moshchuk3a4e77a2020-05-29 21:32:573715 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3716 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3717 DCHECK(pending_entry_);
3718 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3719
3720 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3721
3722 if (action == HistoryNavigationAction::kSameDocument) {
3723 std::unique_ptr<NavigationRequest> navigation_request =
3724 CreateNavigationRequestFromEntry(
3725 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133726 /*is_same_document_history_load=*/true,
3727 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333728 initiator_frame_token, initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:493729 actual_navigation_start, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573730 if (navigation_request) {
3731 // Only add the request if was properly created. It's possible for the
3732 // creation to fail in certain cases, e.g. when the URL is invalid.
3733 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303734 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573735 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473736 std::unique_ptr<NavigationRequest> navigation_request =
3737 CreateNavigationRequestFromEntry(
3738 frame, pending_entry_, new_item, reload_type,
3739 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433740 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493741 initiator_frame_token, initiator_process_id,
3742 actual_navigation_start);
Lei Zhang96031532019-10-10 19:05:473743 if (navigation_request) {
3744 // Only add the request if was properly created. It's possible for the
3745 // creation to fail in certain cases, e.g. when the URL is invalid.
3746 different_document_loads->push_back(std::move(navigation_request));
3747 }
3748 // For a different document, the subframes will be destroyed, so there's
3749 // no need to consider them.
3750 return;
Alex Moshchuke65c39272020-06-03 17:55:373751 } else if (action == HistoryNavigationAction::kStopLooking) {
3752 return;
creis4e2ecb72015-06-20 00:46:303753 }
3754
Yoav Weiss8c573952022-11-17 17:35:133755 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3756 // we currently only support soft navigation heuristics for the top level
3757 // frame.
creis4e2ecb72015-06-20 00:46:303758 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333759 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3760 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373761 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:493762 actual_navigation_start, same_document_loads,
3763 different_document_loads);
creis4e2ecb72015-06-20 00:46:303764 }
3765}
3766
Harkiran Bolariaba823e42021-05-21 18:30:363767base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
Charlie Reisf4d51f402025-05-23 18:00:493768 const LoadURLParams& params,
3769 base::TimeTicks actual_navigation_start) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553770 FrameTreeNode* node = GetTargetFrameTreeNodeForNavigation(params);
clamy21718cc22018-06-13 13:34:243771
Camille Lamy5193caa2018-10-12 11:59:423772 // Compute overrides to the LoadURLParams for |override_user_agent|,
3773 // |should_replace_current_entry| and |has_user_gesture| that will be used
3774 // both in the creation of the NavigationEntry and the NavigationRequest.
3775 // Ideally, the LoadURLParams themselves would be updated, but since they are
3776 // passed as a const reference, this is not possible.
3777 // TODO(clamy): When we only create a NavigationRequest, move this to
3778 // CreateNavigationRequestFromLoadURLParams.
3779 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3780 GetLastCommittedEntry());
3781
Rakina Zata Amnie2d31312022-11-18 03:38:453782 // An entry replacement must happen if the current browsing context should
3783 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333784 bool should_replace_current_entry =
3785 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453786 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423787
clamy21718cc22018-06-13 13:34:243788 // Javascript URLs should not create NavigationEntries. All other navigations
3789 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243790 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373791 std::unique_ptr<NavigationEntryImpl> entry =
3792 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3793 should_replace_current_entry,
3794 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243795 DiscardPendingEntry(false);
3796 SetPendingEntry(std::move(entry));
3797 }
3798
Tim Judkins59548192023-05-17 17:51:203799 // Renderer-debug URLs are sent to the current renderer process immediately
3800 // for processing and don't need to create a NavigationRequest. Note: this
3801 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243802 // renderer-debug URLs.
3803 // Note: we intentionally leave the pending entry in place for renderer debug
3804 // URLs, unlike the cases below where we clear it if the navigation doesn't
3805 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303806 if (blink::IsRendererDebugURL(params.url)) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553807 // Renderer-debug URLs won't go through NavigationThrottles so we have to
3808 // check them explicitly. See crbug.com/40605746.
Aaron Colwelle1908d982020-06-26 22:08:153809 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203810 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483811 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363812 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483813 }
3814
clamy21718cc22018-06-13 13:34:243815 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363816 return nullptr;
clamy21718cc22018-06-13 13:34:243817 }
3818
Antonio Sartori78a749f2020-11-30 12:03:393819 DCHECK(pending_entry_);
3820
clamy21718cc22018-06-13 13:34:243821 // Convert navigations to the current URL to a reload.
3822 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3823 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3824 // DevTools sometimes issues navigations to main frames that they do not
3825 // expect to see treated as reload, and it only works because they pass a
3826 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3827 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543828 ReloadType reload_type = params.reload_type;
3829 if (reload_type == ReloadType::NONE &&
3830 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043831 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243832 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243833 params.load_type ==
3834 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543835 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243836 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473837 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393838
3839 // If this is a reload of an existing FrameNavigationEntry and we had a
3840 // policy container for it, then we should copy it into the pending entry,
3841 // so that it is copied to the navigation request in
3842 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453843 FrameNavigationEntry* previous_frame_entry =
3844 GetLastCommittedEntry()->GetFrameEntry(node);
3845 if (previous_frame_entry &&
3846 previous_frame_entry->policy_container_policies()) {
3847 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3848 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393849 }
3850 }
3851
3852 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173853 // document, then we should copy the document polices from RenderFrameHost's
3854 // PolicyContainerHost. The NavigationRequest will create a new
3855 // PolicyContainerHost with the document policies from the |pending_entry_|,
3856 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3857 // the navigation. This way, we ensure that we keep enforcing the right
3858 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453859 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393860 if (node->current_frame_host() &&
3861 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193862 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163863 node->current_frame_host()
3864 ->policy_container_host()
3865 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233866 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393867 }
clamy21718cc22018-06-13 13:34:243868 }
3869
3870 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263871 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243872
Tsuyoshi Horo167ca6432022-03-09 05:16:393873 // This will be used to set the Navigation Timing API navigationStart
3874 // parameter for browser navigations in new tabs (intents, tabs opened through
3875 // "Open link in new tab"). If the navigation must wait on the current
3876 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3877 // will be updated when the BeforeUnload ack is received.
3878 const auto navigation_start_time = base::TimeTicks::Now();
Tsuyoshi Horo167ca6432022-03-09 05:16:393879
Camille Lamy5193caa2018-10-12 11:59:423880 std::unique_ptr<NavigationRequest> request =
3881 CreateNavigationRequestFromLoadParams(
3882 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143883 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393884 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
Charlie Reisf4d51f402025-05-23 18:00:493885 actual_navigation_start, navigation_start_time);
clamy21718cc22018-06-13 13:34:243886
3887 // If the navigation couldn't start, return immediately and discard the
3888 // pending NavigationEntry.
3889 if (!request) {
3890 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363891 return nullptr;
clamy21718cc22018-06-13 13:34:243892 }
3893
Camille Lamy5193caa2018-10-12 11:59:423894#if DCHECK_IS_ON()
3895 // Safety check that NavigationRequest and NavigationEntry match.
3896 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3897#endif
3898
Charlie Reisd3e4fef2025-05-20 02:04:173899 // Ensure that no re-entrant calls or discards of the pending entry occur
3900 // while calling `Navigator::Navigate` for a pending entry.
3901 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3902 weak_factory_.GetSafeRef());
arthursonzogni66f711c2019-10-08 14:40:363903
Harkiran Bolariaba823e42021-05-21 18:30:363904 base::WeakPtr<NavigationHandle> created_navigation_handle(
3905 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053906 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243907
Harkiran Bolariaba823e42021-05-21 18:30:363908 return created_navigation_handle;
Charlie Reisd3e4fef2025-05-20 02:04:173909 // `reentrancy_guard` deleted here.
clamy21718cc22018-06-13 13:34:243910}
3911
Emmanuel Arias Soto9e159652025-05-16 07:53:553912FrameTreeNode* NavigationControllerImpl::GetTargetFrameTreeNodeForNavigation(
3913 const LoadURLParams& params) {
3914 FrameTreeNode* node = nullptr;
3915 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3916 node = params.frame_tree_node_id
3917 ? frame_tree_->FindByID(params.frame_tree_node_id)
3918 : frame_tree_->FindByName(params.frame_name);
3919 DCHECK(!node || &node->frame_tree() == &frame_tree());
3920 if (!node && params.frame_tree_node_id) {
3921 // If the specified FrameTreeNode exists in another FrameTree, the caller
3922 // is using the wrong NavigationController.
3923 CHECK(!FrameTreeNode::GloballyFindByID(params.frame_tree_node_id),
3924 base::NotFatalUntil::M140);
3925 }
3926 }
3927
3928 // If no FrameTreeNode was specified, navigate the main frame.
3929 if (!node) {
3930 node = frame_tree_->root();
3931 }
3932 return node;
3933}
3934
clamyea99ea12018-05-28 13:54:233935void NavigationControllerImpl::HandleRendererDebugURL(
3936 FrameTreeNode* frame_tree_node,
3937 const GURL& url) {
3938 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243939 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3940 // the renderer process is not live, unless it is the initial navigation
3941 // of the tab.
clamyea99ea12018-05-28 13:54:233942 if (!IsInitialNavigation()) {
3943 DiscardNonCommittedEntries();
3944 return;
3945 }
Fergal Dalyecd3b0202020-06-25 01:57:373946 // The current frame is always a main frame. If IsInitialNavigation() is
3947 // true then there have been no navigations and any frames of this tab must
3948 // be in the same renderer process. If that has crashed then the only frame
3949 // that can be revived is the main frame.
3950 frame_tree_node->render_manager()
3951 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233952 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223953
3954 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3955 // notification, so set is loading to true here to properly surface it when
3956 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313957 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223958 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223959 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223960 }
clamyea99ea12018-05-28 13:54:233961 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3962}
3963
clamy21718cc22018-06-13 13:34:243964std::unique_ptr<NavigationEntryImpl>
3965NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3966 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423967 const LoadURLParams& params,
3968 bool override_user_agent,
3969 bool should_replace_current_entry,
3970 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393971 // Browser initiated navigations might not have a blob_url_loader_factory set
3972 // in params even if the navigation is to a blob URL. If that happens, lookup
3973 // the correct url loader factory to use here.
3974 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483975 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473976 // Resolve the blob URL in the storage partition associated with the target
3977 // frame. This is the storage partition the URL will be loaded in, and only
3978 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393979 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473980 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393981 }
3982
clamy21718cc22018-06-13 13:34:243983 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443984 // extra_headers in params are \n separated; navigation entries want \r\n.
3985 std::string extra_headers_crlf;
3986 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243987
3988 // For subframes, create a pending entry with a corresponding frame entry.
3989 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453990 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243991 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083992 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243993 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373994 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213995 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3996 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393997 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163998 // a conversion of a new navigation into a reload, we will set the right
3999 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:194000 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:244001 } else {
4002 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:174003 // If `node` is the outermost main frame, it rewrites a virtual url in order
4004 // to adjust the original input url if needed. For inner frames such as
4005 // fenced frames or subframes, they don't rewrite urls as the urls are not
4006 // input urls by users.
4007 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:324008 scoped_refptr<SiteInstance> source_site_instance =
4009 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:374010 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:324011 if (source_site_instance && source_site_instance->HasProcess()) {
4012 source_process_site_url =
4013 source_site_instance->GetProcess()->GetProcessLock().site_url();
4014 }
clamy21718cc22018-06-13 13:34:244015 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:064016 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:324017 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:214018 params.transition_type, params.is_renderer_initiated,
4019 extra_headers_crlf, browser_context_, blob_url_loader_factory,
4020 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:244021 entry->set_source_site_instance(
4022 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
4023 entry->SetRedirectChain(params.redirect_chain);
4024 }
4025
4026 // Set the FTN ID (only used in non-site-per-process, for tests).
4027 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:244028 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:424029 entry->SetIsOverridingUserAgent(override_user_agent);
4030 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:544031 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:244032
clamy21718cc22018-06-13 13:34:244033 switch (params.load_type) {
4034 case LOAD_TYPE_DEFAULT:
4035 break;
4036 case LOAD_TYPE_HTTP_POST:
4037 entry->SetHasPostData(true);
4038 entry->SetPostData(params.post_data);
4039 break;
4040 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:544041 // LoadDataWithBaseURL is a special case that needs to assign both a base
4042 // URL and a virtual URL, while loading the actual content from a data
4043 // URL.
clamy21718cc22018-06-13 13:34:244044 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:544045 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:284046#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:244047 entry->SetDataURLAsString(params.data_url_as_string);
4048#endif
4049 entry->SetCanLoadLocalResources(params.can_load_local_resources);
4050 break;
Shu Yang112ad492024-07-25 17:11:544051#if BUILDFLAG(IS_ANDROID)
4052 case LOAD_TYPE_PDF_ANDROID:
4053 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
4054 // internal URL is used for the navigation URL.
4055 entry->SetVirtualURL(params.virtual_url_for_special_cases);
4056 break;
4057#endif
clamy21718cc22018-06-13 13:34:244058 }
4059
4060 // TODO(clamy): NavigationEntry is meant for information that will be kept
4061 // after the navigation ended and therefore is not appropriate for
4062 // started_from_context_menu. Move started_from_context_menu to
4063 // NavigationUIData.
4064 entry->set_started_from_context_menu(params.started_from_context_menu);
4065
4066 return entry;
4067}
4068
clamyea99ea12018-05-28 13:54:234069std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:424070NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
4071 FrameTreeNode* node,
4072 const LoadURLParams& params,
4073 bool override_user_agent,
4074 bool should_replace_current_entry,
4075 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:144076 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:424077 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574078 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:394079 FrameNavigationEntry* frame_entry,
Charlie Reise1d9b8182025-04-02 04:32:124080 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:224081 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:494082 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:454083 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584084 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:344085 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:374086 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574087 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:524088
4089 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
4090 // subframes have FrameNavigationEntries associated with them. Until then,
4091 // there may be cases where a subframe navigation is missing `frame_entry`
4092 // (e.g., see https://crbug.com/358084015).
4093
Nasko Oskov3c2f9e252019-01-10 17:45:534094 // All renderer-initiated navigations must have an initiator_origin.
4095 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:514096
Camille Lamy5193caa2018-10-12 11:59:424097 GURL url_to_load;
4098 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:324099
Camille Lamy2baa8022018-10-19 16:43:174100 // For main frames, rewrite the URL if necessary and compute the virtual URL
4101 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:264102 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424103 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:174104 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424105 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:424106
Shu Yang112ad492024-07-25 17:11:544107 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
4108 // that need to define a virtual URL to display, which differs from the
4109 // navigation URL.
4110 if (params.load_type == LOAD_TYPE_DATA) {
4111 virtual_url = params.virtual_url_for_special_cases;
4112 }
4113#if BUILDFLAG(IS_ANDROID)
4114 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
4115 virtual_url = params.virtual_url_for_special_cases;
4116 }
4117#endif
Camille Lamy5193caa2018-10-12 11:59:424118
Camille Lamy2baa8022018-10-19 16:43:174119 if (virtual_url.is_empty())
4120 virtual_url = url_to_load;
4121
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574122 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:284123
Aran Gilman249eb122019-12-02 23:32:464124 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
4125 // behavior: it is possible for two calls to RewriteUrlForNavigation to
4126 // return different results, leading to a different URL in the
4127 // NavigationRequest and FrameEntry. This will be fixed once we remove the
4128 // pending NavigationEntry, as we'll only make one call to
4129 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:524130 if (frame_entry) {
4131 VLOG_IF(1, (url_to_load != frame_entry->url()))
4132 << "NavigationRequest and FrameEntry have different URLs: "
4133 << url_to_load << " vs " << frame_entry->url();
4134 }
Camille Lamyb9ed3c52018-11-19 15:34:284135
Camille Lamy2baa8022018-10-19 16:43:174136 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424137 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174138 // NavigationRequest.
4139 } else {
4140 url_to_load = params.url;
4141 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244142 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174143 }
Camille Lamy5193caa2018-10-12 11:59:424144
Ehsan Karamad44fc72112019-02-26 18:15:474145 if (node->render_manager()->is_attaching_inner_delegate()) {
4146 // Avoid starting any new navigations since this node is now preparing for
4147 // attaching an inner delegate.
4148 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204149 }
Camille Lamy5193caa2018-10-12 11:59:424150
Alex Moshchuk99242832023-05-22 17:21:444151 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424152 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444153 }
Camille Lamy5193caa2018-10-12 11:59:424154
danakjd83d706d2020-11-25 22:11:124155 // Look for a pending commit that is to another document in this
4156 // FrameTreeNode. If one exists, then the last committed URL will not be the
4157 // current URL by the time this navigation commits.
4158 bool has_pending_cross_document_commit =
4159 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214160 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124161
Minggang Wangb9f3fa92021-07-01 15:30:314162 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494163 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524164 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494165 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134166 /*is_same_document_history_load=*/false,
4167 is_embedder_initiated_fenced_frame_navigation,
4168 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424169
4170 // Create the NavigationParams based on |params|.
4171
Hiroki Nakagawa4ed61282021-06-18 05:37:234172 bool is_view_source_mode = entry->IsViewSourceMode();
4173 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294174
Antonio Sartori6984c742021-08-26 08:03:414175 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294176
Hiroki Nakagawa4ed61282021-06-18 05:37:234177 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294178 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254179 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294180
Charlie Reisf21cd182024-08-09 21:44:524181 std::string page_state_data =
4182 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4183
Minggang Wangb9f3fa92021-07-01 15:30:314184 blink::mojom::CommonNavigationParamsPtr common_params =
4185 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214186 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514187 blink::mojom::Referrer::New(params.referrer.url,
4188 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214189 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514190 should_replace_current_entry, params.base_url_for_data_url,
Charlie Reise1d9b8182025-04-02 04:32:124191 actual_navigation_start_time, navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514192 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144193 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414194 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274195 false /* has_text_fragment_token */,
4196 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4197 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514198 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054199 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424200
Minggang Wangb9f3fa92021-07-01 15:30:314201 blink::mojom::CommitNavigationParamsPtr commit_params =
4202 blink::mojom::CommitNavigationParams::New(
Diana Quae845bf2025-04-03 20:12:374203 url::Origin(),
Ari Chivukulac7533522024-05-14 21:52:344204 // The correct storage key will be computed before committing the
4205 // navigation.
4206 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324207 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504208 std::vector<net::RedirectInfo>(), params.post_content_type,
4209 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524210 params.can_load_local_resources, page_state_data,
4211 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134212 /*intended_as_new_entry=*/true,
Charlie Reis99b2eba22025-01-31 19:18:574213 /*pending_history_list_index=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144214 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4215 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134216 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314217 params.should_clear_history_list,
4218 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224219 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134220 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514221 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284222#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134223 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144224#endif
Yoav Weiss8c573952022-11-17 17:35:134225 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154226 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134227 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074228 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134229 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4230 /*origin_agent_cluster=*/false,
4231 /*origin_agent_cluster_left_as_default=*/true,
4232 /*enabled_client_hints=*/
4233 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264234 /*is_cross_site_cross_browsing_context_group=*/false,
4235 /*should_have_sticky_user_activation=*/false,
4236 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134237 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014238 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134239 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584240 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134241 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134242 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284243 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134244 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444245 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424246 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374247 /*view_transition_state=*/std::nullopt,
4248 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054249 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464250 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374251 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054252 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094253 /*load_with_storage_access=*/
4254 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374255 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374256 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484257 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314258 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164259 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174260 node->current_frame_host()->GetCachedPermissionStatuses(),
Charlie Reiscdb798342025-02-14 22:04:464261 /*should_skip_screentshot=*/false,
Alex Moshchukd0d759c22025-05-09 18:18:354262 /*force_new_document_sequence_number=*/false,
4263 /*navigation_metrics_token=*/base::UnguessableToken::Create());
Xiaohan Wang7f8052e02022-01-14 18:44:284264#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424265 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564266 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424267 }
4268#endif
4269
Lucas Furukawa Gadania9c45682019-07-31 22:05:144270 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074271 commit_params->navigation_timing->system_entropy_at_navigation_start =
4272 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4273 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424274
Camille Lamy5193caa2018-10-12 11:59:424275 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4276 std::string extra_headers_crlf;
4277 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094278
Alex Moshchuk9321e6a2022-12-07 21:58:314279 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144280 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084281 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094282 params.initiator_frame_token, params.initiator_process_id,
4283 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214284 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294285 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454286 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344287 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034288 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134289
4290 if (!navigation_request) {
4291 return nullptr;
4292 }
4293
Yao Xiaodc5ed102019-06-04 19:19:094294 navigation_request->set_from_download_cross_origin_redirect(
4295 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554296 navigation_request->set_force_new_browsing_instance(
4297 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514298 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434299 if (params.force_no_https_upgrade) {
4300 navigation_request->set_force_no_https_upgrade();
4301 }
Yao Xiaodc5ed102019-06-04 19:19:094302 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424303}
4304
4305std::unique_ptr<NavigationRequest>
4306NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234307 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574308 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234309 FrameNavigationEntry* frame_entry,
4310 ReloadType reload_type,
4311 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434312 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374313 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334314 int initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:494315 base::TimeTicks actual_navigation_start,
Arthur Sonzognic686e8f2024-01-11 08:36:374316 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134317 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344318 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234319 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434320 // We should never navigate to an existing initial NavigationEntry that is the
4321 // initial NavigationEntry for the initial empty document that hasn't been
4322 // overridden by the synchronous about:blank commit, to preserve previous
4323 // behavior where trying to reload when the main frame is on the initial empty
4324 // document won't result in a navigation.
4325 // See also https://crbug.com/1277414.
4326 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324327
clamyea99ea12018-05-28 13:54:234328 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234329
Ehsan Karamad44fc72112019-02-26 18:15:474330 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4331 // Avoid starting any new navigations since this node is now preparing for
4332 // attaching an inner delegate.
4333 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204334 }
4335
Alex Moshchuk99242832023-05-22 17:21:444336 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4337 dest_url)) {
clamyea99ea12018-05-28 13:54:234338 return nullptr;
4339 }
4340
clamyea99ea12018-05-28 13:54:234341 // This will be used to set the Navigation Timing API navigationStart
4342 // parameter for browser navigations in new tabs (intents, tabs opened through
4343 // "Open link in new tab"). If the navigation must wait on the current
4344 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4345 // will be updated when the BeforeUnload ack is received.
clamyea99ea12018-05-28 13:54:234346 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074347 const auto navigation_start_system_entropy =
4348 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4349 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234350
danakjd83d706d2020-11-25 22:11:124351 // Look for a pending commit that is to another document in this
4352 // FrameTreeNode. If one exists, then the last committed URL will not be the
4353 // current URL by the time this navigation commits.
4354 bool has_pending_cross_document_commit =
4355 frame_tree_node->render_manager()
4356 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494357 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214358 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124359
Minggang Wangb9f3fa92021-07-01 15:30:314360 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124361 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524362 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494363 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494364 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134365 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494366 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424367
4368 // A form submission may happen here if the navigation is a
4369 // back/forward/reload navigation that does a form resubmission.
4370 scoped_refptr<network::ResourceRequestBody> request_body;
4371 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394372 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504373 // entry. This way, it could be directly retrieved here. Right now, it is only
4374 // partially recovered when request.method == "POST" and request.body exists.
4375 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424376 if (frame_entry->method() == "POST") {
4377 request_body = frame_entry->GetPostData(&post_content_type);
4378 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304379 post_content_type = std::string(
4380 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504381 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424382 }
4383
4384 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314385 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514386 entry->ConstructCommonNavigationParams(
4387 *frame_entry, request_body, dest_url,
4388 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Charlie Reisf4d51f402025-05-23 18:00:494389 navigation_type, actual_navigation_start, navigation_start,
Charlie Reise1d9b8182025-04-02 04:32:124390 /*input_start=*/base::TimeTicks());
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514391 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554392 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424393
4394 // TODO(clamy): |intended_as_new_entry| below should always be false once
4395 // Reload no longer leads to this being called for a pending NavigationEntry
4396 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314397 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144398 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404399 *frame_entry, common_params->url, common_params->method,
4400 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144401 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534402 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484403 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134404 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074405 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144406 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074407 commit_params->navigation_timing->system_entropy_at_navigation_start =
4408 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4409 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164410 commit_params->initial_permission_statuses =
4411 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424412
W. James MacLeanb7d6092682022-10-05 15:23:264413 if (common_params->url.IsAboutSrcdoc()) {
4414 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4415 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594416 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264417 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334418 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314419 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144420 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434421 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334422 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4423 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374424 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294425 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4426 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474427 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234428}
4429
[email protected]d202a7c2012-01-04 07:53:474430void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214431 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274432 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404433
Takashi Toyoshimaea534ef22021-07-21 03:27:594434 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404435 // location bar will have up-to-date information about the security style
4436 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134437 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404438
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374439 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574440 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294441}
4442
initial.commit09911bf2008-07-26 23:55:294443// static
[email protected]d202a7c2012-01-04 07:53:474444size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234445 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154446 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214447 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234448}
4449
[email protected]d202a7c2012-01-04 07:53:474450void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224451 if (is_active && needs_reload_)
4452 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214453
4454 if (frame_tree_->is_primary();
4455 auto* cache = GetNavigationEntryScreenshotCache()) {
4456 cache->SetVisible(is_active);
4457 }
initial.commit09911bf2008-07-26 23:55:294458}
4459
[email protected]d202a7c2012-01-04 07:53:474460void NavigationControllerImpl::LoadIfNecessary() {
Charlie Reisf4d51f402025-05-23 18:00:494461 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:034462 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4463 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294464 if (!needs_reload_)
4465 return;
4466
Bo Liucdfa4b12018-11-06 00:21:444467 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4468 needs_reload_type_);
4469
initial.commit09911bf2008-07-26 23:55:294470 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004471 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294472 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004473 if (entry_replaced_by_post_commit_error_) {
4474 // If the current entry is a post commit error, we reload the entry it
4475 // replaced instead. We leave the error entry in place until a commit
4476 // replaces it, but the pending entry points to the original entry in the
4477 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4478 // case that pending_entry_ != entries_[pending_entry_index_].
4479 // Note that this handling is similar to
4480 // `NavigationControllerImpl::Reload()`.
4481 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4482 pending_entry_index_ = GetCurrentEntryIndex();
4483 NavigateToExistingPendingEntry(
4484 ReloadType::NONE,
4485 /*initiator_rfh=*/nullptr,
4486 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494487 /*navigation_api_key=*/nullptr, actual_navigation_start);
Xinghui Lue4e50be2024-05-15 21:46:004488 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134489 NavigateToExistingPendingEntry(
4490 ReloadType::NONE,
4491 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374492 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494493 /*navigation_api_key=*/nullptr, actual_navigation_start);
Rakina Zata Amnie2d31312022-11-18 03:38:454494 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434495 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274496 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344497 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134498 NavigateToExistingPendingEntry(
4499 ReloadType::NONE,
4500 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374501 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494502 /*navigation_api_key=*/nullptr, actual_navigation_start);
avicc872d7242015-08-19 21:26:344503 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434504 // We should never navigate to an existing initial NavigationEntry that is
4505 // the initial NavigationEntry for the initial empty document that hasn't
4506 // been overridden by the synchronous about:blank commit, to preserve
4507 // legacy behavior where trying to reload when the main frame is on the
4508 // initial empty document won't result in a navigation. See also
4509 // https://crbug.com/1277414. If there is something to reload, the
4510 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4511 // it here.
avicc872d7242015-08-19 21:26:344512 needs_reload_ = false;
4513 }
initial.commit09911bf2008-07-26 23:55:294514}
4515
Kevin McNeeccca6172021-10-19 17:11:144516base::WeakPtr<NavigationHandle>
4517NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364518 RenderFrameHost* render_frame_host,
4519 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364520 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134521 RenderFrameHostImpl* rfhi =
4522 static_cast<RenderFrameHostImpl*>(render_frame_host);
Andrew Verge754c70a2025-04-17 17:19:194523 std::unique_ptr<NavigationRequest> navigation_request =
4524 CreateNavigationRequestForErrorPage(rfhi, url, error_page_html,
4525 /*is_post_commit_error_page=*/true);
4526 if (!navigation_request) {
Kevin McNeeccca6172021-10-19 17:11:144527 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114528 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584529
Rakina Zata Amni919b7922020-12-11 09:03:134530 FrameTreeNode* node = rfhi->frame_tree_node();
Charlie Reis09952ee2022-12-08 16:35:074531 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414532 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144533
Andrew Verge754c70a2025-04-17 17:19:194534 // TODO(crbug.com/406729265): LoadPostCommitErrorPage() does not initiate a
4535 // navigation via Navigator::Navigate(). We should fix that, so that
4536 // post-commit error page navigations don't bypass other important checks in
4537 // this function.
Kevin McNeeccca6172021-10-19 17:11:144538 // Calling BeginNavigation may destroy the NavigationRequest.
4539 base::WeakPtr<NavigationRequest> created_navigation_request(
4540 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414541 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144542 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414543}
4544
Andrew Verge754c70a2025-04-17 17:19:194545void NavigationControllerImpl::NavigateFrameToErrorPage(
4546 RenderFrameHostImpl* render_frame_host_impl,
4547 const GURL& url,
4548 const std::string& error_page_html) {
4549 // For now, this function can only be used for fenced frame roots. In the
4550 // future, it will be updated to work for any frame.
4551 // TODO(crbug.com/406729265): Implement this method for all types of frames,
4552 // including main frames and other subframe types.
4553 CHECK(render_frame_host_impl->IsFencedFrameRoot());
4554
4555 std::unique_ptr<NavigationRequest> navigation_request =
4556 CreateNavigationRequestForErrorPage(render_frame_host_impl, url,
4557 error_page_html,
4558 /*is_post_commit_error_page=*/false);
4559 if (!navigation_request) {
4560 return;
4561 }
4562
4563 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
4564 node->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
4565}
4566
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574567void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214568 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094569 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154570 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144571 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294572}
4573
[email protected]d202a7c2012-01-04 07:53:474574void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364575 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584576 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474577 // represent a no-committed-entry state.
4578 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364579 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584580 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474581 // if `entries_` contains pre-existing entries from the NavigationController
4582 // before restore, which would not be removed and will be at the front of the
4583 // entries list, causing the index to be off by the amount of pre-existing
4584 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294585 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294586}
[email protected]765b35502008-08-21 00:51:204587
arthursonzogni69a6a1b2019-09-17 09:23:004588void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004589 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4590}
4591
4592void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4593 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474594 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104595 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4596 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294597 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474598 return;
Michael Thiessenc5676d22019-09-25 22:32:104599 }
avi45a72532015-04-07 21:01:454600 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314601
4602 if (!delegate_)
4603 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374604 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484605}
4606
avi7c6f35e2015-05-08 17:52:384607int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4608 int nav_entry_id) const {
4609 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4610 if (entries_[i]->GetUniqueID() == nav_entry_id)
4611 return i;
4612 }
4613 return -1;
4614}
4615
[email protected]d202a7c2012-01-04 07:53:474616void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574617 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254618 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574619 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594620 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254621 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374622 // Normally, cloning a NavigationEntryImpl results in sharing
4623 // FrameNavigationEntries between the original and the clone. However, when
4624 // cloning from a different NavigationControllerImpl, we want to fork the
4625 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374626 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594627 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254628 }
Rakina Zata Amnie2d31312022-11-18 03:38:454629 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274630 DCHECK(pending_entry_index_ == -1 ||
4631 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254632}
[email protected]c5b88d82012-10-06 17:03:334633
4634void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184635 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334636 get_timestamp_callback_ = get_timestamp_callback;
4637}
[email protected]8ff00d72012-10-23 19:12:214638
Shivani Sharmaffb32b82019-04-09 16:58:474639// History manipulation intervention:
4640void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474641 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564642 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404643 bool is_renderer_initiated,
4644 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564645 // Note that for a subframe,
4646 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454647 // gesture happened in any subframe (propagated to main frame) or in the main
4648 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564649 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274650 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474651 return;
4652 }
4653 if (last_committed_entry_index_ == -1)
4654 return;
4655
Shivani Sharmac4cc8922019-04-18 03:11:174656 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474657
Alexander Timine3ec4192020-04-20 16:39:404658 // Log UKM with the URL we are navigating away from.
4659 ukm::builders::HistoryManipulationIntervention(
4660 previous_page_load_ukm_source_id)
4661 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474662}
4663
Shivani Sharmac4cc8922019-04-18 03:11:174664void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4665 int reference_index,
4666 bool skippable) {
4667 auto* reference_entry = GetEntryAtIndex(reference_index);
4668 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4669
4670 int64_t document_sequence_number =
4671 reference_entry->root_node()->frame_entry->document_sequence_number();
4672 for (int index = 0; index < GetEntryCount(); index++) {
4673 auto* entry = GetEntryAtIndex(index);
4674 if (entry->root_node()->frame_entry->document_sequence_number() ==
4675 document_sequence_number) {
4676 entry->set_should_skip_on_back_forward_ui(skippable);
4677 }
4678 }
4679}
4680
arthursonzogni66f711c2019-10-08 14:40:364681std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4682NavigationControllerImpl::ReferencePendingEntry() {
4683 DCHECK(pending_entry_);
4684 auto pending_entry_ref =
4685 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4686 pending_entry_refs_.insert(pending_entry_ref.get());
4687 return pending_entry_ref;
4688}
4689
4690void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4691 // Ignore refs that don't correspond to the current pending entry.
4692 auto it = pending_entry_refs_.find(ref);
4693 if (it == pending_entry_refs_.end())
4694 return;
4695 pending_entry_refs_.erase(it);
4696
4697 if (!pending_entry_refs_.empty())
4698 return;
4699
4700 // The pending entry may be deleted before the last PendingEntryRef.
4701 if (!pending_entry_)
4702 return;
4703
4704 // We usually clear the pending entry when the matching NavigationRequest
4705 // fails, so that an arbitrary URL isn't left visible above a committed page.
4706 //
4707 // However, we do preserve the pending entry in some cases, such as on the
4708 // initial navigation of an unmodified blank tab. We also allow the delegate
4709 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4710 // user edit the URL and try again. This may be useful in cases that the
4711 // committed page cannot be attacker-controlled. In these cases, we still
4712 // allow the view to clear the pending entry and typed URL if the user
4713 // requests (e.g., hitting Escape with focus in the address bar).
4714 //
4715 // Do not leave the pending entry visible if it has an invalid URL, since this
4716 // might be formatted in an unexpected or unsafe way.
4717 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364718 bool should_preserve_entry =
4719 (pending_entry_ == GetVisibleEntry()) &&
4720 pending_entry_->GetURL().is_valid() &&
4721 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4722 if (should_preserve_entry)
4723 return;
4724
4725 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374726 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364727}
4728
Titouan Rigoudy6ec70402021-02-02 15:42:194729std::unique_ptr<PolicyContainerPolicies>
4730NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394731 RenderFrameHostImpl* rfh,
4732 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214733 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174734 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214735 if (navigation_encountered_error) {
4736 // We should never reload the policy container of an error page from
4737 // history, see https://crbug.com/364773822.
4738 return nullptr;
4739 }
4740
Antonio Sartori78a749f2020-11-30 12:03:394741 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454742 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394743 FrameNavigationEntry* previous_frame_entry =
4744 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4745
Alison Gale770f3fc2024-04-27 00:39:584746 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394747 // ensure we always have a FrameNavigationEntry here.
4748 if (!previous_frame_entry)
4749 return nullptr;
4750
Titouan Rigoudy6ec70402021-02-02 15:42:194751 const PolicyContainerPolicies* previous_policies =
4752 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394753
Titouan Rigoudy6ec70402021-02-02 15:42:194754 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394755 return nullptr;
4756
4757 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234758 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394759 }
4760
Titouan Rigoudy72f892d2022-05-02 18:21:234761 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394762}
4763
Charlie Reis99b2eba22025-01-31 19:18:574764void NavigationControllerImpl::BroadcastHistoryIndexAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504765 OPTIONAL_TRACE_EVENT2(
Charlie Reis99b2eba22025-01-31 19:18:574766 "content", "NavigationControllerImpl::BroadcastHistoryIndexAndLength",
4767 "history_index", GetLastCommittedEntryIndex(), "history_length",
Hayato Ito2c8c08d02021-06-23 03:38:434768 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504769
Charlie Reis99b2eba22025-01-31 19:18:574770 int history_index = GetLastCommittedEntryIndex();
Kevin McNee7705fe82024-11-07 18:56:314771 int history_length = GetEntryCount();
Charlie Reis99b2eba22025-01-31 19:18:574772 auto callback = [history_index, history_length](RenderViewHostImpl* rvh) {
Kevin McNee7705fe82024-11-07 18:56:314773 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
Charlie Reis99b2eba22025-01-31 19:18:574774 broadcast->SetHistoryIndexAndLength(history_index, history_length);
Kevin McNee7705fe82024-11-07 18:56:314775 }
4776 };
Ali Hijazid87307d2022-11-07 20:15:034777 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504778}
4779
4780void NavigationControllerImpl::DidAccessInitialMainDocument() {
4781 // We may have left a failed browser-initiated navigation in the address bar
4782 // to let the user edit it and try again. Clear it now that content might
4783 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034784 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504785 DiscardPendingEntry(false);
4786
4787 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374788 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504789}
4790
4791void NavigationControllerImpl::UpdateStateForFrame(
4792 RenderFrameHostImpl* rfhi,
4793 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564794 OPTIONAL_TRACE_EVENT1("content",
4795 "NavigationControllerImpl::UpdateStateForFrame",
4796 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504797 // The state update affects the last NavigationEntry associated with the given
4798 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4799 // in the case of an UpdateState from a frame being swapped out). We track
4800 // which entry this is in the RenderFrameHost's nav_entry_id.
4801 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4802 if (!entry)
4803 return;
4804
4805 FrameNavigationEntry* frame_entry =
4806 entry->GetFrameEntry(rfhi->frame_tree_node());
4807 if (!frame_entry)
4808 return;
4809
4810 // The SiteInstance might not match if we do a cross-process navigation with
4811 // replacement (e.g., auto-subframe), in which case the swap out of the old
4812 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4813 // has already been replaced and destroyed.
4814 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4815 return;
4816
4817 if (page_state == frame_entry->page_state())
4818 return; // Nothing to update.
4819
4820 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4821
4822 // The document_sequence_number and item_sequence_number recorded in the
4823 // FrameNavigationEntry should not differ from the one coming with the update,
4824 // since it must come from the same document. Do not update it if a difference
4825 // is detected, as this indicates that |frame_entry| is not the correct one.
4826 blink::ExplodedPageState exploded_state;
4827 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4828 return;
4829
4830 if (exploded_state.top.document_sequence_number !=
4831 frame_entry->document_sequence_number() ||
4832 exploded_state.top.item_sequence_number !=
4833 frame_entry->item_sequence_number()) {
4834 return;
4835 }
4836
4837 frame_entry->SetPageState(page_state);
4838 NotifyEntryChanged(entry);
4839}
4840
Nate Chapina2c881f52023-11-07 17:02:094841namespace {
4842
4843// The caller is responsible for ensuring the entry is same-origin to the
4844// origin to be committed.
4845blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4846 FrameNavigationEntry* frame_entry,
4847 int64_t pending_document_sequence_number) {
4848 blink::ExplodedPageState exploded_state;
4849 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4850 &exploded_state)) {
4851 return nullptr;
4852 }
4853 blink::ExplodedFrameState frame_state = exploded_state.top;
4854
4855 // If the document represented by this FNE hid its full url from appearing in
4856 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4857 // in the navigation API as well (unless we're navigating to that document).
4858 std::u16string url;
4859 if (pending_document_sequence_number ==
4860 frame_entry->document_sequence_number() ||
4861 !frame_entry->protect_url_in_navigation_api()) {
4862 url = frame_state.url_string.value_or(std::u16string());
4863 }
4864
4865 return blink::mojom::NavigationApiHistoryEntry::New(
4866 frame_state.navigation_api_key.value_or(std::u16string()),
4867 frame_state.navigation_api_id.value_or(std::u16string()), url,
4868 frame_state.item_sequence_number, frame_state.document_sequence_number,
4869 frame_state.navigation_api_state);
4870}
4871
4872} // namespace
4873
Domenic Denicolacd30f5f82022-03-16 21:48:014874std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4875NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574876 Direction direction,
4877 int entry_index,
4878 const url::Origin& pending_origin,
4879 FrameTreeNode* node,
4880 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304881 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094882 int64_t pending_document_sequence_number,
4883 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014884 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454885 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174886 // Don't process the initial entry.
4887 DCHECK_EQ(GetEntryCount(), 1);
4888 return entries;
4889 }
Nate Chapind1fe3612021-04-16 20:45:574890 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304891 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574892 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4893 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094894 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574895 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414896 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574897 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014898 // An entry should only appear in the navigation API entries if it is for
4899 // the same origin as the document being committed. Check the committed
4900 // origin, or if that is not available (during restore), check against the
4901 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584902 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094903 // once we can be sure that entries with the same ISN will never be
4904 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414905 url::Origin frame_entry_origin =
4906 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4907 frame_entry->url(),
4908 frame_entry->initiator_origin().value_or(url::Origin())));
4909 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574910 break;
4911 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4912 continue;
Nate Chapina2c881f52023-11-07 17:02:094913 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4914 ToNavigationApiHistoryEntry(frame_entry,
4915 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304916 DCHECK(entry->url.empty() ||
4917 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574918 entries.push_back(std::move(entry));
4919 previous_item_sequence_number = frame_entry->item_sequence_number();
4920 }
4921 }
4922 // If |entries| was constructed by iterating backwards from
4923 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4924 // earliest-at-the-front. Reverse it.
4925 if (direction == Direction::kBack)
4926 std::reverse(entries.begin(), entries.end());
4927 return entries;
4928}
4929
Domenic Denicolacd30f5f82022-03-16 21:48:014930blink::mojom::NavigationApiHistoryEntryArraysPtr
4931NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554932 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574933 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404934 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444935 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404936 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574937
Nate Chapind1fe3612021-04-16 20:45:574938 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554939 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574940
Nate Chapine82339d02022-05-03 23:48:254941 // NOTE: |entry_index| is the index where this entry will commit if no
4942 // modifications are made between now and DidCommitNavigation. This is used to
4943 // walk |entries_| and determine which entries should be exposed by the
4944 // navigation API. It is important to calculate this correctly, because blink
4945 // will cancel a same-document history commit if it's not present in the
4946 // entries blink knows about.
4947 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574948 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304949 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254950 bool will_create_new_entry = false;
4951 if (GetPendingEntryIndex() != -1) {
4952 entry_index = GetPendingEntryIndex();
4953 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4954 pending_item_sequence_number = frame_entry->item_sequence_number();
4955 pending_document_sequence_number =
4956 frame_entry->document_sequence_number();
4957 }
4958 } else if (request &&
4959 !NavigationTypeUtils::IsReload(
4960 request->common_params().navigation_type) &&
4961 !NavigationTypeUtils::IsHistory(
4962 request->common_params().navigation_type) &&
4963 !request->common_params().should_replace_current_entry &&
4964 !request->common_params()
4965 .is_history_navigation_in_new_child_frame) {
4966 will_create_new_entry = true;
4967 entry_index = GetLastCommittedEntryIndex() + 1;
4968 // Don't set pending_item_sequence_number or
4969 // pending_document_sequence_number in this case - a new unique isn/dsn will
4970 // be calculated in the renderer later.
4971 } else if (GetLastCommittedEntryIndex() != -1) {
4972 entry_index = GetLastCommittedEntryIndex();
4973 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574974 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304975 pending_document_sequence_number =
4976 frame_entry->document_sequence_number();
4977 }
Nate Chapind1fe3612021-04-16 20:45:574978 }
4979
Domenic Denicolacd30f5f82022-03-16 21:48:014980 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254981 if (entry_index == -1) {
4982 // TODO(rakina): Exit early when there is no last committed entry.
4983 // Remove when InitialNavigationEntry ships.
4984 return entry_arrays;
4985 }
4986
Nate Chapina2c881f52023-11-07 17:02:094987 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014988 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574989 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094990 pending_item_sequence_number, pending_document_sequence_number,
4991 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574992
4993 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094994 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574995 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014996 entry_arrays->forward_entries =
4997 PopulateSingleNavigationApiHistoryEntryVector(
4998 Direction::kForward, entry_index, pending_origin, node,
4999 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:095000 pending_document_sequence_number, forwardmost_index);
5001 }
5002
5003 // If the previous entry is within the block of contiguous entries being
5004 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:255005 FrameNavigationEntry* previous_entry = nullptr;
5006 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:055007 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
5008 .initiator_frame_tree_node_id();
5009 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:255010 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
5011 previous_entry = initiator_node->frame_tree()
5012 .controller()
5013 .GetLastCommittedEntry()
5014 ->GetFrameEntry(initiator_node);
5015 }
5016 } else if (GetLastCommittedEntryIndex() != -1 &&
5017 GetLastCommittedEntryIndex() >= backmost_index &&
5018 GetLastCommittedEntryIndex() <= forwardmost_index) {
5019 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
5020 }
5021 if (previous_entry) {
5022 url::Origin previous_entry_origin =
5023 previous_entry->committed_origin().value_or(url::Origin::Resolve(
5024 previous_entry->url(),
5025 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:585026 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:255027 // once we can be sure that entries with the same ISN will never be
5028 // cross-origin.
5029 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
5030 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
5031 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:095032 }
Nate Chapind1fe3612021-04-16 20:45:575033 }
Nate Chapinc06cf80a2023-11-18 01:12:255034
Nate Chapin4e657a472022-02-06 03:38:375035 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:575036}
5037
Nate Chapinfbfe5af2021-06-10 17:22:085038NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:575039NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085040 FrameNavigationEntry* current_entry,
5041 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:575042 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:085043 if (!target_entry || !target_entry->committed_origin())
5044 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:085045 if (!current_entry->committed_origin()->IsSameOriginWith(
5046 *target_entry->committed_origin())) {
5047 return HistoryNavigationAction::kStopLooking;
5048 }
5049
5050 // NOTE: We don't actually care between kSameDocument and
5051 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:575052 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:085053 return HistoryNavigationAction::kDifferentDocument;
5054 return HistoryNavigationAction::kKeepLooking;
5055}
5056
Domenic Denicolacc094fb2022-03-16 23:40:575057void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:205058 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:375059 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:145060 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:495061 const std::string& key,
5062 base::TimeTicks actual_navigation_start) {
Nate Chapinbf682fa32022-09-26 22:41:205063 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:085064 FrameNavigationEntry* current_entry =
5065 GetLastCommittedEntry()->GetFrameEntry(node);
Nate Chapin0dbc93af2025-03-28 17:02:525066 if (!current_entry || !current_entry->committed_origin()) {
Nate Chapinfbfe5af2021-06-10 17:22:085067 return;
Nate Chapin0dbc93af2025-03-28 17:02:525068 }
Nate Chapinfbfe5af2021-06-10 17:22:085069
Alison Gale47d1537d2024-04-19 21:31:465070 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:135071 // when `navigation.traverseTo()` is called.
5072
Nate Chapinfbfe5af2021-06-10 17:22:085073 // We want to find the nearest matching entry that is contiguously
5074 // same-instance and same-origin. Check back first, then forward.
5075 // TODO(japhet): Link spec here once it exists.
5076 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:575077 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085078 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5079 if (result == HistoryNavigationAction::kStopLooking)
5080 break;
5081 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495082 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5083 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085084 return;
5085 }
5086 }
5087 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:575088 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085089 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5090 if (result == HistoryNavigationAction::kStopLooking)
5091 break;
5092 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495093 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5094 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085095 return;
5096 }
5097 }
Nate Chapinbf682fa32022-09-26 22:41:205098
5099 // If we fall through to here, a matching NavigationEntry couldn't be found.
5100 // Notify the renderer that the navigation was cancelled.
5101 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
5102 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:085103}
5104
Domenic Denicolacc094fb2022-03-16 23:40:575105bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:305106 network::mojom::ReferrerPolicy referrer_policy) {
5107 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
5108 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
5109}
5110
shivanigithubf405bf0d2021-11-05 17:58:335111bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
5112 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:315113 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:335114 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:545115 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:465116 // The preview mode appears as prerendered page in renderers, and
5117 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:035118 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:515119 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:335120 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:545121}
5122
Julie Jeongeun Kim0e242242022-11-30 10:45:095123void NavigationControllerImpl::DidChangeReferrerPolicy(
5124 FrameTreeNode* node,
5125 network::mojom::ReferrerPolicy referrer_policy) {
5126 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
5127 if (!entry)
5128 return;
5129
5130 // The FrameNavigationEntry may want to change whether to protect its url
5131 // in the navigation API when the referrer policy changes.
5132 entry->set_protect_url_in_navigation_api(
5133 ShouldProtectUrlInNavigationApi(referrer_policy));
5134}
5135
Minoru Chikamune646eba42025-04-14 01:25:035136void NavigationControllerImpl::CheckPotentialNavigationReentrancy() {
Minoru Chikamune13ab4de2025-05-14 21:54:075137 if (can_be_in_navigate_to_pending_entry_) {
Minoru Chikamune646eba42025-04-14 01:25:035138 // This DumpWithoutCrashing is an investigation code for
5139 // https://crbug.com/396998476.
5140 base::debug::DumpWithoutCrashing();
5141 }
5142}
5143
Andrew Verge754c70a2025-04-17 17:19:195144std::unique_ptr<NavigationRequest>
5145NavigationControllerImpl::CreateNavigationRequestForErrorPage(
5146 RenderFrameHostImpl* render_frame_host_impl,
5147 const GURL& url,
5148 const std::string& error_page_html,
5149 bool is_post_commit_error_page) {
5150 // Only active documents can load error pages:
5151 // - If the document is in pending deletion, the browser already committed to
5152 // destroying this RenderFrameHost so ignore loading the error page.
5153 // - If the document is in back-forward cache, it's not allowed to navigate as
5154 // it should remain frozen. Ignore the request and evict the document from
5155 // back-forward cache.
5156 // - If the document is prerendering, it can navigate but when loading error
5157 // pages, cancel prerendering.
5158 if (render_frame_host_impl->IsInactiveAndDisallowActivation(
5159 is_post_commit_error_page
5160 ? DisallowActivationReasonId::kLoadPostCommitErrorPage
5161 : DisallowActivationReasonId::kBrowserInitiatedErrorPage)) {
5162 return nullptr;
5163 }
5164
5165 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
5166
5167 blink::mojom::CommonNavigationParamsPtr common_params =
5168 blink::CreateCommonNavigationParams();
5169 // |url| might be empty, such as when this method is called before
5170 // the frame actually committed (e.g. iframe with "src" set to a
5171 // slow-responding URL). We should rewrite the URL to about:blank in this
5172 // case, as the renderer will only think a page is an error page if it has a
5173 // non-empty unreachable URL.
5174 common_params->url = url.is_empty() ? GURL("about:blank") : url;
5175
5176 // Loading an error page via LoadPostCommitErrorPage() performs a temporary
5177 // replacement of the entire NavigationEntry and swaps it back in later.
5178 // All other error page types should permanently replace the current entry.
5179 if (!is_post_commit_error_page) {
5180 common_params->should_replace_current_entry = true;
5181 }
5182
5183 blink::mojom::CommitNavigationParamsPtr commit_params =
5184 blink::CreateCommitNavigationParams();
5185 commit_params->original_url = common_params->url;
5186
5187 commit_params->navigation_timing->system_entropy_at_navigation_start =
5188 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
5189 node, blink::mojom::SystemEntropy::kNormal);
5190
5191 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
5192 // error pages.
5193 commit_params->frame_policy = node->pending_frame_policy();
5194
5195 std::unique_ptr<NavigationRequest> navigation_request =
5196 NavigationRequest::CreateBrowserInitiated(
5197 node, std::move(common_params), std::move(commit_params),
5198 false /* was_opener_suppressed */, "" /* extra_headers */,
5199 nullptr /* frame_entry */, nullptr /* entry */,
5200 false /* is_form_submission */, nullptr /* navigation_ui_data */,
5201 std::nullopt /* impression */, false /* is_pdf */);
5202 if (is_post_commit_error_page) {
5203 navigation_request->set_browser_initiated_error_navigation_type(
5204 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit);
5205 } else {
5206 navigation_request->set_browser_initiated_error_navigation_type(
5207 NavigationRequest::BrowserInitiatedErrorNavigationType::kRegular);
5208 }
5209 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
5210 navigation_request->set_error_page_html(error_page_html);
5211 return navigation_request;
5212}
5213
[email protected]8ff00d72012-10-23 19:12:215214} // namespace content