blob: 5a3c601b50583b0918cd9ec39bcb1095e001a007 [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"
Rakina Zata Amni627360d2022-02-24 00:53:4043#include "base/debug/dump_without_crashing.h"
Avi Drissmanadac21992023-01-11 23:46:3944#include "base/functional/bind.h"
initial.commit09911bf2008-07-26 23:55:2945#include "base/logging.h"
asvitkine30330812016-08-30 04:01:0846#include "base/metrics/histogram_macros.h"
Kevin McNee37a109792025-04-14 21:16:3847#include "base/not_fatal_until.h"
Charlie Reis23c26da2022-01-29 00:57:4748#include "base/numerics/safe_conversions.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3949#include "base/strings/escape.h"
[email protected]348fbaac2013-06-11 06:31:5150#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0051#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3752#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0053#include "base/trace_event/optional_trace_event.h"
ssid3e765612015-01-28 04:03:4254#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0855#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5956#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2857#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1858#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3959#include "content/browser/blob_storage/chrome_blob_storage_context.h"
William Liu055a3542023-04-02 17:21:1960#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3161#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4162#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0463#include "content/browser/dom_storage/session_storage_namespace_impl.h"
Nate Chapinc06cf80a2023-11-18 01:12:2564#include "content/browser/preloading/prerender/prerender_host.h"
Sharon Yang242ef822023-05-15 21:07:3265#include "content/browser/process_lock.h"
Mingyu Lei68f34412023-08-21 07:31:3766#include "content/browser/renderer_host/back_forward_cache_impl.h"
danakjc492bf82020-09-09 20:02:4467#include "content/browser/renderer_host/debug_urls.h"
68#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0069#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3370#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4471#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5772#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4473#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1974#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
75#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
Khushal Sagar94ea2dc2024-08-06 17:15:2676#include "content/browser/renderer_host/navigation_transitions/navigation_transition_config.h"
danakjc492bf82020-09-09 20:02:4477#include "content/browser/renderer_host/navigator.h"
Takashi Toyoshima4dad2c12023-11-13 10:04:4678#include "content/browser/renderer_host/page_delegate.h"
danakjc492bf82020-09-09 20:02:4479#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0080#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0781#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3282#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3383#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4284#include "content/common/content_constants_internal.h"
Rakina Zata Amni84a859df2024-06-07 15:56:3285#include "content/common/content_navigation_policy.h"
Nate Chapind1fe3612021-04-16 20:45:5786#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5187#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1188#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1989#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1190#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4691#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0092#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4793#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5894#include "content/public/browser/render_widget_host.h"
95#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1096#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3497#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1998#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3899#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:10100#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47101#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43102#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59103#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36104#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57105#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18106#include "services/metrics/public/cpp/ukm_builders.h"
107#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17108#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37109#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44110#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58111#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39112#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30113#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21114#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06115#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43116#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50117#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31118#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51119#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46120#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26121#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29122
[email protected]8ff00d72012-10-23 19:12:21123namespace content {
[email protected]e9ba4472008-09-14 15:42:43124namespace {
125
126// Invoked when entries have been pruned, or removed. For example, if the
127// current entries are [google, digg, yahoo], with the current entry google,
128// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47129void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50130 int index,
[email protected]c12bf1a12008-09-17 16:28:49131 int count) {
[email protected]8ff00d72012-10-23 19:12:21132 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50133 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49134 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14135 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43136}
137
[email protected]e9ba4472008-09-14 15:42:43138// Configure all the NavigationEntries in entries for restore. This resets
139// the transition type to reload and makes sure the content state isn't empty.
140void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57141 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48142 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47143 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43144 // Use a transition type of reload so that we don't incorrectly increase
145 // the typed count.
Lei Zhang96031532019-10-10 19:05:47146 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
147 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43148 }
149}
150
[email protected]bf70edce2012-06-20 22:32:22151// Determines whether or not we should be carrying over a user agent override
152// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57153bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22154 return last_entry && last_entry->GetIsOverridingUserAgent();
155}
156
Camille Lamy5193caa2018-10-12 11:59:42157// Determines whether to override user agent for a navigation.
158bool ShouldOverrideUserAgent(
159 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57160 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42161 switch (override_user_agent) {
162 case NavigationController::UA_OVERRIDE_INHERIT:
163 return ShouldKeepOverride(last_committed_entry);
164 case NavigationController::UA_OVERRIDE_TRUE:
165 return true;
166 case NavigationController::UA_OVERRIDE_FALSE:
167 return false;
Camille Lamy5193caa2018-10-12 11:59:42168 }
Peter Boströmfc7ddc182024-10-31 19:37:21169 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42170}
171
Rakina Zata Amni312822d72021-06-04 16:13:37172// Returns true if this navigation should be treated as a reload. For e.g.
Liang Zhao0351d762024-11-13 00:10:07173// clicking on a link which results in a navigation to the last committed URL
174// (but wasn't converted to do a replacement navigation in the renderer), etc.
175// This intentionally excludes navigating to the last committed URL via the
176// address bar, so that the current scroll position is not restored.
Fergal Daly766177d2020-07-07 07:54:04177// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
178// |base_url_for_data_url|, |transition_type| correspond to the new navigation
179// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
180// navigation that committed.
181bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
182 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57183 const GURL& virtual_url,
184 const GURL& base_url_for_data_url,
185 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57186 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37187 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57188 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37189 // Navigations intended to do a replacement shouldn't be converted to do a
190 // reload.
191 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28192 return false;
clamy0a656e42018-02-06 18:18:28193 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45194 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55195 return false;
196
arthursonzogni7a8243682017-12-14 16:41:42197 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28198 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42199 return false;
200
Liang Zhao0351d762024-11-13 00:10:07201 // Same URL navigations from the address bar should only be treated as reloads
202 // if PAGE_TRANSITION_RELOAD is set (not for PAGE_TRANSITION_TYPED or
203 // PAGE_TRANSITION_LINK). In non-address-bar cases, PAGE_TRANSITION_TYPED
204 // and PAGE_TRANSITION_LINK can be treated as reloads.
clamy0a656e42018-02-06 18:18:28205 bool transition_type_can_be_converted = false;
Liang Zhao0351d762024-11-13 00:10:07206 if (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
207 if (ui::PageTransitionCoreTypeIs(transition_type,
208 ui::PAGE_TRANSITION_RELOAD)) {
209 transition_type_can_be_converted = true;
210 }
211 } else {
212 if (ui::PageTransitionCoreTypeIs(transition_type,
213 ui::PAGE_TRANSITION_TYPED) ||
214 ui::PageTransitionCoreTypeIs(transition_type,
215 ui::PAGE_TRANSITION_LINK)) {
216 transition_type_can_be_converted = true;
217 }
ananta3bdd8ae2016-12-22 17:11:55218 }
clamy0a656e42018-02-06 18:18:28219 if (!transition_type_can_be_converted)
220 return false;
221
222 // This check is required for cases like view-source:, etc. Here the URL of
223 // the navigation entry would contain the url of the page, while the virtual
224 // URL contains the full URL including the view-source prefix.
225 if (virtual_url != last_committed_entry->GetVirtualURL())
226 return false;
227
Fergal Daly766177d2020-07-07 07:54:04228 // Check that the URLs match.
229 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
230 // If there's no frame entry then by definition the URLs don't match.
231 if (!frame_entry)
232 return false;
233
234 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28235 return false;
236
237 // This check is required for Android WebView loadDataWithBaseURL. Apps
238 // can pass in anything in the base URL and we need to ensure that these
239 // match before classifying it as a reload.
240 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
241 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
242 return false;
ananta3bdd8ae2016-12-22 17:11:55243 }
244
clamy0a656e42018-02-06 18:18:28245 // Skip entries with SSL errors.
246 if (last_committed_entry->ssl_error())
247 return false;
248
249 // Don't convert to a reload when the last navigation was a POST or the new
250 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04251 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28252 return false;
253
254 return true;
ananta3bdd8ae2016-12-22 17:11:55255}
256
Arthur Sonzognic686e8f2024-01-11 08:36:37257std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12258 const mojom::DidCommitProvisionalLoadParams& params,
259 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32260 // Error pages commit in an opaque origin, yet have the real URL that resulted
261 // in an error as the |params.url|. Since successful reload of an error page
262 // should commit in the correct origin, setting the opaque origin on the
263 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17264 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37265 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32266
Arthur Sonzognic686e8f2024-01-11 08:36:37267 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32268}
269
Alex Moshchuk99242832023-05-22 17:21:44270bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42271 const GURL& virtual_url,
272 const GURL& dest_url) {
273 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44274 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
275 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42276 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
277 << virtual_url.possibly_invalid_spec();
278 return false;
279 }
280
281 // Don't attempt to navigate to non-empty invalid URLs.
282 if (!dest_url.is_valid() && !dest_url.is_empty()) {
283 LOG(WARNING) << "Refusing to load invalid URL: "
284 << dest_url.possibly_invalid_spec();
285 return false;
286 }
287
288 // The renderer will reject IPC messages with URLs longer than
289 // this limit, so don't attempt to navigate with a longer URL.
290 if (dest_url.spec().size() > url::kMaxURLChars) {
291 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
292 << " characters.";
293 return false;
294 }
295
Aaron Colwell33109c592020-04-21 21:31:19296 // Reject renderer debug URLs because they should have been handled before
297 // we get to this point. This check handles renderer debug URLs
298 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
299 // provides defense-in-depth if a renderer debug URL manages to get here via
300 // some other path. We want to reject the navigation here so it doesn't
301 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30302 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19303 LOG(WARNING) << "Refusing to load renderer debug URL: "
304 << dest_url.possibly_invalid_spec();
305 return false;
306 }
307
Alex Moshchuk99242832023-05-22 17:21:44308 // Guests only support navigations to known-safe schemes. This check already
309 // exists in the extensions layer, where it also dispatches proper events to
310 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
311 // for defense-in-depth to ensure that no other places in the codebase
312 // accidentally navigate guests to schemes such as WebUI, which is not
313 // supported. See https://crbug.com/1444221.
314 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
315 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
316 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
317 !dest_url.SchemeIs(url::kAboutScheme)) {
318 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
319 << dest_url.possibly_invalid_spec();
320 return false;
321 }
322 }
323
Camille Lamy5193caa2018-10-12 11:59:42324 return true;
325}
326
Mikel Astizba9cf2fd2017-12-17 10:38:10327// See replaced_navigation_entry_data.h for details: this information is meant
328// to ensure |*output_entry| keeps track of its original URL (landing page in
329// case of server redirects) as it gets replaced (e.g. history.replaceState()),
330// without overwriting it later, for main frames.
331void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57332 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10333 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17334 if (output_entry->GetReplacedEntryData().has_value() ||
335 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10336 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17337 }
Mikel Astizba9cf2fd2017-12-17 10:38:10338
339 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57340 data.first_committed_url = replaced_entry->GetURL();
341 data.first_timestamp = replaced_entry->GetTimestamp();
342 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29343 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10344}
345
Minggang Wangb9f3fa92021-07-01 15:30:31346blink::mojom::NavigationType GetNavigationType(
347 const GURL& old_url,
348 const GURL& new_url,
349 ReloadType reload_type,
350 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52351 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31352 bool has_pending_cross_document_commit,
353 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49354 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13355 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49356 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23357 // Reload navigations
358 switch (reload_type) {
359 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31360 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23361 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31362 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23363 case ReloadType::NONE:
364 break; // Fall through to rest of function.
365 }
366
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08367 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31368 return entry->GetHasPostData()
369 ? blink::mojom::NavigationType::RESTORE_WITH_POST
370 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23371 }
372
danakjb952ef12021-01-14 19:58:49373 const bool can_be_same_document =
374 // A pending cross-document commit means this navigation will not occur in
375 // the current document, as that document would end up being replaced in
376 // the meantime.
377 !has_pending_cross_document_commit &&
378 // If the current document is an error page, we should always treat it as
379 // a different-document navigation so that we'll attempt to load the
380 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49381 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13382 // If the navigation is an embedder-initiated navigation of a fenced
383 // frame root (i.e. enters a fenced frame tree from outside),
384 // same-document navigations should be disabled because we don't want to
385 // allow information to be joined across multiple embedder-initiated
386 // fenced frame navigations (which may contain separate cross-site data).
387 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49388 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
389 // same-document navigations should be disabled because we want to force
390 // the creation of a new browsing context group.
391 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12392
clamyea99ea12018-05-28 13:54:23393 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52394 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12395 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31396 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
397 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23398 }
399 DCHECK(!is_same_document_history_load);
400
401 // A same-document fragment-navigation happens when the only part of the url
402 // that is modified is after the '#' character.
403 //
404 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12405 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23406 //
407 // Note: this check is only valid for navigations that are not history
408 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
409 // history navigation from 'A#foo' to 'A#bar' is not a same-document
410 // navigation, but a different-document one. This is why history navigation
411 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47412 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52413 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12414
415 // The one case where we do the wrong thing here and incorrectly choose
416 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
417 // the renderer is a frameset. All frameset navigations should be
418 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
419 // navigation would do the right thing, as it would send it to the browser and
420 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
421 // into this method). But since we can't tell that case here for browser-
422 // initiated navigations, we have to get the renderer involved. In that case
423 // the navigation would be restarted due to the renderer spending a reply of
424 // mojom::CommitResult::RestartCrossDocument.
425
426 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31427 ? blink::mojom::NavigationType::SAME_DOCUMENT
428 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23429}
430
Camille Lamy5193caa2018-10-12 11:59:42431// Adjusts the original input URL if needed, to get the URL to actually load and
432// the virtual URL, which may differ.
433void RewriteUrlForNavigation(const GURL& original_url,
434 BrowserContext* browser_context,
435 GURL* url_to_load,
436 GURL* virtual_url,
437 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42438 // Allow the browser URL handler to rewrite the URL. This will, for example,
439 // remove "view-source:" from the beginning of the URL to get the URL that
440 // will actually be loaded. This real URL won't be shown to the user, just
441 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31442 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42443 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
444 url_to_load, browser_context, reverse_on_redirect);
445}
446
447#if DCHECK_IS_ON()
448// Helper sanity check function used in debug mode.
449void ValidateRequestMatchesEntry(NavigationRequest* request,
450 NavigationEntryImpl* entry) {
451 if (request->frame_tree_node()->IsMainFrame()) {
452 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
453 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31454 ui::PageTransitionFromInt(request->common_params().transition),
455 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42456 }
Nasko Oskovc36327d2019-01-03 23:23:04457 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42458 entry->should_clear_history_list());
459 DCHECK_EQ(request->common_params().has_user_gesture,
460 entry->has_user_gesture());
461 DCHECK_EQ(request->common_params().base_url_for_data_url,
462 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04463 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42464 entry->GetCanLoadLocalResources());
465 DCHECK_EQ(request->common_params().started_from_context_menu,
466 entry->has_started_from_context_menu());
467
468 FrameNavigationEntry* frame_entry =
469 entry->GetFrameEntry(request->frame_tree_node());
470 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52471 // TODO(https://crbug.com/40467594): This case should be unreachable once
472 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42473 return;
474 }
475
Camille Lamy5193caa2018-10-12 11:59:42476 DCHECK_EQ(request->common_params().method, frame_entry->method());
477
Nasko Oskovc36327d2019-01-03 23:23:04478 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42479 if (redirect_size == frame_entry->redirect_chain().size()) {
480 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04481 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42482 frame_entry->redirect_chain()[i]);
483 }
484 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21485 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42486 }
487}
488#endif // DCHECK_IS_ON()
489
Dave Tapuska8bfd84c2019-03-26 20:47:16490// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20491// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16492bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20493 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16494 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20495 DCHECK(sandboxed_initiator_rfh);
496 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
497 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16498 for (auto& item : navigations) {
499 bool within_subtree = false;
500 // Check whether this NavigationRequest affects a frame within the
501 // sandboxed frame's subtree by walking up the tree looking for the
502 // sandboxed frame.
503 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03504 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20505 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16506 within_subtree = true;
507 break;
508 }
509 }
510 if (!within_subtree)
511 return false;
512 }
513 return true;
514}
515
William Liu122754942024-01-18 22:34:39516// Used for "Navigation.SessionHistoryCount" histogram.
517enum class HistoryNavTypeForHistogram {
518 // A same-doc or cross-doc navigation of the main frame. We can only have one
519 // main frame request per `NavigationController::GoToIndex()`.
520 kMainFrame = 0,
521 // `NavigationController::GoToIndex()` creates one main frame request and
522 // one or more subframe requests.
523 kMainFrameAndSubframe,
524 // `NavigationController::GoToIndex()` creates one or more subframe requests.
525 kSubframe,
526 // Used for histogram boundary.
527 kCount
528};
529
530void CountRequests(
531 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
532 int& mutable_main_frame_cnt,
533 int& mutable_subframe_cnt) {
534 for (const auto& req : requests) {
535 if (req->IsInPrimaryMainFrame()) {
536 // We can only have one main frame navigation at a time.
537 CHECK_EQ(mutable_main_frame_cnt, 0);
538 ++mutable_main_frame_cnt;
539 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
540 ++mutable_subframe_cnt;
541 }
542 }
543}
544
545// Record the number of different types of navigations as histograms. See
546// `HistoryNavTypeForHistogram` for the types.
547void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
548 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
549 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
550 // We must have one request.
551 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
552
553 int main_frame_cnt = 0;
554 int subframe_cnt = 0;
555 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
556 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
557
558 std::optional<HistoryNavTypeForHistogram> history_nav_type;
559 if (main_frame_cnt > 0) {
560 if (subframe_cnt == 0) {
561 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
562 } else {
563 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
564 }
565 } else if (subframe_cnt > 0) {
566 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
567 }
568 if (history_nav_type.has_value()) {
569 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
570 history_nav_type.value(),
571 HistoryNavTypeForHistogram::kCount);
572 }
573}
574
[email protected]e9ba4472008-09-14 15:42:43575} // namespace
576
arthursonzogni66f711c2019-10-08 14:40:36577// NavigationControllerImpl::PendingEntryRef------------------------------------
578
579NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
580 base::WeakPtr<NavigationControllerImpl> controller)
581 : controller_(controller) {}
582
583NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
584 if (!controller_) // Can be null with interstitials.
585 return;
586
587 controller_->PendingEntryRefDeleted(this);
588}
589
[email protected]d202a7c2012-01-04 07:53:47590// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29591
[email protected]23a918b2014-07-15 09:51:36592const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23593
[email protected]765b35502008-08-21 00:51:20594// static
[email protected]d202a7c2012-01-04 07:53:47595size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23596 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20597
[email protected]e6fec472013-05-14 05:29:02598// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20599// when testing.
600static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29601
[email protected]71fde352011-12-29 03:29:56602// static
dcheng9bfa5162016-04-09 01:00:57603std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
604 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10605 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37606 std::optional<url::Origin> initiator_origin,
607 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10608 ui::PageTransition transition,
609 bool is_renderer_initiated,
610 const std::string& extra_headers,
611 BrowserContext* browser_context,
612 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
613 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21614 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37615 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32616 is_renderer_initiated, extra_headers, browser_context,
617 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10618}
619
620// static
621std::unique_ptr<NavigationEntryImpl>
622NavigationControllerImpl::CreateNavigationEntry(
623 const GURL& url,
624 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37625 std::optional<url::Origin> initiator_origin,
626 std::optional<GURL> initiator_base_url,
627 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57628 ui::PageTransition transition,
629 bool is_renderer_initiated,
630 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09631 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17632 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
633 bool rewrite_virtual_urls) {
634 GURL url_to_load = url;
635 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56636 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17637 if (rewrite_virtual_urls) {
638 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
639 &reverse_on_redirect);
640 }
Lukasz Anforowicz641234d52019-11-07 21:07:10641 // Let the NTP override the navigation params and pretend that this is a
642 // browser-initiated, bookmark-like navigation.
643 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32644 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21645 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10646
Patrick Monettef507e982019-06-19 20:18:06647 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28648 nullptr, // The site instance for tabs is sent on navigation
649 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21650 url_to_load, referrer, initiator_origin, initiator_base_url,
651 std::u16string(), transition, is_renderer_initiated,
652 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17653 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42654 entry->SetVirtualURL(virtual_url);
655 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56656 entry->set_update_virtual_url_with_url(reverse_on_redirect);
657 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06658 return entry;
[email protected]71fde352011-12-29 03:29:56659}
660
[email protected]cdcb1dee2012-01-04 00:46:20661// static
662void NavigationController::DisablePromptOnRepost() {
663 g_check_for_repost = false;
664}
665
[email protected]c5b88d82012-10-06 17:03:33666base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
667 base::Time t) {
668 // If |t| is between the water marks, we're in a run of duplicates
669 // or just getting out of it, so increase the high-water mark to get
670 // a time that probably hasn't been used before and return it.
671 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35672 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33673 return high_water_mark_;
674 }
675
676 // Otherwise, we're clear of the last duplicate run, so reset the
677 // water marks.
678 low_water_mark_ = high_water_mark_ = t;
679 return t;
680}
681
ckitagawa0faa5e42020-06-17 17:30:54682NavigationControllerImpl::ScopedShowRepostDialogForTesting::
683 ScopedShowRepostDialogForTesting()
684 : was_disallowed_(g_check_for_repost) {
685 g_check_for_repost = true;
686}
687
688NavigationControllerImpl::ScopedShowRepostDialogForTesting::
689 ~ScopedShowRepostDialogForTesting() {
690 g_check_for_repost = was_disallowed_;
691}
692
Nate Chapin9eb16be72022-09-23 22:54:31693NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
694 base::SafeRef<NavigationControllerImpl> controller)
695 : controller_(controller) {
696 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
697 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
698 frame_tree_node_id_to_keys_.insert(
699 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
700 if (auto* frame_entry = frame_tree_node->current_frame_host()
701 ->last_committed_frame_entry()) {
702 frame_tree_node_id_to_doc_seq_nos_.insert(
703 {frame_tree_node->frame_tree_node_id(),
704 frame_entry->document_sequence_number()});
705 }
706 }
707 PopulateKeySet(Direction::kBack);
708 PopulateKeySet(Direction::kForward);
709}
710
711void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
712 Direction direction) {
713 // Keep track of which FrameTreeNodes may still have relevant API keys in
714 // additional FrameNavigationEntries.
715 std::set<FrameTreeNode*> nodes_to_process;
716 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
717 nodes_to_process.insert(node);
718 }
719
720 const int offset = direction == Direction::kForward ? 1 : -1;
721 const int start = direction == Direction::kForward
722 ? controller_->GetLastCommittedEntryIndex()
723 : controller_->GetLastCommittedEntryIndex() - 1;
724 for (int i = start;
725 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
726 i += offset) {
727 std::set<FrameTreeNode*> nodes_to_continue_processing;
728
729 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
730 entry->ForEachFrameEntry([this, &nodes_to_process,
731 &nodes_to_continue_processing,
732 &entry](FrameNavigationEntry* frame_entry) {
733 // Find the |node| that matches |frame_entry|, if any.
734 FrameTreeNode* node = nullptr;
735 if (frame_entry == entry->root_node()->frame_entry) {
736 node = controller_->frame_tree().root();
737 } else {
738 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
739 if (it == names_to_nodes_.end())
740 return;
741 node = it->second;
742 }
743
744 // Skip this node if a previous step determine there are no longer
745 // relevant navigation API keys in this direction.
746 if (nodes_to_process.find(node) == nodes_to_process.end())
747 return;
748
749 // Stop processing |node| if we reach a point where it's cross-origin.
750 // See also PopulateSingleNavigationApiHistoryEntryVector().
751 url::Origin frame_entry_origin =
752 frame_entry->committed_origin().value_or(url::Origin::Resolve(
753 frame_entry->url(),
754 frame_entry->initiator_origin().value_or(url::Origin())));
755 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
756 return;
757
758 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
759 frame_entry->navigation_api_key());
760 // Mark |node| as needing more processing for the next entry.
761 nodes_to_continue_processing.insert(node);
762
763 // Check whether |node| went cross-document. If so, its children are
764 // no longer the same conceptual iframe as the current one, and
765 // should no longer be processed. This check is intentionally done
766 // after processing the current |node|, which may still have relevant
767 // discarded API keys.
768 if (frame_entry->document_sequence_number() !=
769 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50770 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31771 nodes_to_process.erase(descendant);
772 }
773 });
774
775 nodes_to_process.swap(nodes_to_continue_processing);
776 }
777}
778
779NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
780 std::set<std::string> all_keys;
781 // Find all remaining navigation API keys after some entries have been
782 // removed.
783 for (auto& entry : controller_->entries_) {
784 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
785 all_keys.insert(frame_entry->navigation_api_key());
786 });
787 }
788
789 // Notify each frame in the renderer of any disposed navigation API keys.
790 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
791 std::vector<std::string> disposed_keys;
792 for (const auto& key : id_to_keys.second) {
793 if (all_keys.find(key) == all_keys.end())
794 disposed_keys.push_back(key);
795 }
796 if (disposed_keys.empty())
797 continue;
798
799 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
800 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
801 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
802 }
803}
804
[email protected]d202a7c2012-01-04 07:53:47805NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00806 BrowserContext* browser_context,
807 FrameTree& frame_tree,
808 NavigationControllerDelegate* delegate)
809 : frame_tree_(frame_tree),
810 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57811 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22812 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37813 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
814 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37815 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29816}
817
[email protected]d202a7c2012-01-04 07:53:47818NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00819 // The NavigationControllerImpl might be called inside its delegate
820 // destructor. Calling it is not valid anymore.
821 delegate_ = nullptr;
822 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29823}
824
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57825BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55826 return browser_context_;
827}
828
[email protected]d202a7c2012-01-04 07:53:47829void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30830 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36831 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57832 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47833 // Note that it's possible for `entries_` to contain multiple entries at this
834 // point, as Restore() might be called on a NavigationController that is
835 // already used (e.g. due to WebView's restoreState() API), not only for fresh
836 // NavigationControllers. These entries are not cleared to preserve legacy
837 // behavior and also because `pending_entry_` might point to one of the
838 // pre-existing entries. An exception for this is when `entries_` contains
839 // only the initial NavigationEntry, which must be removed.
840
841 // Do not proceed if selected_navigation will be out of bounds for the updated
842 // entries_ list, since it will be assigned to last_committed_entry_index_ and
843 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58844 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47845 // is empty, since there should be no work to do (rather than marking the
846 // existing entries as needing reload). Also consider returning early if the
847 // selected index is -1, which represents a no-committed-entry state.
848 if (selected_navigation < -1 ||
849 selected_navigation >=
850 base::checked_cast<int>(entries->size() + entries_.size())) {
851 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24852 }
Charlie Reis23c26da2022-01-29 00:57:47853
Rakina Zata Amni46087a12022-11-11 08:28:38854 // There will always be at least one entry (new NavigationControllers will
855 // have the initial NavigationEntry).
856 if (selected_navigation == -1)
857 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47858
Rakina Zata Amni46087a12022-11-11 08:28:38859 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
860 // If we are on the initial NavigationEntry, it must be the only entry in
861 // the list. Since it's impossible to do a history navigation to the
862 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
863 // `pending_entry` might be set for a new non-history navigation).
864 // Note that we should not clear `entries_` if `entries` is empty (when
865 // InitialNavigationEntry mode is enabled), since that would leave us
866 // without any NavigationEntry.
867 CHECK_EQ(1, GetEntryCount());
868 CHECK_EQ(-1, pending_entry_index_);
869 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47870 }
[email protected]ce3fa3c2009-04-20 19:55:57871
[email protected]ce3fa3c2009-04-20 19:55:57872 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44873 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03874 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47875 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43876 if (entry->GetURL().is_empty()) {
877 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01878 // persisting the initial NavigationEntry [which is no longer possible but
879 // some old persisted sessions might still contain it] or when the
880 // serializer failed to write the URL because it's too long). Trying to
881 // restore and navigate to an entry with an empty URL will result in
882 // crashes, so change the URL to about:blank. See also
883 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43884 entry->SetURL(GURL(url::kAboutBlankURL));
885 }
dcheng36b6aec92015-12-26 06:16:36886 entries_.push_back(
887 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47888 }
avif16f85a72015-11-13 18:25:03889
890 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
891 // cleared out safely.
892 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57893
894 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36895 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57896}
897
toyoshim6142d96f2016-12-19 09:07:25898void NavigationControllerImpl::Reload(ReloadType reload_type,
899 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03900 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
901 (int)reload_type);
902 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
903 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28904 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28905 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32906 int current_index = -1;
907
Carlos IL42b416592019-10-07 23:10:36908 if (entry_replaced_by_post_commit_error_) {
909 // If there is an entry that was replaced by a currently active post-commit
910 // error navigation, this can't be the initial navigation.
911 DCHECK(!IsInitialNavigation());
912 // If the current entry is a post commit error, we reload the entry it
913 // replaced instead. We leave the error entry in place until a commit
914 // replaces it, but the pending entry points to the original entry in the
915 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
916 // case that pending_entry_ != entries_[pending_entry_index_].
917 entry = entry_replaced_by_post_commit_error_.get();
918 current_index = GetCurrentEntryIndex();
919 } else if (IsInitialNavigation() && pending_entry_) {
920 // If we are reloading the initial navigation, just use the current
921 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32922 entry = pending_entry_;
923 // The pending entry might be in entries_ (e.g., after a Clone), so we
924 // should also update the current_index.
925 current_index = pending_entry_index_;
926 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00927 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32928 current_index = GetCurrentEntryIndex();
929 if (current_index != -1) {
creis3da03872015-02-20 21:12:32930 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32931 }
[email protected]979a4bc2013-04-24 01:27:15932 }
[email protected]241db352013-04-22 18:04:05933
[email protected]59167c22013-06-03 18:07:32934 // If we are no where, then we can't reload. TODO(darin): We should add a
935 // CanReload method.
936 if (!entry)
937 return;
938
Rakina Zata Amnif297a802022-01-18 03:53:43939 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
940 // We should never navigate to an existing initial NavigationEntry that is
941 // the initial NavigationEntry for the initial empty document that hasn't
942 // been overridden by the synchronous about:blank commit, to preserve
943 // legacy behavior where trying to reload when the main frame is on the
944 // initial empty document won't result in a navigation. See also
945 // https://crbug.com/1277414.
946 return;
947 }
948
Aran Gilman37d11632019-10-08 23:07:15949 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30950 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07951 // they really want to do this. If they do, the dialog will call us back
952 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57953 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02954
[email protected]106a0812010-03-18 00:15:12955 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57956 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47957 return;
initial.commit09911bf2008-07-26 23:55:29958 }
Lei Zhang96031532019-10-10 19:05:47959
Wang Huia25efabc2022-09-24 17:27:22960 // Set ReloadType for |entry|.
961 entry->set_reload_type(reload_type);
962
Lei Zhang96031532019-10-10 19:05:47963 if (!IsInitialNavigation())
964 DiscardNonCommittedEntries();
965
966 pending_entry_ = entry;
967 pending_entry_index_ = current_index;
968 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
969
Nate Chapin45f620582021-09-30 17:45:43970 // location.reload() goes through BeginNavigation, so all reloads triggered
971 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13972 NavigateToExistingPendingEntry(
973 reload_type,
974 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:37975 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:13976 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29977}
978
[email protected]d202a7c2012-01-04 07:53:47979void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48980 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12981}
982
[email protected]d202a7c2012-01-04 07:53:47983void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49984 // If the pending reload type has been cleared by another navigation
985 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48986 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49987 return;
[email protected]106a0812010-03-18 00:15:12988 }
Wang Hui96ab1012022-10-11 02:05:49989 Reload(pending_reload_, false);
990 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12991}
992
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57993bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09994 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11995}
996
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57997bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38998 // Check that we're on the initial NavigationEntry and that this is not a
999 // cloned tab.
1000 return IsInitialNavigation() && GetEntryCount() == 1 &&
1001 GetLastCommittedEntry()->IsInitialEntry() &&
1002 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401003}
1004
Aran Gilman37d11632019-10-08 23:07:151005NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1006 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581007 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031008 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581009}
1010
Adithya Srinivasan9b0c99c2021-08-10 15:19:451011NavigationEntryImpl*
1012NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1013 int nav_entry_id) const {
1014 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1015 if (entry)
1016 return entry;
1017 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521018 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451019 : nullptr;
1020}
1021
W. James MacLeanc07dc41b2022-07-25 18:52:161022void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571023 const url::Origin& origin) {
1024 for (int i = 0; i < GetEntryCount(); i++) {
1025 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161026 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571027 }
1028 if (entry_replaced_by_post_commit_error_) {
1029 // It's possible we could come back to this entry if the error
1030 // page/interstitial goes away.
1031 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161032 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571033 }
W. James MacLean1c40862c2020-04-27 21:05:571034}
1035
avi25764702015-06-23 15:43:371036void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571037 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001038 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371039 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271040 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201041}
1042
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571043NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471044 if (pending_entry_)
1045 return pending_entry_;
1046 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201047}
1048
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571049NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321050 // The pending entry is safe to return for new (non-history), browser-
1051 // initiated navigations. Most renderer-initiated navigations should not
1052 // show the pending entry, to prevent URL spoof attacks.
1053 //
1054 // We make an exception for renderer-initiated navigations in new tabs, as
1055 // long as no other page has tried to access the initial empty document in
1056 // the new tab. If another page modifies this blank page, a URL spoof is
1057 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321058 bool safe_to_show_pending =
1059 pending_entry_ &&
1060 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091061 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321062 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461063 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321064
1065 // Also allow showing the pending entry for history navigations in a new tab,
1066 // such as Ctrl+Back. In this case, no existing page is visible and no one
1067 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151068 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1069 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321070 safe_to_show_pending = true;
1071
1072 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191073 return pending_entry_;
1074 return GetLastCommittedEntry();
1075}
1076
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571077int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201078 if (pending_entry_index_ != -1)
1079 return pending_entry_index_;
1080 return last_committed_entry_index_;
1081}
1082
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571083NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381084 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031085 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201086}
1087
Elad Alon32044f532025-03-04 22:16:031088const NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry()
1089 const {
1090 CHECK_NE(last_committed_entry_index_, -1);
1091 return entries_[last_committed_entry_index_].get();
1092}
1093
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571094bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351095 const std::string& mime_type = frame_tree_->root()
1096 ->current_frame_host()
1097 ->GetPage()
1098 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531099 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1100 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271101 NavigationEntry* visible_entry = GetVisibleEntry();
1102 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391103 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161104}
1105
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571106int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271107 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451108 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271109 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551110 return last_committed_entry_index_;
1111}
1112
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571113int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451114 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291115 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551116 return static_cast<int>(entries_.size());
1117}
1118
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571119NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371120 if (index < 0 || index >= GetEntryCount())
1121 return nullptr;
1122
avif16f85a72015-11-13 18:25:031123 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251124}
1125
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571126NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471127 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201128}
1129
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571130int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461131 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031132}
1133
Arthur Sonzognic686e8f2024-01-11 08:36:371134std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031135 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591136 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1137 return index;
1138 }
Shivani Sharma298d12852019-01-22 20:04:031139 }
Arthur Sonzognic686e8f2024-01-11 08:36:371140 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591141}
1142
1143bool NavigationControllerImpl::CanGoBack() {
1144 return GetIndexForGoBack().has_value();
1145}
1146
Arthur Sonzognic686e8f2024-01-11 08:36:371147std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591148 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1149 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1150 return index;
1151 }
1152 }
Arthur Sonzognic686e8f2024-01-11 08:36:371153 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201154}
1155
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571156bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591157 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201158}
1159
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571160bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031161 int index = GetIndexForOffset(offset);
1162 return index >= 0 && index < GetEntryCount();
1163}
1164
Xiaohan Wang7f8052e02022-01-14 18:44:281165#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151166bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151167 if (offset == 0)
1168 return true;
1169 int increment = offset > 0 ? 1 : -1;
1170 int non_skippable_entries = 0;
1171 for (int index = GetIndexForOffset(increment);
1172 index >= 0 && index < GetEntryCount(); index += increment) {
1173 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1174 non_skippable_entries++;
1175
1176 if (non_skippable_entries == std::abs(offset))
1177 return true;
1178 }
1179 return false;
1180}
1181#endif
1182
[email protected]d202a7c2012-01-04 07:53:471183void NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371184 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061185
Kevin McNeeedc481c2023-04-27 22:30:581186 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211187
Kevin McNee3b3a56192023-03-17 14:40:591188 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201189}
1190
[email protected]d202a7c2012-01-04 07:53:471191void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161192 // Note that at least one entry (the last one) will be non-skippable since
1193 // entries are marked skippable only when they add another entry because of
1194 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371195 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591196
Kevin McNeeedc481c2023-04-27 22:30:581197 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591198
1199 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201200}
1201
[email protected]d202a7c2012-01-04 07:53:471202void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131203 GoToIndex(index, /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371204 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:131205 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161206}
1207
William Liu62ae26c2024-08-08 14:28:161208std::vector<base::WeakPtr<NavigationRequest>>
1209NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201210 int index,
1211 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371212 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131213 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201214 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441215 TRACE_EVENT0("browser,navigation,benchmark",
1216 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501217 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1218 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1219 entries_.size());
1220 // Indices should have have been validated by the caller.
1221 CHECK_GE(index, 0);
1222 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201223
Rakina Zata Amnif297a802022-01-18 03:53:431224 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1225 // We should never navigate to an existing initial NavigationEntry that is
1226 // the initial NavigationEntry for the initial empty document that hasn't
1227 // been overridden by the synchronous about:blank commit, to preserve
1228 // legacy behavior where trying to reload when the main frame is on the
1229 // initial empty document won't result in a navigation. See also
1230 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161231 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431232 }
1233
[email protected]cbab76d2008-10-13 22:42:471234 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201235
arthursonzogni5c4c202d2017-04-25 23:41:271236 DCHECK_EQ(nullptr, pending_entry_);
1237 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431238
arthursonzogni5c4c202d2017-04-25 23:41:271239 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201240 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271241 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1242 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
William Liuec04e382024-05-23 18:03:271243 return NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
1244 soft_navigation_heuristics_task_id,
1245 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201246}
1247
[email protected]d202a7c2012-01-04 07:53:471248void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121249 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031250 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201251 return;
1252
[email protected]9ba14052012-06-22 23:50:031253 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201254}
1255
Nate Chapinbf682fa32022-09-26 22:41:201256void NavigationControllerImpl::GoToOffsetFromRenderer(
1257 int offset,
Yoav Weiss8c573952022-11-17 17:35:131258 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371259 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131260 soft_navigation_heuristics_task_id) {
Nate Chapinbb74c5a52023-07-21 23:13:351261 // Note: This is actually reached in unit tests.
1262 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431263 return;
1264
Nate Chapinbf682fa32022-09-26 22:41:201265 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131266 soft_navigation_heuristics_task_id,
1267 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431268}
1269
William Liu62ae26c2024-08-08 14:28:161270std::vector<base::WeakPtr<NavigationRequest>>
1271NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271272 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1273 /*soft_navigation_heuristics_task_id=*/std::nullopt,
1274 /*navigation_api_key=*/nullptr);
1275}
1276
Xiaohan Wang7f8052e02022-01-14 18:44:281277#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151278void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1279 // Note: This is actually reached in unit tests.
1280 if (!CanGoToOffsetWithSkipping(offset))
1281 return;
1282
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421283 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151284 GoToIndex(GetIndexForOffset(offset));
1285 return;
1286 }
1287 int increment = offset > 0 ? 1 : -1;
1288 // Find the offset without counting skippable entries.
1289 int target_index = GetIndexForOffset(increment);
1290 int non_skippable_entries = 0;
1291 for (int index = target_index; index >= 0 && index < GetEntryCount();
1292 index += increment) {
1293 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1294 non_skippable_entries++;
1295
1296 if (non_skippable_entries == std::abs(offset)) {
1297 target_index = index;
1298 break;
1299 }
1300 }
1301
1302 GoToIndex(target_index);
1303}
1304#endif
1305
[email protected]41374f12013-07-24 02:49:281306bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151307 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281308 return false;
[email protected]6a13a6c2011-12-20 21:47:121309
[email protected]43032342011-03-21 14:10:311310 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281311 return true;
[email protected]cbab76d2008-10-13 22:42:471312}
1313
Michael Thiessen9b14d512019-09-23 21:19:471314void NavigationControllerImpl::PruneForwardEntries() {
1315 DiscardNonCommittedEntries();
1316 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471317 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471318 if (num_removed <= 0)
1319 return;
Nate Chapin9eb16be72022-09-23 22:54:311320 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471321 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1322 NotifyPrunedEntries(this, remove_start_index /* start index */,
1323 num_removed /* count */);
1324}
1325
Aran Gilman37d11632019-10-08 23:07:151326void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1327 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321328 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311329 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511330 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1331 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321332 }
1333}
1334
Harkiran Bolariaba823e42021-05-21 18:30:361335base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1336 const GURL& url,
1337 const Referrer& referrer,
1338 ui::PageTransition transition,
1339 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471340 LoadURLParams params(url);
1341 params.referrer = referrer;
1342 params.transition_type = transition;
1343 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361344 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471345}
1346
Harkiran Bolariaba823e42021-05-21 18:30:361347base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1348 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061349 if (params.is_renderer_initiated)
1350 DCHECK(params.initiator_origin.has_value());
1351
naskob8744d22014-08-28 17:07:431352 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151353 "NavigationControllerImpl::LoadURLWithParams", "url",
1354 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291355 bool is_explicit_navigation =
1356 GetContentClient()->browser()->IsExplicitNavigation(
1357 params.transition_type);
1358 if (HandleDebugURL(params.url, params.transition_type,
1359 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431360 // If Telemetry is running, allow the URL load to proceed as if it's
1361 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491362 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181363 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361364 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181365 }
[email protected]47752982014-07-29 08:01:431366 }
[email protected]8bf1048012012-02-08 01:22:181367
[email protected]cf002332012-08-14 19:17:471368 // Checks based on params.load_type.
1369 switch (params.load_type) {
1370 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431371 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541372#if BUILDFLAG(IS_ANDROID)
1373 case LOAD_TYPE_PDF_ANDROID:
1374#endif
[email protected]cf002332012-08-14 19:17:471375 break;
1376 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261377 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211378 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471379 }
1380 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461381 }
[email protected]e47ae9472011-10-13 19:48:341382
[email protected]e47ae9472011-10-13 19:48:341383 // The user initiated a load, we don't need to reload anymore.
1384 needs_reload_ = false;
1385
Harkiran Bolariaba823e42021-05-21 18:30:361386 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441387}
1388
Charlie Reis4c53a962023-06-21 23:17:531389void NavigationControllerImpl::LoadOriginalRequestURL() {
1390 // If the original request URL is not valid, matches the current URL, or
1391 // involves POST data, then simply reload. The POST check avoids issues with
1392 // sending data to the wrong page.
1393 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1394 const GURL& original_request_url =
1395 GetLastCommittedEntry()->GetOriginalRequestURL();
1396 if (!original_request_url.is_valid() ||
1397 original_request_url == last_committed_url ||
1398 GetLastCommittedEntry()->GetHasPostData()) {
1399 Reload(ReloadType::NORMAL, true);
1400 return;
1401 }
1402
1403 // Otherwise, attempt to load the original request URL without any of the
1404 // other data from the current NavigationEntry, replacing the current entry.
1405 // Loading the original URL is useful in cases such as modifying the user
1406 // agent.
1407 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1408 std::make_unique<NavigationController::LoadURLParams>(
1409 original_request_url);
1410 load_params->should_replace_current_entry = true;
1411 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1412 LoadURLWithParams(*load_params.get());
1413}
1414
Mohamed Abdelhalim833de902019-09-16 17:41:451415bool NavigationControllerImpl::PendingEntryMatchesRequest(
1416 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191417 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451418 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191419}
1420
[email protected]d202a7c2012-01-04 07:53:471421bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321422 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071423 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331424 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441425 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251426 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561427 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131428 NavigationRequest* navigation_request) {
1429 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331430
1431 // Note: validation checks and renderer kills due to invalid commit messages
1432 // must happen before getting here, in
1433 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1434 // effects of the navigation have already occurred.
1435
[email protected]cd2e15742013-03-08 04:08:311436 is_initial_navigation_ = false;
1437
Wang Hui96ab1012022-10-11 02:05:491438 // Any pending request to repost a form submission is no longer valid, since a
1439 // different NavigationEntry is committing.
1440 pending_reload_ = ReloadType::NONE;
1441
[email protected]0e8db942008-09-24 21:21:481442 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431443 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451444 if (entry_replaced_by_post_commit_error_) {
1445 // Same document navigation events with a post-commit error should already
1446 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1447 // reaching here.
1448 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331449
Xinghui Lub9e86a352024-05-17 16:29:421450 if (pending_entry_) {
1451 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1452 // `pending_entry_` isn't pointing to the last committed entry.
1453 // Instead, all reload approaches (e.g., in `Reload` and
1454 // `LoadIfNecessary`) should attempt to load the
1455 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1456 // entry itself.
1457 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1458 << "Incorrectly reloading the post commit error page entry.";
1459 }
Xinghui Lue4e50be2024-05-15 21:46:001460
Rakina Zata Amnie2d31312022-11-18 03:38:451461 // Any commit while a post-commit error page is showing should put the
1462 // original entry back, replacing the error page's entry. This includes
1463 // reloads, where the original entry was used as the pending entry and
1464 // should now be at the correct index at commit time.
1465 entries_[last_committed_entry_index_] =
1466 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481467 }
Rakina Zata Amnie2d31312022-11-18 03:38:451468 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1469 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001470 // Must honor user agent overrides in the |navigation_request|, such as
1471 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1472 // result, besides comparing |pending_entry_|'s user agent against
1473 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1474 // agent against LastCommittedEntry's.
1475 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541476 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1477 (PendingEntryMatchesRequest(navigation_request) &&
1478 pending_entry_->GetIsOverridingUserAgent() !=
1479 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001480 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451481 }
[email protected]ecd9d8702008-08-28 22:10:171482
Dave Tapuskaa2ab4f252021-07-08 21:31:281483 bool is_main_frame_navigation = !rfh->GetParent();
1484
Alexander Timind2f2e4f22019-04-02 20:04:531485 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1486 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281487 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141488 // BackForwardCacheMetrics to be associated with the new navigation's
1489 // NavigationEntry, by either creating a new object or reusing the previous
1490 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281491 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211492 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141493 back_forward_cache_metrics = BackForwardCacheMetrics::
1494 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281495 GetLastCommittedEntry(), is_main_frame_navigation,
1496 params.document_sequence_number);
1497 }
Yuzu Saijo29f96ca92022-12-08 04:54:121498
Alexander Timind2f2e4f22019-04-02 20:04:531499 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281500 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451501 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1502 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531503 }
1504 }
1505
Rakina Zata Amnifd8370b2022-11-14 13:32:251506 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1507 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091508 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251509 details->did_replace_entry =
1510 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091511
fdegans9caf66a2015-07-30 21:10:421512 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111513 // except for restored entries. This should be true even if the current commit
1514 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291515 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481516 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081517 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111518
1519 // Only make changes based on the pending entry if the NavigationRequest
1520 // matches it. Otherwise, the pending entry may be for a different request
1521 // (e.g., if a slow history navigation is pending while an auto-subframe
1522 // commit occurs).
1523 if (PendingEntryMatchesRequest(navigation_request)) {
1524 // It is no longer necessary to consider the pending entry as restored.
1525 if (pending_entry_->IsRestored()) {
1526 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1527 was_restored = true;
1528 }
[email protected]e9ba4472008-09-14 15:42:431529
Charlie Reisf8cde712022-10-20 16:25:091530 // If the SiteInstance has changed from the matching pending entry, this
1531 // must be treated as a new navigation with replacement. Set the replacement
1532 // bit here and ClassifyNavigation will identify this case and return
1533 // NEW_ENTRY.
1534 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1535 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1536 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251537 // TODO(nasko,creis,rakina): Move this to happen before committing the
1538 // navigation. This is a bit complicated because we don't currently
1539 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091540 details->did_replace_entry = true;
1541 }
Nasko Oskovaee2f862018-06-15 00:05:521542 }
[email protected]bcd904482012-02-01 01:54:221543
[email protected]e9ba4472008-09-14 15:42:431544 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101545 NavigationType navigation_type =
1546 ClassifyNavigation(rfh, params, navigation_request);
1547 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451548
Rakina Zata Amnie2d31312022-11-18 03:38:451549 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451550 // Ensure that this navigation does not add a navigation entry, since
1551 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1552 // beyond the last committed one. Therefore, `should_replace_current_entry`
1553 // should be set, which replaces the current entry, or this should be a
1554 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251555 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331556 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451557 }
1558
Rakina Zata Amnie2d31312022-11-18 03:38:451559 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551560 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241561 // This is a subframe navigation on the initial empty document, which used
1562 // to not have a NavigationEntry to attach to. Now it can attach to the
1563 // initial NavigationEntry, and we must ensure that its NavigationEntry
1564 // will keep the "initial NavigationEntry" status and won't append a new
1565 // NavigationEntry (it should always do replacement instead).
1566 // See also https://crbug.com/1277414.
1567 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551568 // Subframe navigation on initial NavigationEntry must not append a new
1569 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1570 // means every subframe navigation that happens while we're on the initial
1571 // NavigationEntry will always reuse the existing NavigationEntry and
1572 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101573 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1574 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551575 // This is a navigation that modifies the initial NavigationEntry, either
1576 // for a replacement or a reload. The initial NavigationEntry should
1577 // retain its "initial NavigationEntry" status in this case.
1578 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241579 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251580 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1581 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241582 // This is a synchronous about:blank navigation on the main frame, which
1583 // used to not create a NavigationEntry when we have no NavigationEntry on
1584 // FrameTree creation. We now have the initial NavigationEntry and are on
1585 // the initial NavigationEntry. To preserve old behavior, we should still
1586 // keep the "initial" status for the new NavigationEntry that we will
1587 // create for this navigation, so that subframe navigations under the
1588 // synchronously committed about:blank document will never append new
1589 // NavigationEntry, and instead will just reuse the initial
1590 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1591 // See also https://crbug.com/1277414.
1592 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551593 }
1594 }
1595 DCHECK(!details->should_stay_as_initial_entry ||
1596 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201597
eugenebutee08663a2017-04-27 17:43:121598 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441599 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121600
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071601 details->is_prerender_activation =
1602 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241603 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1604 ->GetOutermostMainFrame()
1605 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071606
Peter Boströmd7592132019-01-30 04:50:311607 // Make sure we do not discard the pending entry for a different ongoing
1608 // navigation when a same document commit comes in unexpectedly from the
1609 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1610 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581611 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061612 bool keep_pending_entry =
1613 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101614 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061615 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311616
Miyoung Shin3299cbf2022-11-22 01:41:101617 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061618 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491619 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051620 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561621 previous_document_had_history_intervention_activation,
1622 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431623 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061624 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491625 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1626 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001627 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431628 break;
[email protected]8ff00d72012-10-23 19:12:211629 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471630 RendererDidNavigateNewSubframe(
1631 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561632 previous_document_had_history_intervention_activation,
1633 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431634 break;
[email protected]8ff00d72012-10-23 19:12:211635 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391636 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251637 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001638 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081639 // We don't send a notification about auto-subframe PageState during
1640 // UpdateStateForFrame, since it looks like nothing has changed. Send
1641 // it here at commit time instead.
1642 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431643 return false;
creis59d5a47cb2016-08-24 23:57:191644 }
[email protected]e9ba4472008-09-14 15:42:431645 break;
Aran Gilman37d11632019-10-08 23:07:151646 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211647 NOTREACHED();
[email protected]765b35502008-08-21 00:51:201648 }
1649
[email protected]688aa65c62012-09-28 04:32:221650 // At this point, we know that the navigation has just completed, so
1651 // record the time.
1652 //
1653 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261654 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331655 base::Time timestamp =
1656 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1657 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131658 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221659
Peter Boströmd7592132019-01-30 04:50:311660 // If we aren't keeping the pending entry, there shouldn't be one at this
1661 // point. Clear it again in case any error cases above forgot to do so.
1662 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1663 // been cleared instead of protecting against it.
1664 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551665 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141666
[email protected]e9ba4472008-09-14 15:42:431667 // All committed entries should have nonempty content state so WebKit doesn't
1668 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471669 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321670 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221671 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441672 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141673
Alexander Timind2f2e4f22019-04-02 20:04:531674 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1675 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281676 if (back_forward_cache_metrics &&
1677 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531678 active_entry->set_back_forward_cache_metrics(
1679 std::move(back_forward_cache_metrics));
1680 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281681
1682 // `back_forward_cache_metrics()` may return null as we do not record
1683 // back-forward cache metrics for navigations in non-primary frame trees.
1684 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581685 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141686 // These are both only available from details at this point, so we capture
1687 // them here.
1688 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101689 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141690 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1691 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281692 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1693 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321694 IsBackForwardCacheEnabled() &&
1695 rfh->delegate()->IsBackForwardCacheSupported() &&
1696 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281697 }
naskoc7533512016-05-06 17:01:121698
Charles Reisc0507202017-09-21 00:40:021699 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1700 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1701 // A mismatch can occur if the renderer lies or due to a unique name collision
1702 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121703 FrameNavigationEntry* frame_entry =
1704 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021705 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1706 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031707 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081708 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1709 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031710 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201711
1712 // Remember the bindings the renderer process has at this point, so that
1713 // we do not grant this entry additional bindings if we come back to it.
1714 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301715 }
[email protected]132e281a2012-07-31 18:32:441716
[email protected]97d8f0d2013-10-29 16:49:211717 // Once it is committed, we no longer need to track several pieces of state on
1718 // the entry.
naskoc7533512016-05-06 17:01:121719 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131720
[email protected]49bd30e62011-03-22 20:12:591721 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221722 // TODO(creis): This check won't pass for subframes until we create entries
1723 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001724 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421725 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591726
[email protected]e9ba4472008-09-14 15:42:431727 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001728 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001729 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311730 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531731
arthursonzogni7ddc6542021-04-09 09:16:501732 active_entry->SetIsOverridingUserAgent(
1733 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031734
[email protected]93f230e02011-06-01 14:40:001735 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291736
aelias100c9192017-01-13 00:01:431737 if (overriding_user_agent_changed)
1738 delegate_->UpdateOverridingUserAgent();
1739
creis03b48002015-11-04 00:54:561740 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1741 // one knows the latest NavigationEntry it is showing (whether it has
1742 // committed anything in this navigation or not). This allows things like
1743 // state and title updates from RenderFrames to apply to the latest relevant
1744 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381745 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031746 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381747 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431748
1749 if (navigation_request->IsPrerenderedPageActivation()) {
Charlie Reis99b2eba22025-01-31 19:18:571750 BroadcastHistoryIndexAndLength();
Alison Gale47d1537d2024-04-19 21:31:461751 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431752 // is activated. As a result, a "prerenderingchange" event listener sees the
1753 // history.length which is not updated yet. We should guarantee that
Charlie Reis99b2eba22025-01-31 19:18:571754 // history's length and index should be updated before a
Hayato Ito2c8c08d02021-06-23 03:38:431755 // "prerenderingchange" event listener runs. One possible approach is to use
1756 // the same IPC which "prerenderingchange" uses, and propagate history's
Charlie Reis99b2eba22025-01-31 19:18:571757 // length and index together with that.
Hayato Ito2c8c08d02021-06-23 03:38:431758 }
1759
[email protected]e9ba4472008-09-14 15:42:431760 return true;
initial.commit09911bf2008-07-26 23:55:291761}
1762
[email protected]8ff00d72012-10-23 19:12:211763NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321764 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101765 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241766 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591767 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511768 "ClassifyNavigation");
1769
avi7c6f35e2015-05-08 17:52:381770 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241771 // A new entry. We may or may not have a corresponding pending entry, and
1772 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001773 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491774 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061775 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381776 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241777 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511778 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381779 return NAVIGATION_TYPE_NEW_SUBFRAME;
1780 }
1781
Charlie Reisc0f17d2d2021-01-12 18:52:491782 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381783 DCHECK(!params.history_list_was_cleared);
1784
avi39c1edd32015-06-04 20:06:001785 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381786 // All manual subframes would be did_create_new_entry and handled above, so
1787 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081788 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1789 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381790 }
1791
Rakina Zata Amnif6950d552020-11-24 03:26:101792 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1793 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381794 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1795 // create a new page.
1796
Hayato Ito2ae49442021-07-02 02:59:251797 // This main frame navigation is not a history navigation (since
1798 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1799 // reload or a replacement navigation, which will modify the existing entry.
1800 //
Nasko Oskov332593c2018-08-16 17:21:341801 // TODO(nasko): With error page isolation, reloading an existing session
1802 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491803 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341804 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511805 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491806 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061807 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381808 }
1809
Charlie Reisf8cde712022-10-20 16:25:091810 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521811 // If the SiteInstance of the |pending_entry_| does not match the
1812 // SiteInstance that got committed, treat this as a new navigation with
1813 // replacement. This can happen if back/forward/reload encounters a server
1814 // redirect to a different site or an isolated error page gets successfully
1815 // reloaded into a different SiteInstance.
1816 if (pending_entry_->site_instance() &&
1817 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491818 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061819 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521820 }
creis77c9aa32015-09-25 19:59:421821
Nasko Oskovaee2f862018-06-15 00:05:521822 if (pending_entry_index_ == -1) {
1823 // In this case, we have a pending entry for a load of a new URL but Blink
1824 // didn't do a new navigation (params.did_create_new_entry). First check
1825 // to make sure Blink didn't treat a new cross-process navigation as
1826 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161827 // we must treat it as NEW rather than the converted reload case below,
1828 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451829 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161830 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061831 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521832 }
1833
1834 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161835 // We will create a pending entry, but NavigateWithoutEntry will convert
1836 // it to a reload since it's the same page and not create a new entry for
1837 // it. (The user doesn't want to have a new back/forward entry when they
1838 // do this.) Therefore we want to just ignore the pending entry and go
1839 // back to where we were (the "existing entry").
1840 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061841 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521842 }
avi7c6f35e2015-05-08 17:52:381843 }
1844
Rakina Zata Amni153d5702021-09-13 22:48:001845 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381846 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491847 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1848 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161849 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061850 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381851 }
1852
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121853 if (navigation_request->DidEncounterError() &&
1854 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101855 nav_entry_id == failed_pending_entry_id_) {
Charlie Reisb5f39cf2024-11-12 16:55:011856 // If the renderer was going to a pending entry that got cleared because of
1857 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511858 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491859 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061860 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381861 }
1862
Charlie Reisc0f17d2d2021-01-12 18:52:491863 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101864 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511865 trace_return.traced_value()->SetInteger("existing_entry_index",
1866 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381867 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441868 // The renderer has committed a navigation to an entry that no longer
1869 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491870 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061871 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381872 }
1873
avi7c6f35e2015-05-08 17:52:381874 // Since we weeded out "new" navigations above, we know this is an existing
1875 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491876 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061877 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381878}
1879
Rakina Zata Amni3460d382021-10-29 00:43:371880void NavigationControllerImpl::UpdateNavigationEntryDetails(
1881 NavigationEntryImpl* entry,
1882 RenderFrameHostImpl* rfh,
1883 const mojom::DidCommitProvisionalLoadParams& params,
1884 NavigationRequest* request,
1885 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001886 bool is_new_entry,
1887 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371888 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171889 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371890 entry->AddOrUpdateFrameEntry(
1891 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571892 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371893 rfh->GetSiteInstance(), nullptr, params.url,
1894 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171895 Referrer(*params.referrer),
1896 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371897 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171898 request ? request->GetRedirectChain() : redirects, params.page_state,
1899 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371900 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171901 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211902 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171903 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371904
1905 if (rfh->GetParent()) {
1906 // Only modify the NavigationEntry for main frame navigations.
1907 return;
1908 }
1909 if (entry->update_virtual_url_with_url())
1910 UpdateVirtualURLToURL(entry, params.url);
1911 // Don't use the page type from the pending entry. Some interstitial page
1912 // may have set the type to interstitial. Once we commit, however, the page
1913 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171914 entry->set_page_type((request && request->DidEncounterError())
1915 ? PAGE_TYPE_ERROR
1916 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431917 if (commit_details && commit_details->should_stay_as_initial_entry) {
1918 // Retain the "initial NavigationEntry" status.
1919 if (request->IsSameDocument()) {
1920 // If this is for a same-document navigation, the NavigationEntry must be
1921 // reused and should already be marked as the initial NavigationEntry.
1922 DCHECK(entry->IsInitialEntry());
1923 } else {
1924 // If this is for a cross-document navigation, it can be caused by a
1925 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1926 // "for synchronous about:blank" in the latter case, and also when it is
1927 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1928 // is not for a synchronous about:blank commit.
1929 NavigationEntryImpl::InitialNavigationEntryState new_state =
1930 NavigationEntryImpl::InitialNavigationEntryState::
1931 kInitialNotForSynchronousAboutBlank;
1932 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1933 request->is_synchronous_renderer_commit()) {
1934 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1935 kInitialForSynchronousAboutBlank;
1936 }
1937 entry->set_initial_navigation_entry_state(new_state);
1938 }
1939 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1940 // Remove the "initial NavigationEntry" status.
1941 entry->set_initial_navigation_entry_state(
1942 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001943 }
Rakina Zata Amniddf10502022-01-15 02:56:551944
Rakina Zata Amni3460d382021-10-29 00:43:371945 if (is_new_entry) {
1946 // Some properties of the NavigationEntry are only set when the entry is
1947 // new (we aren't reusing it).
1948 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171949 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:401950 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:011951 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
1952 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:371953 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1954 } else {
1955 // We are reusing the NavigationEntry. The site instance will normally be
1956 // the same except for a few cases:
1957 // 1) session restore, when no site instance will be assigned or
1958 // 2) redirect, when the site instance is reset.
1959 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1960 entry->site_instance() == rfh->GetSiteInstance());
1961 }
1962}
1963
Rakina Zata Amniafd3c6582021-11-30 06:19:171964void NavigationControllerImpl::CreateInitialEntry() {
1965 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031966 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171967 auto params = mojom::DidCommitProvisionalLoadParams::New();
1968 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1969 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1970 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:401971 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:171972 params->http_status_code = 0;
1973 params->url_is_unreachable = false;
1974 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171975 params->post_id = -1;
1976 params->embedding_token = base::UnguessableToken::Create();
1977 params->navigation_token = base::UnguessableToken::Create();
1978 params->did_create_new_entry = true;
1979 params->origin = rfh->GetLastCommittedOrigin();
1980 params->should_update_history = true;
1981 params->item_sequence_number = 0;
1982 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151983 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171984 params->transition = is_in_fenced_frame_tree
1985 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1986 : ui::PAGE_TRANSITION_LINK;
1987 params->referrer = blink::mojom::Referrer::New();
1988
Rakina Zata Amniafd3c6582021-11-30 06:19:171989 auto new_entry = std::make_unique<NavigationEntryImpl>(
1990 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381991 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211992 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1993 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1994 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171995 UpdateNavigationEntryDetails(
1996 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001997 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1998 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171999
2000 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
2001 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:002002 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172003}
2004
Charlie Reisc0f17d2d2021-01-12 18:52:492005void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:322006 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072007 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362008 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442009 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562010 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002011 NavigationRequest* request,
2012 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572013 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372014 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452015 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372016 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522017 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2018 initiator_base_url = request->common_params().initiator_base_url;
2019 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062020
creisf49dfc92016-07-26 17:05:182021 // First check if this is an in-page navigation. If so, clone the current
2022 // entry instead of looking at the pending entry, because the pending entry
2023 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452024 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302025 FrameNavigationEntry* previous_frame_entry =
2026 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452027 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482028 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572029 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082030 rfh->GetSiteInstance(), nullptr, params.url,
2031 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212032 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092033 request->GetRedirectChain(), params.page_state, params.method,
2034 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392035 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302036 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572037 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302038 // FrameNavigationEntry.
2039 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572040 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032041
creisf49dfc92016-07-26 17:05:182042 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032043 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522044 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2045 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572046 // TODO(jam): we had one report of this with a URL that was redirecting to
2047 // only tildes. Until we understand that better, don't copy the cert in
2048 // this case.
2049 new_entry->GetSSL() = SSLStatus();
2050 }
creisf49dfc92016-07-26 17:05:182051
Patrick Monette50e8bd82019-06-13 22:40:452052 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2053 // that |frame_entry| should now have a reference count of exactly 2: one
2054 // due to the local variable |frame_entry|, and another due to |new_entry|
2055 // also retaining one. This should never fail, because it's the main frame.
2056 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182057 }
2058
Harkiran Bolaria59290d62021-03-17 01:53:012059 // If this is an activation navigation from a prerendered page, transfer the
2060 // new entry from an entry already created and stored in the
2061 // NavigationRequest. |new_entry| will not have been set prior to this as
2062 // |is_same_document| is mutually exclusive with
2063 // |IsPrerenderedPageActivation|.
2064 if (request->IsPrerenderedPageActivation()) {
2065 DCHECK(!is_same_document);
2066 DCHECK(!new_entry);
2067 new_entry = request->TakePrerenderNavigationEntry();
2068 DCHECK(new_entry);
2069 }
2070
Charlie Reisc0f17d2d2021-01-12 18:52:492071 // Only make a copy of the pending entry if it is appropriate for the new
2072 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452073 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042074 // 1. The SiteInstance hasn't been assigned to something else.
2075 // 2. The pending entry was intended as a new entry, rather than being a
2076 // history navigation that was interrupted by an unrelated,
2077 // renderer-initiated navigation.
2078 // TODO(csharrison): Investigate whether we can remove some of the coarser
2079 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452080 if (!new_entry && PendingEntryMatchesRequest(request) &&
2081 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342082 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432083 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352084 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432085
Camille Lamy62b826012019-02-26 09:15:472086 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452087 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182088 }
2089
Charlie Reisc0f17d2d2021-01-12 18:52:492090 // For cross-document commits with no matching pending entry, create a new
2091 // entry.
creisf49dfc92016-07-26 17:05:182092 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062093 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072094 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212095 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582096 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452097 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172098 nullptr, // blob_url_loader_factory
2099 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242100
2101 // Find out whether the new entry needs to update its virtual URL on URL
2102 // change and set up the entry accordingly. This is needed to correctly
2103 // update the virtual URL when replaceState is called after a pushState.
2104 GURL url = params.url;
2105 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492106 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412107 // update the virtual URL based on the new URL. For example, this is needed
2108 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2109 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372110 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2111 &url, browser_context_, &needs_update);
2112 new_entry->set_update_virtual_url_with_url(needs_update);
2113
Camille Lamy62b826012019-02-26 09:15:472114 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452115 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432116 }
2117
Alison Gale770f3fc2024-04-27 00:39:582118 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2119 // set for prerendered contents, if any. This is because
2120 // prerendering/activation technically won't be creating a new document.
2121 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2122 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012123 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372124 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2125 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002126 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082127
Harkiran Bolaria59290d62021-03-17 01:53:012128 // history.pushState() is classified as a navigation to a new page, but sets
2129 // is_same_document to true. In this case, we already have the title and
2130 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452131 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012132 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2133 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2134 }
[email protected]3a868f212014-08-09 10:41:192135 }
[email protected]ff64b3e2014-05-31 04:07:332136
[email protected]60d6cca2013-04-30 08:47:132137 DCHECK(!params.history_list_was_cleared || !replace_entry);
2138 // The browser requested to clear the session history when it initiated the
2139 // navigation. Now we know that the renderer has updated its state accordingly
2140 // and it is safe to also clear the browser side history.
2141 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552142 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132143 entries_.clear();
2144 last_committed_entry_index_ = -1;
2145 }
2146
Nasko Oskovaee2f862018-06-15 00:05:522147 // If this is a new navigation with replacement and there is a
2148 // pending_entry_ which matches the navigation reported by the renderer
2149 // process, then it should be the one replaced, so update the
2150 // last_committed_entry_index_ to use it.
2151 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092152 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522153 last_committed_entry_index_ = pending_entry_index_;
2154 }
2155
Alexander Timine3ec4192020-04-20 16:39:402156 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562157 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402158 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052159
Yuzu Saijoa725585f2022-11-28 04:14:032160 // If this is a history navigation and the old entry has an existing
2161 // back/forward cache metrics object, keep using the old one so that the
2162 // reasons logged from the last time the page navigated gets preserved.
2163 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2164 request)) {
2165 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2166 // because some tests do not have a pending entry.
2167 NavigationEntryImpl* entry =
2168 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2169 if (entry && entry->back_forward_cache_metrics()) {
2170 scoped_refptr<BackForwardCacheMetrics> metrics =
2171 entry->TakeBackForwardCacheMetrics();
2172 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2173 }
2174 }
2175
Andrew Verge754c70a2025-04-17 17:19:192176 bool was_post_commit_error =
2177 request->browser_initiated_error_navigation_type() ==
2178 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit;
2179
Carlos IL42b416592019-10-07 23:10:362180 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Andrew Verge754c70a2025-04-17 17:19:192181 was_post_commit_error, rfh->IsNestedWithinFencedFrame(),
2182 commit_details);
[email protected]e9ba4472008-09-14 15:42:432183}
2184
Charlie Reisc0f17d2d2021-01-12 18:52:492185void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322186 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072187 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362188 bool is_same_document,
jam48cea9082017-02-15 06:13:292189 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452190 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002191 bool keep_pending_entry,
2192 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562193 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2194 << "that a last committed entry exists.";
2195
[email protected]e9ba4472008-09-14 15:42:432196 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002197 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432198
Charlie Reis7e2cb6d2021-01-26 01:27:162199 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002200 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162201 // We're guaranteed to have a last committed entry if intended_as_new_entry
2202 // is true.
avicbdc4c12015-07-01 16:07:112203 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162204
2205 // If the NavigationRequest matches a new pending entry and is classified as
2206 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2207 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092208 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162209 // Note: The pending entry will usually have a real ReloadType here, but
2210 // it can still be ReloadType::NONE in cases that
2211 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2212
2213 // If we classified this correctly, the SiteInstance should not have
2214 // changed.
2215 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2216
2217 // For converted reloads, we assign the entry's unique ID to be that of
2218 // the new one. Since this is always the result of a user action, we want
2219 // to dismiss infobars, etc. like a regular user-initiated navigation.
2220 entry->set_unique_id(pending_entry_->GetUniqueID());
2221
2222 // The extra headers may have changed due to reloading with different
2223 // headers.
2224 entry->set_extra_headers(pending_entry_->extra_headers());
2225 }
2226 // Otherwise, this was intended as a new entry but the pending entry was
2227 // lost in the meantime and no new entry was created. We are stuck at the
2228 // last committed entry.
2229
2230 // Even if this is a converted reload from pressing enter in the omnibox,
2231 // the server could redirect, requiring an update to the SSL status. If this
2232 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452233 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162234 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472235 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452236 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162237 }
Rakina Zata Amnif6950d552020-11-24 03:26:102238 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112239 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102240 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162241
eugenebut604866f2017-05-10 21:35:362242 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452243 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362244 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2245 // this was a restored same document navigation entry, then it won't have
2246 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2247 // navigated it.
jam48cea9082017-02-15 06:13:292248 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522249 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2250 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292251 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2252 was_restored) {
2253 entry->GetSSL() = last_entry->GetSSL();
2254 }
2255 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452256 // In rapid back/forward navigations |request| sometimes won't have a cert
2257 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192258 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452259 if (request->GetSSLInfo().has_value() &&
2260 request->GetSSLInfo()->is_valid()) {
2261 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522262 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2263 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192264 entry->GetSSL() = SSLStatus();
2265 }
jam48cea9082017-02-15 06:13:292266 }
avicbdc4c12015-07-01 16:07:112267 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272268 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572269 // navigations that are EXISTING_ENTRY are same-document navigations that
2270 // result in replacement (e.g. history.replaceState(), location.replace(),
2271 // forced replacements for trivial session history contexts). For these
2272 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112273 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102274
Alison Gale81f4f2c72024-04-22 19:33:312275 // TODO(crbug.com/40532777): Set page transition type to
2276 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2277 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2278 // well as to fix the inconsistency with what we report to observers
2279 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102280
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572281 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102282
eugenebut604866f2017-05-10 21:35:362283 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452284 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362285 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472286 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452287 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112288 }
2289 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432290
Rakina Zata Amni3460d382021-10-29 00:43:372291 UpdateNavigationEntryDetails(entry, rfh, params, request,
2292 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002293 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302294
[email protected]5ccd4dc2012-10-24 02:28:142295 // The redirected to page should not inherit the favicon from the previous
2296 // page.
eugenebut604866f2017-05-10 21:35:362297 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482298 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142299
Charlie Reis951f43372023-05-05 00:30:072300 // Update the last committed index to reflect the committed entry. Do this
2301 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2302 // delegate sees the correct committed index when notified of navigation
2303 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2304 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212305 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072306
Peter Boströmd7592132019-01-30 04:50:312307 // We should also usually discard the pending entry if it corresponds to a
2308 // different navigation, since that one is now likely canceled. In rare
2309 // cases, we leave the pending entry for another navigation in place when we
2310 // know it is still ongoing, to avoid a flicker in the omnibox (see
2311 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432312 //
2313 // Note that we need to use the "internal" version since we don't want to
2314 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312315 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002316 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432317}
2318
[email protected]d202a7c2012-01-04 07:53:472319void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322320 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072321 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362322 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472323 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562324 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002325 NavigationRequest* request,
2326 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262327 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2328 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552329 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2330 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112331
[email protected]e9ba4472008-09-14 15:42:432332 // Manual subframe navigations just get the current entry cloned so the user
2333 // can go back or forward to it. The actual subframe information will be
2334 // stored in the page state for each of those entries. This happens out of
2335 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092336 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2337 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382338
Mikel Astizba9cf2fd2017-12-17 10:38:102339 // The DCHECK below documents the fact that we don't know of any situation
2340 // where |replace_entry| is true for subframe navigations. This simplifies
2341 // reasoning about the replacement struct for subframes (see
2342 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2343 DCHECK(!replace_entry);
2344
Patrick Monette50e8bd82019-06-13 22:40:452345 // This FrameNavigationEntry might not end up being used in the
2346 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372347 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452348 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372349 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522350 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2351 initiator_base_url = request->common_params().initiator_base_url;
2352 }
Nate Chapin63db0d12022-01-20 22:03:302353 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2354 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212355 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302356 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572357 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302358 if (is_same_document) {
2359 FrameNavigationEntry* previous_frame_entry =
2360 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572361 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302362 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572363 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302364 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572365 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302366 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572367 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302368 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572369 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302370 policy_container_policies->referrer_policy);
2371 }
2372
Patrick Monette50e8bd82019-06-13 22:40:452373 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482374 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572375 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082376 rfh->GetSiteInstance(), nullptr, params.url,
2377 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212378 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2379 request->GetRedirectChain(), params.page_state, params.method,
2380 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572381 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032382
creisce0ef3572017-01-26 17:53:082383 std::unique_ptr<NavigationEntryImpl> new_entry =
2384 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452385 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032386 frame_tree_->root());
creise062d542015-08-25 02:01:552387
Alexander Timine3ec4192020-04-20 16:39:402388 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562389 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402390 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472391
creisce0ef3572017-01-26 17:53:082392 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452393 // to replace, which can happen due to a unique name change. See
2394 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2395 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382396
Dave Tapuska87696ae2021-11-18 18:48:312397 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152398 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432399}
2400
[email protected]d202a7c2012-01-04 07:53:472401bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322402 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072403 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392404 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252405 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002406 NavigationRequest* request,
2407 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292408 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2409 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2410
[email protected]e9ba4472008-09-14 15:42:432411 // We're guaranteed to have a previously committed entry, and we now need to
2412 // handle navigation inside of a subframe in it without creating a new entry.
2413 DCHECK(GetLastCommittedEntry());
2414
creis913c63ce2016-07-16 19:52:522415 // For newly created subframes, we don't need to send a commit notification.
2416 // This is only necessary for history navigations in subframes.
2417 bool send_commit_notification = false;
2418
Rakina Zata Amnif6950d552020-11-24 03:26:102419 // If |nav_entry_id| is non-zero and matches an existing entry, this
2420 // is a history navigation. Update the last committed index accordingly. If
2421 // we don't recognize the |nav_entry_id|, it might be a recently
2422 // pruned entry. We'll handle it below.
2423 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2424 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472425 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062426 // Make sure that a subframe commit isn't changing the main frame's
2427 // origin. Otherwise the renderer process may be confused, leading to a
2428 // URL spoof. We can't check the path since that may change
2429 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572430 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2431 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242432 // We should use checks similar to RenderFrameHostImpl's
2433 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2434 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572435 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2436 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2437 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2438 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522439 current_top_url.DeprecatedGetOriginAsURL() !=
2440 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442441 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512442 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062443 }
creis3cdc3b02015-05-29 23:00:472444
creis913c63ce2016-07-16 19:52:522445 // We only need to discard the pending entry in this history navigation
2446 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062447 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002448 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522449
2450 // History navigations should send a commit notification.
2451 send_commit_notification = true;
avi98405c22015-05-21 20:47:062452 }
[email protected]e9ba4472008-09-14 15:42:432453 }
[email protected]f233e4232013-02-23 00:55:142454
creisce0ef3572017-01-26 17:53:082455 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2456 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372457 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2458 // exists), or we may want to clobber it and create a new one. We update in
2459 // cases where the corresponding FrameNavigationEntry is conceptually similar
2460 // to the document described by the commit params: same-document
2461 // navigations, history traversal to an existing entry, and reloads (including
2462 // a "soft reload" where we navigate to the same url without flagging it as a
2463 // reload). But in the case of a different document that is not logically
2464 // related to the committed FrameNavigationEntry's document (cross-document,
2465 // not same url, not a reload, not a history traversal), we replace rather
2466 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252467 //
Nate Chapin9f169072021-06-09 19:32:372468 // In the case where we update, the FrameNavigationEntry will potentially be
2469 // shared across multiple NavigationEntries, and any updates will be reflected
2470 // in all of those NavigationEntries. In the replace case, any existing
2471 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252472 //
2473 // When navigating away from the initial empty document, we also update rather
2474 // than replace. Either update or replace will overwrite the initial empty
2475 // document state for |last_committed|, but if the FrameNavigationEntry for
2476 // the initial empty document is shared across multiple NavigationEntries (due
2477 // to a navigation in another frame), we want to make sure we overwrite the
2478 // initial empty document state everywhere this FrameNavigationEntry is used,
2479 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452480 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372481 FrameNavigationEntry* last_committed_frame_entry =
2482 last_committed->GetFrameEntry(rfh->frame_tree_node());
2483 NavigationEntryImpl::UpdatePolicy update_policy =
2484 NavigationEntryImpl::UpdatePolicy::kUpdate;
2485 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312486 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372487 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252488 last_committed_frame_entry->url() != params.url &&
2489 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372490 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2491 }
2492
Rakina Zata Amni3460d382021-10-29 00:43:372493 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002494 update_policy, false /* is_new_entry */,
2495 commit_details);
creis625a0c7d2015-03-24 23:17:122496
creis913c63ce2016-07-16 19:52:522497 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432498}
2499
[email protected]d202a7c2012-01-04 07:53:472500int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232501 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032502 for (size_t i = 0; i < entries_.size(); ++i) {
2503 if (entries_[i].get() == entry)
2504 return i;
2505 }
2506 return -1;
[email protected]765b35502008-08-21 00:51:202507}
2508
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572509void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242510 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572511 NavigationControllerImpl* source =
2512 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572513 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382514 DCHECK_EQ(1, GetEntryCount());
2515 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472516 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172517 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572518
Francois Dorayeaace782017-06-21 16:37:242519 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442520 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572521 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572522
Fergal Dalya1d569972021-03-16 03:24:532523 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302524 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532525 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2526 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302527 }
[email protected]4e6419c2010-01-15 04:50:342528
Lukasz Anforowicz0de0f452020-12-02 19:57:152529 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572530}
2531
[email protected]79368982013-11-13 01:11:012532bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022533 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162534 if (last_committed_entry_index_ == -1)
2535 return false;
[email protected]9350602e2013-02-26 23:27:442536
[email protected]474f8512013-05-31 22:31:162537 // We cannot prune if there is a pending entry at an existing entry index.
2538 // It may not commit, so we have to keep the last committed entry, and thus
2539 // there is no sensible place to keep the pending entry. It is ok to have
2540 // a new pending entry, which can optionally commit as a new navigation.
2541 if (pending_entry_index_ != -1)
2542 return false;
2543
[email protected]474f8512013-05-31 22:31:162544 return true;
2545}
2546
[email protected]79368982013-11-13 01:11:012547void NavigationControllerImpl::PruneAllButLastCommitted() {
2548 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162549
avi2b177592014-12-10 02:08:022550 DCHECK_EQ(0, last_committed_entry_index_);
2551 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442552
Charlie Reis99b2eba22025-01-31 19:18:572553 BroadcastHistoryIndexAndLength();
[email protected]9350602e2013-02-26 23:27:442554}
2555
[email protected]79368982013-11-13 01:11:012556void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162557 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012558 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262559
Nate Chapin9eb16be72022-09-23 22:54:312560 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2561
[email protected]474f8512013-05-31 22:31:162562 // Erase all entries but the last committed entry. There may still be a
2563 // new pending entry after this.
2564 entries_.erase(entries_.begin(),
2565 entries_.begin() + last_committed_entry_index_);
2566 entries_.erase(entries_.begin() + 1, entries_.end());
2567 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262568}
2569
Christian Dullweber1af31e62018-02-22 11:49:482570void NavigationControllerImpl::DeleteNavigationEntries(
2571 const DeletionPredicate& deletionPredicate) {
2572 // It is up to callers to check the invariants before calling this.
2573 CHECK(CanPruneAllButLastCommitted());
2574 std::vector<int> delete_indices;
2575 for (size_t i = 0; i < entries_.size(); i++) {
2576 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572577 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482578 delete_indices.push_back(i);
2579 }
2580 }
2581 if (delete_indices.empty())
2582 return;
2583
2584 if (delete_indices.size() == GetEntryCount() - 1U) {
2585 PruneAllButLastCommitted();
2586 } else {
2587 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382588 for (const auto& index : base::Reversed(delete_indices)) {
2589 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482590 }
Charlie Reis99b2eba22025-01-31 19:18:572591 BroadcastHistoryIndexAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482592 }
2593 delegate()->NotifyNavigationEntriesDeleted();
2594}
2595
Carlos Caballero35ce710c2019-09-19 10:59:452596BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2597 return back_forward_cache_;
2598}
2599
William Liu055a3542023-04-02 17:21:192600NavigationEntryScreenshotCache*
2601NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212602 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262603 if (!nav_entry_screenshot_cache_ &&
2604 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192605 nav_entry_screenshot_cache_ =
2606 std::make_unique<NavigationEntryScreenshotCache>(
2607 BrowserContextImpl::From(browser_context_)
2608 ->GetNavigationEntryScreenshotManager()
2609 ->GetSafeRef(),
2610 this);
2611 }
2612 return nav_entry_screenshot_cache_.get();
2613}
2614
clamy987a3752018-05-03 17:36:262615void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2616 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2617 // progress, since this will cause a use-after-free. (We only allow this
2618 // when the tab is being destroyed for shutdown, since it won't return to
2619 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032620 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
Minoru Chikamune646eba42025-04-14 01:25:032621 if (can_be_in_navigate_to_pending_entry_ &&
2622 !frame_tree_->IsBeingDestroyed()) {
2623 CheckPotentialNavigationReentrancy();
2624 }
clamy987a3752018-05-03 17:36:262625
2626 if (was_failure && pending_entry_) {
2627 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2628 } else {
2629 failed_pending_entry_id_ = 0;
2630 }
2631
2632 if (pending_entry_) {
2633 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332634 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262635 pending_entry_index_ = -1;
2636 pending_entry_ = nullptr;
2637 }
arthursonzogni66f711c2019-10-08 14:40:362638
2639 // Ensure any refs to the current pending entry are ignored if they get
2640 // deleted, by clearing the set of known refs. All future pending entries will
2641 // only be affected by new refs.
2642 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262643}
2644
2645void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2646 if (pending_entry_)
2647 pending_entry_->set_ssl_error(error);
2648}
2649
Xiaohan Wang7f8052e02022-01-14 18:44:282650#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422651// static
2652bool NavigationControllerImpl::ValidateDataURLAsString(
2653 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2654 if (!data_url_as_string)
2655 return false;
2656
2657 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2658 return false;
2659
2660 // The number of characters that is enough for validating a data: URI.
2661 // From the GURL's POV, the only important part here is scheme, it doesn't
2662 // check the actual content. Thus we can take only the prefix of the url, to
2663 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562664 constexpr size_t kDataUriPrefixMaxLen = 64;
2665 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2666 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422667 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2668 return false;
2669
2670 return true;
2671}
2672#endif
2673
Shivani Sharma194877032019-03-07 17:52:472674void NavigationControllerImpl::NotifyUserActivation() {
2675 // When a user activation occurs, ensure that all adjacent entries for the
2676 // same document clear their skippable bit, so that the history manipulation
2677 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012678 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172679 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012680 // If the value of CanGoBack changes as a result of making some entries
2681 // non-skippable, then we must let the delegate know to update its UI state.
2682 // See https://crbug.com/1477784.
2683 if (!can_go_back && CanGoBack()) {
2684 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2685 }
Shivani Sharma194877032019-03-07 17:52:472686}
2687
clamy987a3752018-05-03 17:36:262688bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2689 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332690 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2691 blink::LocalFrameToken initiator_frame_token,
2692 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262693 NavigationEntryImpl* entry =
2694 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2695 if (!entry)
2696 return false;
2697
2698 FrameNavigationEntry* frame_entry =
2699 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2700 if (!frame_entry)
2701 return false;
2702
Camille Lamy5193caa2018-10-12 11:59:422703 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572704 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232705 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332706 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2707 initiator_process_id);
clamyea99ea12018-05-28 13:54:232708
2709 if (!request)
2710 return false;
2711
arthursonzognif046d4a2019-12-12 19:08:102712 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412713
Rakina Zata Amni1c83b082023-02-08 01:09:002714 SCOPED_CRASH_KEY_STRING256(
2715 "Bug1400009", "req_url",
2716 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2717 SCOPED_CRASH_KEY_NUMBER(
2718 "Bug1400009", "nav_entry_si",
2719 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2720 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2721 frame_entry->site_instance()
2722 ? ((int)frame_entry->site_instance()->GetId())
2723 : -1);
2724 bool has_sig =
2725 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2726 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2727 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2728 has_sig ? (!!frame_tree_->GetRenderViewHost(
2729 frame_entry->site_instance()->group()))
2730 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052731 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2732 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232733
2734 return true;
clamy987a3752018-05-03 17:36:262735}
2736
Tsuyoshi Horo52fd08e2020-07-07 07:03:452737bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2738 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2739 if (!entry)
2740 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432741
2742 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2743 // We should never navigate to an existing initial NavigationEntry that is
2744 // the initial NavigationEntry for the initial empty document that hasn't
2745 // been overridden by the synchronous about:blank commit, to preserve
2746 // legacy behavior where trying to reload when the main frame is on the
2747 // initial empty document won't result in a navigation. See also
2748 // https://crbug.com/1277414.
2749 return false;
2750 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452751 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2752 if (!frame_entry)
2753 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142754 ReloadType reload_type = ReloadType::NORMAL;
2755 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452756 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142757 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452758 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432759 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372760 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332761 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452762 if (!request)
2763 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052764 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452765 return true;
2766}
2767
clamy987a3752018-05-03 17:36:262768void NavigationControllerImpl::NavigateFromFrameProxy(
2769 RenderFrameHostImpl* render_frame_host,
2770 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022771 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452772 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372773 const std::optional<url::Origin>& initiator_origin,
2774 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262775 bool is_renderer_initiated,
2776 SiteInstance* source_site_instance,
2777 const Referrer& referrer,
2778 ui::PageTransition page_transition,
2779 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252780 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262781 const std::string& method,
2782 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092783 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142784 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212785 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502786 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372787 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292788 blink::mojom::NavigationInitiatorActivationAndAdStatus
2789 initiator_activation_and_ad_status,
Charlie Reise1d9b8182025-04-02 04:32:122790 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:222791 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492792 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462793 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452794 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582795 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032796 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342797 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372798 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582799 if (is_renderer_initiated)
2800 DCHECK(initiator_origin.has_value());
2801
clamy987a3752018-05-03 17:36:262802 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582803
Rakina Zata Amni2322f4f82022-01-24 13:24:242804 // Don't allow an entry replacement if there is no entry to replace.
2805 // http://crbug.com/457149
2806 if (GetEntryCount() == 0)
2807 should_replace_current_entry = false;
2808
clamy987a3752018-05-03 17:36:262809 // Create a NavigationEntry for the transfer, without making it the pending
2810 // entry. Subframe transfers should have a clone of the last committed entry
2811 // with a FrameNavigationEntry for the target frame. Main frame transfers
2812 // should have a new NavigationEntry.
2813 // TODO(creis): Make this unnecessary by creating (and validating) the params
2814 // directly, passing them to the destination RenderFrameHost. See
2815 // https://crbug.com/536906.
2816 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262817 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262818 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452819 DCHECK(GetLastCommittedEntry());
2820 entry = GetLastCommittedEntry()->Clone();
2821 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172822 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2823 // Renderer-initiated navigation that target a remote frame are currently
2824 // classified as browser-initiated when this one has already navigated.
2825 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372826 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2827 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2828 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2829 // same-document navigation), they will still be present in the
2830 // committed NavigationEntry that will be referenced to construct the new
2831 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262832 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082833 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582834 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372835 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212836 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152837 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262838 } else {
2839 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172840 // If `node` is the outermost main frame, it rewrites a virtual url in order
2841 // to adjust the original input url if needed. For inner frames such as
2842 // fenced frames or subframes, they don't rewrite urls as the urls are not
2843 // input urls by users.
2844 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372845 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322846 if (source_site_instance && source_site_instance->HasProcess()) {
2847 source_process_site_url =
2848 source_site_instance->GetProcess()->GetProcessLock().site_url();
2849 }
clamy987a3752018-05-03 17:36:262850 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212851 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322852 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212853 extra_headers, browser_context_, blob_url_loader_factory,
2854 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262855 entry->root_node()->frame_entry->set_source_site_instance(
2856 static_cast<SiteInstanceImpl*>(source_site_instance));
2857 entry->root_node()->frame_entry->set_method(method);
2858 }
clamy987a3752018-05-03 17:36:262859
Camille Lamy5193caa2018-10-12 11:59:422860 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452861 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262862 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422863 override_user_agent = true;
clamy987a3752018-05-03 17:36:262864 }
2865 // TODO(creis): Set user gesture and intent received timestamp on Android.
2866
2867 // We may not have successfully added the FrameNavigationEntry to |entry|
2868 // above (per https://crbug.com/608402), in which case we create it from
2869 // scratch. This works because we do not depend on |frame_entry| being inside
2870 // |entry| during NavigateToEntry. This will go away when we shortcut this
2871 // further in https://crbug.com/536906.
2872 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2873 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452874 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082875 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582876 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372877 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212878 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152879 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572880 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262881 }
2882
Camille Lamy5193caa2018-10-12 11:59:422883 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022884 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452885 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292886 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212887 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422888 params.source_site_instance = source_site_instance;
2889 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2890 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032891 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422892 params.referrer = referrer;
2893 /* params.redirect_chain: skip */
2894 params.extra_headers = extra_headers;
2895 params.is_renderer_initiated = is_renderer_initiated;
2896 params.override_user_agent = UA_OVERRIDE_INHERIT;
2897 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542898 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422899 /* params.data_url_as_string: skip */
2900 params.post_data = post_body;
2901 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582902 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422903 /* params.frame_name: skip */
2904 // TODO(clamy): See if user gesture should be propagated to this function.
2905 params.has_user_gesture = false;
2906 params.should_clear_history_list = false;
2907 params.started_from_context_menu = false;
2908 /* params.navigation_ui_data: skip */
2909 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222910 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542911 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212912 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412913 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502914 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292915 params.initiator_activation_and_ad_status =
2916 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032917 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422918
2919 std::unique_ptr<NavigationRequest> request =
2920 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032921 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142922 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392923 ReloadType::NONE, entry.get(), frame_entry.get(),
Charlie Reise1d9b8182025-04-02 04:32:122924 actual_navigation_start_time, navigation_start_time,
2925 is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582926 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:342927 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232928
2929 if (!request)
2930 return;
2931
Garrett Tanzerbb8db412022-09-27 21:59:462932 // Force the navigation to take place in a new browsing instance.
2933 // This is used by _unfencedTop in fenced frames to ensure that navigations
2934 // leaving the fenced context create a new browsing instance.
2935 if (force_new_browsing_instance) {
2936 request->coop_status().ForceBrowsingInstanceSwap();
2937 }
2938
Arthur Hemery948742762019-09-18 10:06:242939 // At this stage we are proceeding with this navigation. If this was renderer
2940 // initiated with user gesture, we need to make sure we clear up potential
2941 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2942 DiscardNonCommittedEntries();
2943
Lukasz Anforowicz9ee83c272020-12-01 20:14:052944 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262945}
2946
[email protected]d1198fd2012-08-13 22:50:192947void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252948 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212949 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192950 if (!session_storage_namespace)
2951 return;
2952
2953 // We can't overwrite an existing SessionStorage without violating spec.
2954 // Attempts to do so may give a tab access to another tab's session storage
2955 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152956 bool successful_insert =
2957 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252958 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052959 static_cast<SessionStorageNamespaceImpl*>(
2960 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302961 .second;
2962 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192963}
2964
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572965bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452966 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032967 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462968}
2969
Aran Gilman37d11632019-10-08 23:07:152970SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252971 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302972 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252973 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032974 DOMStorageContextWrapper* context_wrapper =
2975 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2976
2977 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252978 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032979 if (it != session_storage_namespace_map_.end()) {
2980 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152981 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2982 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472983
michaelnbacbcbd2016-02-09 00:32:032984 return it->second.get();
2985 }
2986
2987 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102988 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2989 SessionStorageNamespaceImpl::Create(context_wrapper);
2990 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2991 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252992 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102993 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302994
Daniel Murphy31bbb8b12018-02-07 21:44:102995 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302996}
2997
2998SessionStorageNamespace*
2999NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:253000 return GetSessionStorageNamespace(
3001 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:303002}
3003
3004const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573005NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303006 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553007}
[email protected]d202a7c2012-01-04 07:53:473008
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573009bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563010 return needs_reload_;
3011}
[email protected]a26023822011-12-29 00:23:553012
[email protected]46bb5e9c2013-10-03 22:16:473013void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413014 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3015}
3016
3017void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473018 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413019 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543020
3021 if (last_committed_entry_index_ != -1) {
3022 entries_[last_committed_entry_index_]->SetTransitionType(
3023 ui::PAGE_TRANSITION_RELOAD);
3024 }
[email protected]46bb5e9c2013-10-03 22:16:473025}
3026
[email protected]d202a7c2012-01-04 07:53:473027void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573028 DCHECK_LT(index, GetEntryCount());
3029 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313030 DiscardNonCommittedEntries();
3031
Nate Chapin9eb16be72022-09-23 22:54:313032 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313033 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123034 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313035 last_committed_entry_index_--;
3036}
3037
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573038NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273039 // If there is no pending_entry_, there should be no pending_entry_index_.
3040 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3041
3042 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363043 // at that index. An exception is while a reload of a post commit error page
3044 // is ongoing; in that case pending entry will point to the entry replaced
3045 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273046 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363047 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3048 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273049
[email protected]022af742011-12-28 18:37:253050 return pending_entry_;
3051}
3052
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573053int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273054 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273055 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553056 return pending_entry_index_;
3057}
3058
avi25764702015-06-23 15:43:373059void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573060 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363061 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313062 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003063 bool in_fenced_frame_tree,
3064 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313065 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3066 // set because:
3067 // 1) They don't influence the history of the outer page.
3068 // 2) They are always replace only navigation (there is always only one entry
3069 // in their history stack).
3070 // 3) Are not top level navigations and appear similar to iframes.
3071 // Navigations of the fenced frame might create a new NavigationEntry, which
3072 // will call this function. Non fenced frame navigations will never have
3073 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3074 // InsertOrReplaceEntry.
3075 DCHECK_EQ(in_fenced_frame_tree,
3076 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3077 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203078
avi5cad4912015-06-19 05:25:443079 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3080 // need to keep continuity with the pending entry, so copy the pending entry's
3081 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3082 // then the renderer navigated on its own, independent of the pending entry,
3083 // so don't copy anything.
3084 if (pending_entry_ && pending_entry_index_ == -1)
3085 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203086
Rakina Zata Amnia4e27222021-12-22 01:05:003087 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203088
creisee17e932015-07-17 17:56:223089 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453090 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103091 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573092 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363093 // If the new entry is a post-commit error page, we store the current last
3094 // committed entry to the side so that we can put it back when navigating
3095 // away from the error.
3096 if (was_post_commit_error) {
3097 DCHECK(!entry_replaced_by_post_commit_error_);
3098 entry_replaced_by_post_commit_error_ =
3099 std::move(entries_[last_committed_entry_index_]);
3100 }
dcheng36b6aec92015-12-26 06:16:363101 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223102 return;
3103 }
[email protected]765b35502008-08-21 00:51:203104
creis37979a62015-08-04 19:48:183105 // We shouldn't see replace == true when there's no committed entries.
3106 DCHECK(!replace);
3107
Michael Thiessen9b14d512019-09-23 21:19:473108 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203109
Shivani Sharmad8c8d652019-02-13 17:27:573110 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203111
dcheng36b6aec92015-12-26 06:16:363112 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203113 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293114}
3115
Shivani Sharmad8c8d652019-02-13 17:27:573116void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163117 if (entries_.size() < max_entry_count())
3118 return;
3119
3120 DCHECK_EQ(max_entry_count(), entries_.size());
3121 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573122 CHECK_EQ(pending_entry_index_, -1);
3123
3124 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423125 // Retrieve the oldest skippable entry.
3126 for (; index < GetEntryCount(); index++) {
3127 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3128 break;
Shivani Sharmad8c8d652019-02-13 17:27:573129 }
3130
3131 // If there is no skippable entry or if it is the last committed entry then
3132 // fall back to pruning the oldest entry. It is not safe to prune the last
3133 // committed entry.
3134 if (index == GetEntryCount() || index == last_committed_entry_index_)
3135 index = 0;
3136
3137 bool should_succeed = RemoveEntryAtIndex(index);
3138 DCHECK_EQ(true, should_succeed);
3139
3140 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253141}
3142
William Liu62ae26c2024-08-08 14:28:163143std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273144NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163145 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203146 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373147 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133148 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203149 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503150 TRACE_EVENT0("navigation",
3151 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273152 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023153 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363154 if (pending_entry_index_ != -1) {
3155 // The pending entry may not be in entries_ if a post-commit error page is
3156 // showing.
3157 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3158 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3159 }
Gyuyoung Kim107c2a02021-04-13 01:49:303160 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573161 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013162 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033163 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573164 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133165 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3166 // the same as the top level frame being navigated.
3167 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373168 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133169 }
Arthur Sonzogni620cec62018-12-13 13:08:573170
[email protected]83c2e232011-10-07 21:36:463171 // If we were navigating to a slow-to-commit page, and the user performs
3172 // a session history navigation to the last committed page, RenderViewHost
3173 // will force the throbber to start, but WebKit will essentially ignore the
3174 // navigation, and won't send a message to stop the throbber. To prevent this
3175 // from happening, we drop the navigation here and stop the slow-to-commit
3176 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023177 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083178 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273179 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033180 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123181
[email protected]83c2e232011-10-07 21:36:463182 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163183 return {};
[email protected]83c2e232011-10-07 21:36:463184 }
3185
Arthur Sonzognic686e8f2024-01-11 08:36:373186 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333187 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3188 if (initiator_rfh) {
3189 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543190 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333191 DCHECK(initiator_frame_token);
3192 }
3193
creisce0ef3572017-01-26 17:53:083194 // Compare FrameNavigationEntries to see which frames in the tree need to be
3195 // navigated.
clamy3cb9bea92018-07-10 12:42:023196 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3197 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333198 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3199 initiator_process_id, soft_navigation_heuristics_task_id,
3200 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303201
3202 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573203 // We were unable to match any frames to navigate. This can happen if a
3204 // history navigation targets a subframe that no longer exists
3205 // (https://crbug.com/705550). In this case, we need to update the current
3206 // history entry to the pending one but keep the main document loaded. We
3207 // also need to ensure that observers are informed about the updated
3208 // current history entry (e.g., for greying out back/forward buttons), and
Charlie Reis99b2eba22025-01-31 19:18:573209 // that renderer processes update their history indices. The easiest way
Alex Moshchuk3a4e77a2020-05-29 21:32:573210 // to do all that is to schedule a "redundant" same-document navigation in
3211 // the main frame.
3212 //
3213 // Note that we don't want to remove this history entry, as it might still
3214 // be valid later, since a frame that it's targeting may be recreated.
3215 //
3216 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3217 // need to repeat history navigations until finding the one that works.
3218 // Consider changing this behavior to keep looking for the first valid
3219 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023220 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423221 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573222 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573223 ReloadType::NONE /* reload_type */,
3224 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433225 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333226 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023227 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573228 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023229 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163230 return {};
clamy3cb9bea92018-07-10 12:42:023231 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573232 same_document_loads.push_back(std::move(navigation_request));
3233
3234 // Sanity check that we never take this branch for any kinds of reloads,
3235 // as those should've queued a different-document load in the main frame.
3236 DCHECK(!is_forced_reload);
3237 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303238 }
3239
Nate Chapinbf682fa32022-09-26 22:41:203240 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163241 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203242 if (initiator_rfh && initiator_rfh->IsSandboxed(
3243 network::mojom::WebSandboxFlags::kTopNavigation)) {
3244 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3245 initiator_rfh, same_document_loads) &&
3246 DoesSandboxNavigationStayWithinSubtree(
3247 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503248 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163249 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203250 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3251 initiator_rfh,
3252 navigates_inside_tree
3253 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3254 : blink::mojom::WebFeature::
3255 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523256
3257 // If the navigation occurred outside the tree discard it because
3258 // the sandboxed frame didn't have permission to navigate outside
3259 // its tree. If it is possible that the navigation is both inside and
3260 // outside the frame tree and we discard it entirely because we don't
3261 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143262 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203263 // If a |navigation_api_key| was provided, this navigation originated from
3264 // the navigation API. Notify the renderer that the navigation was
3265 // cancelled so the navigation API can fire an error event and reject the
3266 // relevant promise.
3267 if (navigation_api_key) {
3268 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3269 *navigation_api_key,
3270 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3271 }
Dave Tapuska855c1e12019-08-23 20:45:523272 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133273
3274 for (auto& unused_request : same_document_loads) {
3275 unused_request->set_navigation_discard_reason(
3276 NavigationDiscardReason::kNeverStarted);
3277 }
3278 for (auto& unused_request : different_document_loads) {
3279 unused_request->set_navigation_discard_reason(
3280 NavigationDiscardReason::kNeverStarted);
3281 }
William Liu62ae26c2024-08-08 14:28:163282 return {};
Dave Tapuska855c1e12019-08-23 20:45:523283 }
Dave Tapuska8bfd84c2019-03-26 20:47:163284 }
3285
Nate Chapin6c43c022023-02-13 23:32:423286 // If it is possible that this traverse may involve a same-document navigation
3287 // in the initiator and there is a Navigation API key involved, then we may
3288 // need to notify the initiator if it fails. (The early returns above either
3289 // do not involve these cases or already notify the initiator.)
3290 // The event only needs to fire for the initiator, and only if the initiator
3291 // itself is performing a same-document navigation (because the event will not
3292 // fire if it navigates cross-document).
3293 if (navigation_api_key) {
3294 for (auto& item : same_document_loads) {
3295 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3296 item->set_pending_navigation_api_key(*navigation_api_key);
3297 break;
3298 }
3299 }
3300 }
3301
Carlos Caballero539a421c2020-07-06 10:25:573302 // BackForwardCache:
3303 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563304 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573305 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3306 DCHECK_EQ(reload_type, ReloadType::NONE);
3307 auto navigation_request = CreateNavigationRequestFromEntry(
3308 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3309 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333310 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3311 initiator_process_id);
William Liuec04e382024-05-23 18:03:273312 base::WeakPtr<NavigationRequest> request = navigation_request->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053313 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Rakina Zata Amni58681c62024-06-25 06:32:133314
3315 for (auto& unused_request : same_document_loads) {
3316 unused_request->set_navigation_discard_reason(
3317 NavigationDiscardReason::kNeverStarted);
3318 }
3319 for (auto& unused_request : different_document_loads) {
3320 unused_request->set_navigation_discard_reason(
3321 NavigationDiscardReason::kNeverStarted);
3322 }
3323
William Liu62ae26c2024-08-08 14:28:163324 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_request;
3325 if (request) {
3326 bf_cache_request.push_back(std::move(request));
3327 }
3328 return bf_cache_request;
Carlos Caballero539a421c2020-07-06 10:25:573329 }
3330
3331 // History navigation might try to reuse a specific BrowsingInstance, already
3332 // used by a page in the cache. To avoid having two different main frames that
3333 // live in the same BrowsingInstance, evict the all pages with this
3334 // BrowsingInstance from the cache.
3335 //
3336 // For example, take the following scenario:
3337 //
3338 // A1 = Some page on a.com
3339 // A2 = Some other page on a.com
3340 // B3 = An uncacheable page on b.com
3341 //
3342 // Then the following navigations occur:
3343 // A1->A2->B3->A1
3344 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3345 // take its place) and A1 will be created in the same BrowsingInstance (and
3346 // SiteInstance), as A2.
3347 //
3348 // If we didn't do anything, both A1 and A2 would remain alive in the same
3349 // BrowsingInstance/SiteInstance, which is unsupported by
3350 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3351 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483352 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3353 pending_entry_->site_instance()
3354 ? pending_entry_->site_instance()->GetId().value()
3355 : -1);
3356 SCOPED_CRASH_KEY_NUMBER(
3357 "rvh_double", "pending_entry_bi",
3358 pending_entry_->site_instance()
3359 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3360 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573361 if (pending_entry_->site_instance()) {
3362 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3363 pending_entry_->site_instance());
3364 }
3365
Rakina Zata Amnid605d462022-06-01 10:17:033366 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3367 pending_entry_ && pending_entry_->IsRestored());
3368 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3369 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3370 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3371 pending_entry_index_);
3372 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3373 last_committed_entry_index_);
3374 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3375 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3376 pending_entry_ && pending_entry_->IsInitialEntry());
3377 SCOPED_CRASH_KEY_BOOL(
3378 "nav_reentrancy", "pending_entry_initial2",
3379 pending_entry_ &&
3380 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3381 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3382 IsInitialNavigation());
3383 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3384 IsInitialBlankNavigation());
3385 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3386 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3387 (int)pending_reload_);
3388
clamy3cb9bea92018-07-10 12:42:023389 // This call does not support re-entrancy. See http://crbug.com/347742.
3390 CHECK(!in_navigate_to_pending_entry_);
3391 in_navigate_to_pending_entry_ = true;
Minoru Chikamune646eba42025-04-14 01:25:033392 CheckPotentialNavigationReentrancy();
creis4e2ecb72015-06-20 00:46:303393
Rakina Zata Amnid605d462022-06-01 10:17:033394 // If the navigation-reentrancy is caused by calling
3395 // NavigateToExistingPendingEntry twice, this will note the previous call's
3396 // pending entry's ID.
3397 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3398 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3399
arthursonzogni66f711c2019-10-08 14:40:363400 // It is not possible to delete the pending NavigationEntry while navigating
3401 // to it. Grab a reference to delay potential deletion until the end of this
3402 // function.
3403 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3404
Nate Chapin154b14b2023-02-17 18:28:163405 // If there is a main-frame same-document history navigation, we may defer
3406 // the subframe history navigations in order to give JS in the main frame the
3407 // opportunity to cancel the entire traverse via the navigate event. In that
3408 // case, we need to stash the main frame request's navigation token on the
3409 // subframes, so they can look up the main frame request and defer themselves
3410 // until it completes.
3411 if (!same_document_loads.empty() &&
3412 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3413 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3414 // The token will only be returned in cases where deferring the navigation
3415 // is necessary.
3416 if (auto main_frame_same_document_token =
3417 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3418 for (auto& item : same_document_loads) {
3419 if (item.get() != main_frame_request) {
3420 item->set_main_frame_same_document_history_token(
3421 main_frame_same_document_token);
3422 }
3423 }
3424 for (auto& item : different_document_loads) {
3425 item->set_main_frame_same_document_history_token(
3426 main_frame_same_document_token);
3427 }
3428 }
3429 }
3430
William Liu122754942024-01-18 22:34:393431 if (!initiator_rfh) {
3432 // A browser-initiated navigation won't have a `initiator_rfh`.
3433 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3434 different_document_loads, same_document_loads);
3435 }
3436
William Liu62ae26c2024-08-08 14:28:163437 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3438 all_requests.reserve(same_document_loads.size() +
3439 different_document_loads.size());
3440 bool seen_primary_main_frame_request = false;
3441
creis4e2ecb72015-06-20 00:46:303442 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023443 for (auto& item : same_document_loads) {
3444 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273445 // The request could be destroyed before `navigator().Navigate()` returns.
3446 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053447 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163448 if (request) {
3449 // Can only have one primary main frame request.
3450 CHECK(!seen_primary_main_frame_request ||
3451 !request->IsInPrimaryMainFrame());
3452 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3453 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273454 }
creis4e2ecb72015-06-20 00:46:303455 }
clamy3cb9bea92018-07-10 12:42:023456 for (auto& item : different_document_loads) {
3457 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273458 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053459 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163460 if (request) {
3461 // Can only have one primary main frame request.
3462 CHECK(!seen_primary_main_frame_request ||
3463 !request->IsInPrimaryMainFrame());
3464 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3465 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273466 }
creis4e2ecb72015-06-20 00:46:303467 }
clamy3cb9bea92018-07-10 12:42:023468
3469 in_navigate_to_pending_entry_ = false;
William Liuec04e382024-05-23 18:03:273470
William Liu62ae26c2024-08-08 14:28:163471 return all_requests;
creis4e2ecb72015-06-20 00:46:303472}
3473
Alex Moshchuk3a4e77a2020-05-29 21:32:573474NavigationControllerImpl::HistoryNavigationAction
3475NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303476 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573477 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423478 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583479 // Only active and prerendered documents are allowed to navigate in their
3480 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423481 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013482 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583483 // - If the document is in pending deletion, the browser already committed
3484 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3485 // - If the document is in back-forward cache, it's not allowed to navigate
3486 // as it should remain frozen. Ignore the request and evict the document
3487 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423488 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583489 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423490 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113491 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3492 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423493 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113494 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423495 }
arthursonzogni03f76152019-02-12 10:35:203496
Alex Moshchuk3a4e77a2020-05-29 21:32:573497 // Reloads should result in a different-document load. Note that reloads may
3498 // also happen via the |needs_reload_| mechanism where the reload_type is
3499 // NONE, so detect this by comparing whether we're going to the same
3500 // entry that we're currently on. Similarly to above, only main frames
3501 // should reach this. Note that subframes support reloads, but that's done
3502 // via a different path that doesn't involve FindFramesToNavigate (see
3503 // RenderFrameHost::Reload()).
3504 if (reload_type != ReloadType::NONE ||
3505 pending_entry_index_ == last_committed_entry_index_) {
3506 DCHECK(frame->IsMainFrame());
3507 return HistoryNavigationAction::kDifferentDocument;
3508 }
3509
Alex Moshchuk47d1a4bd2020-06-01 22:15:343510 // If there is no new FrameNavigationEntry for the frame, ignore the
3511 // load. For example, this may happen when going back to an entry before a
3512 // frame was created. Suppose we commit a same-document navigation that also
3513 // results in adding a new subframe somewhere in the tree. If we go back,
3514 // the new subframe will be missing a FrameNavigationEntry in the previous
3515 // NavigationEntry, but we shouldn't delete or change what's loaded in
3516 // it.
3517 //
Alex Moshchuke65c39272020-06-03 17:55:373518 // Note that in this case, there is no need to keep looking for navigations
3519 // in subframes, which would be missing FrameNavigationEntries as well.
3520 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343521 // It's important to check this before checking |old_item| below, since both
3522 // might be null, and in that case we still shouldn't change what's loaded in
3523 // this frame. Note that scheduling any loads assumes that |new_item| is
3524 // non-null. See https://crbug.com/1088354.
3525 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3526 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373527 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343528
Charlie Reisa474fb62022-03-17 02:31:363529 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3530 // which history item it is currently on, since this may be different than the
3531 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3532 // (e.g., if a history navigation is targeting multiple frames and only some
3533 // have committed so far).
creis4e2ecb72015-06-20 00:46:303534 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363535 frame->current_frame_host()->last_committed_frame_entry();
3536 if (!old_item) {
3537 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3538 // fall back to the last committed NavigationEntry's record for this frame.
3539 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583540 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363541 // accurate FrameNavigationEntry and eliminate this case.
3542 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3543 }
3544 // If neither approach finds a FrameNavigationEntry, schedule a
3545 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583546 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573547 if (!old_item)
3548 return HistoryNavigationAction::kDifferentDocument;
3549
Alex Moshchuk3a4e77a2020-05-29 21:32:573550 // If the new item is not in the same SiteInstance, schedule a
3551 // different-document load. Newly restored items may not have a SiteInstance
3552 // yet, in which case it will be assigned on first commit.
3553 if (new_item->site_instance() &&
3554 new_item->site_instance() != old_item->site_instance())
3555 return HistoryNavigationAction::kDifferentDocument;
3556
Charlie Reis71e4ae32025-01-29 21:37:573557 // If the origins of the new and old items are both present but don't match,
3558 // schedule a different document load even if the document sequence numbers
3559 // somehow match.
3560 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3561 // committed origin on `new_item`, and update the Blink DSN computation to
3562 // avoid a cross-origin DSN match when possible.
3563 if (new_item->committed_origin().has_value() &&
3564 old_item->committed_origin().has_value() &&
3565 !new_item->committed_origin()->IsSameOriginWith(
3566 old_item->committed_origin().value())) {
3567 return HistoryNavigationAction::kDifferentDocument;
3568 }
3569
Alex Moshchuk3a4e77a2020-05-29 21:32:573570 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313571 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3572 // that we do this even if the history navigation would not be modifying this
3573 // frame were it live.
3574 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573575 return HistoryNavigationAction::kDifferentDocument;
3576
3577 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313578 // Starting a navigation after a crash early-promotes the speculative
3579 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3580 // committed yet, so we can not possibly perform a same-document history
3581 // navigation. The frame would need to be reloaded with a cross-document
3582 // navigation.
3583 if (!frame->current_frame_host()->has_committed_any_navigation())
3584 return HistoryNavigationAction::kDifferentDocument;
3585
creis54131692016-08-12 18:32:253586 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493587 // sequence number but different item sequence number.
3588 if (new_item->document_sequence_number() ==
3589 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573590 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493591 }
avib48cb312016-05-05 21:35:003592
Alex Moshchuk3a4e77a2020-05-29 21:32:573593 // Otherwise, if both item and document sequence numbers differ, this
3594 // should be a different document load.
3595 return HistoryNavigationAction::kDifferentDocument;
3596 }
3597
3598 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373599 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573600 DCHECK_EQ(new_item->document_sequence_number(),
3601 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373602 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573603}
3604
3605void NavigationControllerImpl::FindFramesToNavigate(
3606 FrameTreeNode* frame,
3607 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373608 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333609 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373610 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133611 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573612 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3613 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3614 DCHECK(pending_entry_);
3615 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3616
3617 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3618
3619 if (action == HistoryNavigationAction::kSameDocument) {
3620 std::unique_ptr<NavigationRequest> navigation_request =
3621 CreateNavigationRequestFromEntry(
3622 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133623 /*is_same_document_history_load=*/true,
3624 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333625 initiator_frame_token, initiator_process_id,
3626 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573627 if (navigation_request) {
3628 // Only add the request if was properly created. It's possible for the
3629 // creation to fail in certain cases, e.g. when the URL is invalid.
3630 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303631 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573632 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473633 std::unique_ptr<NavigationRequest> navigation_request =
3634 CreateNavigationRequestFromEntry(
3635 frame, pending_entry_, new_item, reload_type,
3636 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433637 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333638 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473639 if (navigation_request) {
3640 // Only add the request if was properly created. It's possible for the
3641 // creation to fail in certain cases, e.g. when the URL is invalid.
3642 different_document_loads->push_back(std::move(navigation_request));
3643 }
3644 // For a different document, the subframes will be destroyed, so there's
3645 // no need to consider them.
3646 return;
Alex Moshchuke65c39272020-06-03 17:55:373647 } else if (action == HistoryNavigationAction::kStopLooking) {
3648 return;
creis4e2ecb72015-06-20 00:46:303649 }
3650
Yoav Weiss8c573952022-11-17 17:35:133651 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3652 // we currently only support soft navigation heuristics for the top level
3653 // frame.
creis4e2ecb72015-06-20 00:46:303654 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333655 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3656 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373657 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433658 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303659 }
3660}
3661
Harkiran Bolariaba823e42021-05-21 18:30:363662base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243663 const LoadURLParams& params) {
3664 // Find the appropriate FrameTreeNode.
3665 FrameTreeNode* node = nullptr;
Avi Drissmanbd153642024-09-03 18:58:053666 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3667 node = params.frame_tree_node_id
Ali Hijazid87307d2022-11-07 20:15:033668 ? frame_tree_->FindByID(params.frame_tree_node_id)
3669 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503670 DCHECK(!node || &node->frame_tree() == &frame_tree());
Kevin McNee37a109792025-04-14 21:16:383671 if (!node && params.frame_tree_node_id) {
3672 // If the specified FrameTreeNode exists in another FrameTree, the caller
3673 // is using the wrong NavigationController.
3674 CHECK(!FrameTreeNode::GloballyFindByID(params.frame_tree_node_id),
3675 base::NotFatalUntil::M140);
3676 }
clamy21718cc22018-06-13 13:34:243677 }
3678
3679 // If no FrameTreeNode was specified, navigate the main frame.
3680 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033681 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243682
Camille Lamy5193caa2018-10-12 11:59:423683 // Compute overrides to the LoadURLParams for |override_user_agent|,
3684 // |should_replace_current_entry| and |has_user_gesture| that will be used
3685 // both in the creation of the NavigationEntry and the NavigationRequest.
3686 // Ideally, the LoadURLParams themselves would be updated, but since they are
3687 // passed as a const reference, this is not possible.
3688 // TODO(clamy): When we only create a NavigationRequest, move this to
3689 // CreateNavigationRequestFromLoadURLParams.
3690 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3691 GetLastCommittedEntry());
3692
Rakina Zata Amnie2d31312022-11-18 03:38:453693 // An entry replacement must happen if the current browsing context should
3694 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333695 bool should_replace_current_entry =
3696 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453697 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423698
clamy21718cc22018-06-13 13:34:243699 // Javascript URLs should not create NavigationEntries. All other navigations
3700 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243701 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373702 std::unique_ptr<NavigationEntryImpl> entry =
3703 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3704 should_replace_current_entry,
3705 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243706 DiscardPendingEntry(false);
3707 SetPendingEntry(std::move(entry));
3708 }
3709
Tim Judkins59548192023-05-17 17:51:203710 // Renderer-debug URLs are sent to the current renderer process immediately
3711 // for processing and don't need to create a NavigationRequest. Note: this
3712 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243713 // renderer-debug URLs.
3714 // Note: we intentionally leave the pending entry in place for renderer debug
3715 // URLs, unlike the cases below where we clear it if the navigation doesn't
3716 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303717 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483718 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3719 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153720 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203721 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483722 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363723 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483724 }
3725
clamy21718cc22018-06-13 13:34:243726 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363727 return nullptr;
clamy21718cc22018-06-13 13:34:243728 }
3729
Antonio Sartori78a749f2020-11-30 12:03:393730 DCHECK(pending_entry_);
3731
clamy21718cc22018-06-13 13:34:243732 // Convert navigations to the current URL to a reload.
3733 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3734 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3735 // DevTools sometimes issues navigations to main frames that they do not
3736 // expect to see treated as reload, and it only works because they pass a
3737 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3738 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543739 ReloadType reload_type = params.reload_type;
3740 if (reload_type == ReloadType::NONE &&
3741 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043742 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243743 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243744 params.load_type ==
3745 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543746 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243747 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473748 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393749
3750 // If this is a reload of an existing FrameNavigationEntry and we had a
3751 // policy container for it, then we should copy it into the pending entry,
3752 // so that it is copied to the navigation request in
3753 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453754 FrameNavigationEntry* previous_frame_entry =
3755 GetLastCommittedEntry()->GetFrameEntry(node);
3756 if (previous_frame_entry &&
3757 previous_frame_entry->policy_container_policies()) {
3758 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3759 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393760 }
3761 }
3762
3763 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173764 // document, then we should copy the document polices from RenderFrameHost's
3765 // PolicyContainerHost. The NavigationRequest will create a new
3766 // PolicyContainerHost with the document policies from the |pending_entry_|,
3767 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3768 // the navigation. This way, we ensure that we keep enforcing the right
3769 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453770 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393771 if (node->current_frame_host() &&
3772 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193773 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163774 node->current_frame_host()
3775 ->policy_container_host()
3776 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233777 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393778 }
clamy21718cc22018-06-13 13:34:243779 }
3780
3781 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263782 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243783
Tsuyoshi Horo167ca6432022-03-09 05:16:393784 // This will be used to set the Navigation Timing API navigationStart
3785 // parameter for browser navigations in new tabs (intents, tabs opened through
3786 // "Open link in new tab"). If the navigation must wait on the current
3787 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3788 // will be updated when the BeforeUnload ack is received.
3789 const auto navigation_start_time = base::TimeTicks::Now();
Charlie Reise1d9b8182025-04-02 04:32:123790 // For now, treat this as the actual navigation start time as well, even
3791 // though a fair amount of work is done in the browser process between the
3792 // various ways to start a navigation and reaching here (e.g., sending
3793 // OpenURLParams through the embedder and converting them to LoadURLParams).
3794 // Note that this may be used for some renderer-initiated navigations that go
3795 // through RenderFrameHostImpl::OpenURL as well.
3796 // TODO(crbug.com/385170155): Consider whether tracking this earlier work with
3797 // an earlier start time is worthwhile for metrics.
3798 const auto actual_navigation_start_time = navigation_start_time;
Tsuyoshi Horo167ca6432022-03-09 05:16:393799
Camille Lamy5193caa2018-10-12 11:59:423800 std::unique_ptr<NavigationRequest> request =
3801 CreateNavigationRequestFromLoadParams(
3802 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143803 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393804 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
Charlie Reise1d9b8182025-04-02 04:32:123805 actual_navigation_start_time, navigation_start_time);
clamy21718cc22018-06-13 13:34:243806
3807 // If the navigation couldn't start, return immediately and discard the
3808 // pending NavigationEntry.
3809 if (!request) {
3810 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363811 return nullptr;
clamy21718cc22018-06-13 13:34:243812 }
3813
Camille Lamy5193caa2018-10-12 11:59:423814#if DCHECK_IS_ON()
3815 // Safety check that NavigationRequest and NavigationEntry match.
3816 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3817#endif
3818
clamy21718cc22018-06-13 13:34:243819 // This call does not support re-entrancy. See http://crbug.com/347742.
3820 CHECK(!in_navigate_to_pending_entry_);
3821 in_navigate_to_pending_entry_ = true;
Minoru Chikamune646eba42025-04-14 01:25:033822 CheckPotentialNavigationReentrancy();
clamy21718cc22018-06-13 13:34:243823
arthursonzogni66f711c2019-10-08 14:40:363824 // It is not possible to delete the pending NavigationEntry while navigating
3825 // to it. Grab a reference to delay potential deletion until the end of this
3826 // function.
3827 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3828
Harkiran Bolariaba823e42021-05-21 18:30:363829 base::WeakPtr<NavigationHandle> created_navigation_handle(
3830 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053831 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243832
3833 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363834 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243835}
3836
clamyea99ea12018-05-28 13:54:233837void NavigationControllerImpl::HandleRendererDebugURL(
3838 FrameTreeNode* frame_tree_node,
3839 const GURL& url) {
3840 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243841 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3842 // the renderer process is not live, unless it is the initial navigation
3843 // of the tab.
clamyea99ea12018-05-28 13:54:233844 if (!IsInitialNavigation()) {
3845 DiscardNonCommittedEntries();
3846 return;
3847 }
Fergal Dalyecd3b0202020-06-25 01:57:373848 // The current frame is always a main frame. If IsInitialNavigation() is
3849 // true then there have been no navigations and any frames of this tab must
3850 // be in the same renderer process. If that has crashed then the only frame
3851 // that can be revived is the main frame.
3852 frame_tree_node->render_manager()
3853 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233854 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223855
3856 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3857 // notification, so set is loading to true here to properly surface it when
3858 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313859 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223860 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223861 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223862 }
clamyea99ea12018-05-28 13:54:233863 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3864}
3865
clamy21718cc22018-06-13 13:34:243866std::unique_ptr<NavigationEntryImpl>
3867NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3868 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423869 const LoadURLParams& params,
3870 bool override_user_agent,
3871 bool should_replace_current_entry,
3872 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393873 // Browser initiated navigations might not have a blob_url_loader_factory set
3874 // in params even if the navigation is to a blob URL. If that happens, lookup
3875 // the correct url loader factory to use here.
3876 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483877 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473878 // Resolve the blob URL in the storage partition associated with the target
3879 // frame. This is the storage partition the URL will be loaded in, and only
3880 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393881 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473882 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393883 }
3884
clamy21718cc22018-06-13 13:34:243885 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443886 // extra_headers in params are \n separated; navigation entries want \r\n.
3887 std::string extra_headers_crlf;
3888 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243889
3890 // For subframes, create a pending entry with a corresponding frame entry.
3891 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453892 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243893 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083894 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243895 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373896 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213897 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3898 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393899 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163900 // a conversion of a new navigation into a reload, we will set the right
3901 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193902 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243903 } else {
3904 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173905 // If `node` is the outermost main frame, it rewrites a virtual url in order
3906 // to adjust the original input url if needed. For inner frames such as
3907 // fenced frames or subframes, they don't rewrite urls as the urls are not
3908 // input urls by users.
3909 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323910 scoped_refptr<SiteInstance> source_site_instance =
3911 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373912 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323913 if (source_site_instance && source_site_instance->HasProcess()) {
3914 source_process_site_url =
3915 source_site_instance->GetProcess()->GetProcessLock().site_url();
3916 }
clamy21718cc22018-06-13 13:34:243917 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063918 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323919 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213920 params.transition_type, params.is_renderer_initiated,
3921 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3922 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243923 entry->set_source_site_instance(
3924 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3925 entry->SetRedirectChain(params.redirect_chain);
3926 }
3927
3928 // Set the FTN ID (only used in non-site-per-process, for tests).
3929 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243930 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423931 entry->SetIsOverridingUserAgent(override_user_agent);
3932 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543933 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243934
clamy21718cc22018-06-13 13:34:243935 switch (params.load_type) {
3936 case LOAD_TYPE_DEFAULT:
3937 break;
3938 case LOAD_TYPE_HTTP_POST:
3939 entry->SetHasPostData(true);
3940 entry->SetPostData(params.post_data);
3941 break;
3942 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:543943 // LoadDataWithBaseURL is a special case that needs to assign both a base
3944 // URL and a virtual URL, while loading the actual content from a data
3945 // URL.
clamy21718cc22018-06-13 13:34:243946 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:543947 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:283948#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243949 entry->SetDataURLAsString(params.data_url_as_string);
3950#endif
3951 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3952 break;
Shu Yang112ad492024-07-25 17:11:543953#if BUILDFLAG(IS_ANDROID)
3954 case LOAD_TYPE_PDF_ANDROID:
3955 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
3956 // internal URL is used for the navigation URL.
3957 entry->SetVirtualURL(params.virtual_url_for_special_cases);
3958 break;
3959#endif
clamy21718cc22018-06-13 13:34:243960 }
3961
3962 // TODO(clamy): NavigationEntry is meant for information that will be kept
3963 // after the navigation ended and therefore is not appropriate for
3964 // started_from_context_menu. Move started_from_context_menu to
3965 // NavigationUIData.
3966 entry->set_started_from_context_menu(params.started_from_context_menu);
3967
3968 return entry;
3969}
3970
clamyea99ea12018-05-28 13:54:233971std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423972NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3973 FrameTreeNode* node,
3974 const LoadURLParams& params,
3975 bool override_user_agent,
3976 bool should_replace_current_entry,
3977 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143978 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423979 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573980 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393981 FrameNavigationEntry* frame_entry,
Charlie Reise1d9b8182025-04-02 04:32:123982 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:223983 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493984 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453985 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583986 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343987 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:373988 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573989 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:523990
3991 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
3992 // subframes have FrameNavigationEntries associated with them. Until then,
3993 // there may be cases where a subframe navigation is missing `frame_entry`
3994 // (e.g., see https://crbug.com/358084015).
3995
Nasko Oskov3c2f9e252019-01-10 17:45:533996 // All renderer-initiated navigations must have an initiator_origin.
3997 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513998
Camille Lamy5193caa2018-10-12 11:59:423999 GURL url_to_load;
4000 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:324001
Camille Lamy2baa8022018-10-19 16:43:174002 // For main frames, rewrite the URL if necessary and compute the virtual URL
4003 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:264004 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424005 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:174006 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424007 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:424008
Shu Yang112ad492024-07-25 17:11:544009 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
4010 // that need to define a virtual URL to display, which differs from the
4011 // navigation URL.
4012 if (params.load_type == LOAD_TYPE_DATA) {
4013 virtual_url = params.virtual_url_for_special_cases;
4014 }
4015#if BUILDFLAG(IS_ANDROID)
4016 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
4017 virtual_url = params.virtual_url_for_special_cases;
4018 }
4019#endif
Camille Lamy5193caa2018-10-12 11:59:424020
Camille Lamy2baa8022018-10-19 16:43:174021 if (virtual_url.is_empty())
4022 virtual_url = url_to_load;
4023
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574024 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:284025
Aran Gilman249eb122019-12-02 23:32:464026 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
4027 // behavior: it is possible for two calls to RewriteUrlForNavigation to
4028 // return different results, leading to a different URL in the
4029 // NavigationRequest and FrameEntry. This will be fixed once we remove the
4030 // pending NavigationEntry, as we'll only make one call to
4031 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:524032 if (frame_entry) {
4033 VLOG_IF(1, (url_to_load != frame_entry->url()))
4034 << "NavigationRequest and FrameEntry have different URLs: "
4035 << url_to_load << " vs " << frame_entry->url();
4036 }
Camille Lamyb9ed3c52018-11-19 15:34:284037
Camille Lamy2baa8022018-10-19 16:43:174038 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424039 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174040 // NavigationRequest.
4041 } else {
4042 url_to_load = params.url;
4043 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244044 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174045 }
Camille Lamy5193caa2018-10-12 11:59:424046
Ehsan Karamad44fc72112019-02-26 18:15:474047 if (node->render_manager()->is_attaching_inner_delegate()) {
4048 // Avoid starting any new navigations since this node is now preparing for
4049 // attaching an inner delegate.
4050 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204051 }
Camille Lamy5193caa2018-10-12 11:59:424052
Alex Moshchuk99242832023-05-22 17:21:444053 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424054 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444055 }
Camille Lamy5193caa2018-10-12 11:59:424056
danakjd83d706d2020-11-25 22:11:124057 // Look for a pending commit that is to another document in this
4058 // FrameTreeNode. If one exists, then the last committed URL will not be the
4059 // current URL by the time this navigation commits.
4060 bool has_pending_cross_document_commit =
4061 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214062 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124063
Minggang Wangb9f3fa92021-07-01 15:30:314064 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494065 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524066 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494067 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134068 /*is_same_document_history_load=*/false,
4069 is_embedder_initiated_fenced_frame_navigation,
4070 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424071
4072 // Create the NavigationParams based on |params|.
4073
Hiroki Nakagawa4ed61282021-06-18 05:37:234074 bool is_view_source_mode = entry->IsViewSourceMode();
4075 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294076
Antonio Sartori6984c742021-08-26 08:03:414077 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294078
Hiroki Nakagawa4ed61282021-06-18 05:37:234079 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294080 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254081 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294082
Charlie Reisf21cd182024-08-09 21:44:524083 std::string page_state_data =
4084 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4085
Minggang Wangb9f3fa92021-07-01 15:30:314086 blink::mojom::CommonNavigationParamsPtr common_params =
4087 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214088 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514089 blink::mojom::Referrer::New(params.referrer.url,
4090 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214091 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514092 should_replace_current_entry, params.base_url_for_data_url,
Charlie Reise1d9b8182025-04-02 04:32:124093 actual_navigation_start_time, navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514094 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144095 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414096 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274097 false /* has_text_fragment_token */,
4098 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4099 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514100 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054101 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424102
Minggang Wangb9f3fa92021-07-01 15:30:314103 blink::mojom::CommitNavigationParamsPtr commit_params =
4104 blink::mojom::CommitNavigationParams::New(
Diana Quae845bf2025-04-03 20:12:374105 url::Origin(),
Ari Chivukulac7533522024-05-14 21:52:344106 // The correct storage key will be computed before committing the
4107 // navigation.
4108 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324109 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504110 std::vector<net::RedirectInfo>(), params.post_content_type,
4111 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524112 params.can_load_local_resources, page_state_data,
4113 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134114 /*intended_as_new_entry=*/true,
Charlie Reis99b2eba22025-01-31 19:18:574115 /*pending_history_list_index=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144116 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4117 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134118 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314119 params.should_clear_history_list,
4120 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224121 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134122 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514123 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284124#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134125 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144126#endif
Yoav Weiss8c573952022-11-17 17:35:134127 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154128 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134129 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074130 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134131 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4132 /*origin_agent_cluster=*/false,
4133 /*origin_agent_cluster_left_as_default=*/true,
4134 /*enabled_client_hints=*/
4135 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264136 /*is_cross_site_cross_browsing_context_group=*/false,
4137 /*should_have_sticky_user_activation=*/false,
4138 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134139 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014140 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134141 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584142 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134143 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134144 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284145 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134146 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444147 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424148 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374149 /*view_transition_state=*/std::nullopt,
4150 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054151 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464152 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374153 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054154 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094155 /*load_with_storage_access=*/
4156 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374157 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374158 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484159 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314160 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164161 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174162 node->current_frame_host()->GetCachedPermissionStatuses(),
Charlie Reiscdb798342025-02-14 22:04:464163 /*should_skip_screentshot=*/false,
4164 /*force_new_document_sequence_number=*/false);
Xiaohan Wang7f8052e02022-01-14 18:44:284165#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424166 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564167 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424168 }
4169#endif
4170
Lucas Furukawa Gadania9c45682019-07-31 22:05:144171 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074172 commit_params->navigation_timing->system_entropy_at_navigation_start =
4173 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4174 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424175
Camille Lamy5193caa2018-10-12 11:59:424176 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4177 std::string extra_headers_crlf;
4178 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094179
Alex Moshchuk9321e6a2022-12-07 21:58:314180 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144181 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084182 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094183 params.initiator_frame_token, params.initiator_process_id,
4184 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214185 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294186 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454187 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344188 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034189 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134190
4191 if (!navigation_request) {
4192 return nullptr;
4193 }
4194
Yao Xiaodc5ed102019-06-04 19:19:094195 navigation_request->set_from_download_cross_origin_redirect(
4196 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554197 navigation_request->set_force_new_browsing_instance(
4198 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514199 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434200 if (params.force_no_https_upgrade) {
4201 navigation_request->set_force_no_https_upgrade();
4202 }
Yao Xiaodc5ed102019-06-04 19:19:094203 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424204}
4205
4206std::unique_ptr<NavigationRequest>
4207NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234208 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574209 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234210 FrameNavigationEntry* frame_entry,
4211 ReloadType reload_type,
4212 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434213 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374214 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334215 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374216 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134217 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344218 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234219 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434220 // We should never navigate to an existing initial NavigationEntry that is the
4221 // initial NavigationEntry for the initial empty document that hasn't been
4222 // overridden by the synchronous about:blank commit, to preserve previous
4223 // behavior where trying to reload when the main frame is on the initial empty
4224 // document won't result in a navigation.
4225 // See also https://crbug.com/1277414.
4226 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324227
clamyea99ea12018-05-28 13:54:234228 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234229
Ehsan Karamad44fc72112019-02-26 18:15:474230 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4231 // Avoid starting any new navigations since this node is now preparing for
4232 // attaching an inner delegate.
4233 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204234 }
4235
Alex Moshchuk99242832023-05-22 17:21:444236 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4237 dest_url)) {
clamyea99ea12018-05-28 13:54:234238 return nullptr;
4239 }
4240
clamyea99ea12018-05-28 13:54:234241 // This will be used to set the Navigation Timing API navigationStart
4242 // parameter for browser navigations in new tabs (intents, tabs opened through
4243 // "Open link in new tab"). If the navigation must wait on the current
4244 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4245 // will be updated when the BeforeUnload ack is received.
Charlie Reise1d9b8182025-04-02 04:32:124246 // TODO(crbug.com/385170155): Consider whether to track an earlier
4247 // `actual_navigation_start` by plumbing it from the the initiator (e.g.,
4248 // for renderer-initiated history navigations, etc).
clamyea99ea12018-05-28 13:54:234249 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074250 const auto navigation_start_system_entropy =
4251 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4252 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234253
danakjd83d706d2020-11-25 22:11:124254 // Look for a pending commit that is to another document in this
4255 // FrameTreeNode. If one exists, then the last committed URL will not be the
4256 // current URL by the time this navigation commits.
4257 bool has_pending_cross_document_commit =
4258 frame_tree_node->render_manager()
4259 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494260 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214261 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124262
Minggang Wangb9f3fa92021-07-01 15:30:314263 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124264 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524265 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494266 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494267 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134268 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494269 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424270
4271 // A form submission may happen here if the navigation is a
4272 // back/forward/reload navigation that does a form resubmission.
4273 scoped_refptr<network::ResourceRequestBody> request_body;
4274 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394275 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504276 // entry. This way, it could be directly retrieved here. Right now, it is only
4277 // partially recovered when request.method == "POST" and request.body exists.
4278 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424279 if (frame_entry->method() == "POST") {
4280 request_body = frame_entry->GetPostData(&post_content_type);
4281 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304282 post_content_type = std::string(
4283 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504284 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424285 }
4286
4287 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314288 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514289 entry->ConstructCommonNavigationParams(
4290 *frame_entry, request_body, dest_url,
4291 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Charlie Reise1d9b8182025-04-02 04:32:124292 navigation_type, /*actual_navigation_start=*/navigation_start,
4293 navigation_start,
4294 /*input_start=*/base::TimeTicks());
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514295 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554296 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424297
4298 // TODO(clamy): |intended_as_new_entry| below should always be false once
4299 // Reload no longer leads to this being called for a pending NavigationEntry
4300 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314301 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144302 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404303 *frame_entry, common_params->url, common_params->method,
4304 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144305 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534306 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484307 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134308 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074309 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144310 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074311 commit_params->navigation_timing->system_entropy_at_navigation_start =
4312 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4313 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164314 commit_params->initial_permission_statuses =
4315 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424316
W. James MacLeanb7d6092682022-10-05 15:23:264317 if (common_params->url.IsAboutSrcdoc()) {
4318 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4319 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594320 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264321 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334322 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314323 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144324 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434325 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334326 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4327 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374328 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294329 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4330 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474331 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234332}
4333
[email protected]d202a7c2012-01-04 07:53:474334void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214335 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274336 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404337
Takashi Toyoshimaea534ef22021-07-21 03:27:594338 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404339 // location bar will have up-to-date information about the security style
4340 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134341 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404342
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374343 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574344 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294345}
4346
initial.commit09911bf2008-07-26 23:55:294347// static
[email protected]d202a7c2012-01-04 07:53:474348size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234349 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154350 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214351 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234352}
4353
[email protected]d202a7c2012-01-04 07:53:474354void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224355 if (is_active && needs_reload_)
4356 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214357
4358 if (frame_tree_->is_primary();
4359 auto* cache = GetNavigationEntryScreenshotCache()) {
4360 cache->SetVisible(is_active);
4361 }
initial.commit09911bf2008-07-26 23:55:294362}
4363
[email protected]d202a7c2012-01-04 07:53:474364void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034365 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4366 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294367 if (!needs_reload_)
4368 return;
4369
Bo Liucdfa4b12018-11-06 00:21:444370 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4371 needs_reload_type_);
4372
initial.commit09911bf2008-07-26 23:55:294373 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004374 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294375 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004376 if (entry_replaced_by_post_commit_error_) {
4377 // If the current entry is a post commit error, we reload the entry it
4378 // replaced instead. We leave the error entry in place until a commit
4379 // replaces it, but the pending entry points to the original entry in the
4380 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4381 // case that pending_entry_ != entries_[pending_entry_index_].
4382 // Note that this handling is similar to
4383 // `NavigationControllerImpl::Reload()`.
4384 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4385 pending_entry_index_ = GetCurrentEntryIndex();
4386 NavigateToExistingPendingEntry(
4387 ReloadType::NONE,
4388 /*initiator_rfh=*/nullptr,
4389 /*soft_navigation_heuristics_task_id=*/std::nullopt,
4390 /*navigation_api_key=*/nullptr);
4391 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134392 NavigateToExistingPendingEntry(
4393 ReloadType::NONE,
4394 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374395 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134396 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454397 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434398 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274399 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344400 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134401 NavigateToExistingPendingEntry(
4402 ReloadType::NONE,
4403 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374404 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134405 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344406 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434407 // We should never navigate to an existing initial NavigationEntry that is
4408 // the initial NavigationEntry for the initial empty document that hasn't
4409 // been overridden by the synchronous about:blank commit, to preserve
4410 // legacy behavior where trying to reload when the main frame is on the
4411 // initial empty document won't result in a navigation. See also
4412 // https://crbug.com/1277414. If there is something to reload, the
4413 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4414 // it here.
avicc872d7242015-08-19 21:26:344415 needs_reload_ = false;
4416 }
initial.commit09911bf2008-07-26 23:55:294417}
4418
Kevin McNeeccca6172021-10-19 17:11:144419base::WeakPtr<NavigationHandle>
4420NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364421 RenderFrameHost* render_frame_host,
4422 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364423 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134424 RenderFrameHostImpl* rfhi =
4425 static_cast<RenderFrameHostImpl*>(render_frame_host);
Andrew Verge754c70a2025-04-17 17:19:194426 std::unique_ptr<NavigationRequest> navigation_request =
4427 CreateNavigationRequestForErrorPage(rfhi, url, error_page_html,
4428 /*is_post_commit_error_page=*/true);
4429 if (!navigation_request) {
Kevin McNeeccca6172021-10-19 17:11:144430 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114431 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584432
Rakina Zata Amni919b7922020-12-11 09:03:134433 FrameTreeNode* node = rfhi->frame_tree_node();
Charlie Reis09952ee2022-12-08 16:35:074434 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414435 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144436
Andrew Verge754c70a2025-04-17 17:19:194437 // TODO(crbug.com/406729265): LoadPostCommitErrorPage() does not initiate a
4438 // navigation via Navigator::Navigate(). We should fix that, so that
4439 // post-commit error page navigations don't bypass other important checks in
4440 // this function.
Kevin McNeeccca6172021-10-19 17:11:144441 // Calling BeginNavigation may destroy the NavigationRequest.
4442 base::WeakPtr<NavigationRequest> created_navigation_request(
4443 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414444 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144445 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414446}
4447
Andrew Verge754c70a2025-04-17 17:19:194448void NavigationControllerImpl::NavigateFrameToErrorPage(
4449 RenderFrameHostImpl* render_frame_host_impl,
4450 const GURL& url,
4451 const std::string& error_page_html) {
4452 // For now, this function can only be used for fenced frame roots. In the
4453 // future, it will be updated to work for any frame.
4454 // TODO(crbug.com/406729265): Implement this method for all types of frames,
4455 // including main frames and other subframe types.
4456 CHECK(render_frame_host_impl->IsFencedFrameRoot());
4457
4458 std::unique_ptr<NavigationRequest> navigation_request =
4459 CreateNavigationRequestForErrorPage(render_frame_host_impl, url,
4460 error_page_html,
4461 /*is_post_commit_error_page=*/false);
4462 if (!navigation_request) {
4463 return;
4464 }
4465
4466 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
4467 node->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
4468}
4469
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574470void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214471 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094472 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154473 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144474 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294475}
4476
[email protected]d202a7c2012-01-04 07:53:474477void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364478 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584479 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474480 // represent a no-committed-entry state.
4481 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364482 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584483 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474484 // if `entries_` contains pre-existing entries from the NavigationController
4485 // before restore, which would not be removed and will be at the front of the
4486 // entries list, causing the index to be off by the amount of pre-existing
4487 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294488 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294489}
[email protected]765b35502008-08-21 00:51:204490
arthursonzogni69a6a1b2019-09-17 09:23:004491void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004492 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4493}
4494
4495void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4496 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474497 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104498 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4499 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294500 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474501 return;
Michael Thiessenc5676d22019-09-25 22:32:104502 }
avi45a72532015-04-07 21:01:454503 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314504
4505 if (!delegate_)
4506 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374507 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484508}
4509
avi7c6f35e2015-05-08 17:52:384510int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4511 int nav_entry_id) const {
4512 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4513 if (entries_[i]->GetUniqueID() == nav_entry_id)
4514 return i;
4515 }
4516 return -1;
4517}
4518
[email protected]d202a7c2012-01-04 07:53:474519void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574520 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254521 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574522 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594523 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254524 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374525 // Normally, cloning a NavigationEntryImpl results in sharing
4526 // FrameNavigationEntries between the original and the clone. However, when
4527 // cloning from a different NavigationControllerImpl, we want to fork the
4528 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374529 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594530 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254531 }
Rakina Zata Amnie2d31312022-11-18 03:38:454532 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274533 DCHECK(pending_entry_index_ == -1 ||
4534 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254535}
[email protected]c5b88d82012-10-06 17:03:334536
4537void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184538 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334539 get_timestamp_callback_ = get_timestamp_callback;
4540}
[email protected]8ff00d72012-10-23 19:12:214541
Shivani Sharmaffb32b82019-04-09 16:58:474542// History manipulation intervention:
4543void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474544 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564545 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404546 bool is_renderer_initiated,
4547 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564548 // Note that for a subframe,
4549 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454550 // gesture happened in any subframe (propagated to main frame) or in the main
4551 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564552 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274553 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474554 return;
4555 }
4556 if (last_committed_entry_index_ == -1)
4557 return;
4558
Shivani Sharmac4cc8922019-04-18 03:11:174559 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474560
Alexander Timine3ec4192020-04-20 16:39:404561 // Log UKM with the URL we are navigating away from.
4562 ukm::builders::HistoryManipulationIntervention(
4563 previous_page_load_ukm_source_id)
4564 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474565}
4566
Shivani Sharmac4cc8922019-04-18 03:11:174567void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4568 int reference_index,
4569 bool skippable) {
4570 auto* reference_entry = GetEntryAtIndex(reference_index);
4571 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4572
4573 int64_t document_sequence_number =
4574 reference_entry->root_node()->frame_entry->document_sequence_number();
4575 for (int index = 0; index < GetEntryCount(); index++) {
4576 auto* entry = GetEntryAtIndex(index);
4577 if (entry->root_node()->frame_entry->document_sequence_number() ==
4578 document_sequence_number) {
4579 entry->set_should_skip_on_back_forward_ui(skippable);
4580 }
4581 }
4582}
4583
arthursonzogni66f711c2019-10-08 14:40:364584std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4585NavigationControllerImpl::ReferencePendingEntry() {
4586 DCHECK(pending_entry_);
4587 auto pending_entry_ref =
4588 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4589 pending_entry_refs_.insert(pending_entry_ref.get());
4590 return pending_entry_ref;
4591}
4592
4593void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4594 // Ignore refs that don't correspond to the current pending entry.
4595 auto it = pending_entry_refs_.find(ref);
4596 if (it == pending_entry_refs_.end())
4597 return;
4598 pending_entry_refs_.erase(it);
4599
4600 if (!pending_entry_refs_.empty())
4601 return;
4602
4603 // The pending entry may be deleted before the last PendingEntryRef.
4604 if (!pending_entry_)
4605 return;
4606
4607 // We usually clear the pending entry when the matching NavigationRequest
4608 // fails, so that an arbitrary URL isn't left visible above a committed page.
4609 //
4610 // However, we do preserve the pending entry in some cases, such as on the
4611 // initial navigation of an unmodified blank tab. We also allow the delegate
4612 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4613 // user edit the URL and try again. This may be useful in cases that the
4614 // committed page cannot be attacker-controlled. In these cases, we still
4615 // allow the view to clear the pending entry and typed URL if the user
4616 // requests (e.g., hitting Escape with focus in the address bar).
4617 //
4618 // Do not leave the pending entry visible if it has an invalid URL, since this
4619 // might be formatted in an unexpected or unsafe way.
4620 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364621 bool should_preserve_entry =
4622 (pending_entry_ == GetVisibleEntry()) &&
4623 pending_entry_->GetURL().is_valid() &&
4624 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4625 if (should_preserve_entry)
4626 return;
4627
4628 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374629 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364630}
4631
Titouan Rigoudy6ec70402021-02-02 15:42:194632std::unique_ptr<PolicyContainerPolicies>
4633NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394634 RenderFrameHostImpl* rfh,
4635 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214636 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174637 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214638 if (navigation_encountered_error) {
4639 // We should never reload the policy container of an error page from
4640 // history, see https://crbug.com/364773822.
4641 return nullptr;
4642 }
4643
Antonio Sartori78a749f2020-11-30 12:03:394644 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454645 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394646 FrameNavigationEntry* previous_frame_entry =
4647 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4648
Alison Gale770f3fc2024-04-27 00:39:584649 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394650 // ensure we always have a FrameNavigationEntry here.
4651 if (!previous_frame_entry)
4652 return nullptr;
4653
Titouan Rigoudy6ec70402021-02-02 15:42:194654 const PolicyContainerPolicies* previous_policies =
4655 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394656
Titouan Rigoudy6ec70402021-02-02 15:42:194657 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394658 return nullptr;
4659
4660 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234661 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394662 }
4663
Titouan Rigoudy72f892d2022-05-02 18:21:234664 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394665}
4666
Charlie Reis99b2eba22025-01-31 19:18:574667void NavigationControllerImpl::BroadcastHistoryIndexAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504668 OPTIONAL_TRACE_EVENT2(
Charlie Reis99b2eba22025-01-31 19:18:574669 "content", "NavigationControllerImpl::BroadcastHistoryIndexAndLength",
4670 "history_index", GetLastCommittedEntryIndex(), "history_length",
Hayato Ito2c8c08d02021-06-23 03:38:434671 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504672
Charlie Reis99b2eba22025-01-31 19:18:574673 int history_index = GetLastCommittedEntryIndex();
Kevin McNee7705fe82024-11-07 18:56:314674 int history_length = GetEntryCount();
Charlie Reis99b2eba22025-01-31 19:18:574675 auto callback = [history_index, history_length](RenderViewHostImpl* rvh) {
Kevin McNee7705fe82024-11-07 18:56:314676 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
Charlie Reis99b2eba22025-01-31 19:18:574677 broadcast->SetHistoryIndexAndLength(history_index, history_length);
Kevin McNee7705fe82024-11-07 18:56:314678 }
4679 };
Ali Hijazid87307d2022-11-07 20:15:034680 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504681}
4682
4683void NavigationControllerImpl::DidAccessInitialMainDocument() {
4684 // We may have left a failed browser-initiated navigation in the address bar
4685 // to let the user edit it and try again. Clear it now that content might
4686 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034687 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504688 DiscardPendingEntry(false);
4689
4690 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374691 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504692}
4693
4694void NavigationControllerImpl::UpdateStateForFrame(
4695 RenderFrameHostImpl* rfhi,
4696 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564697 OPTIONAL_TRACE_EVENT1("content",
4698 "NavigationControllerImpl::UpdateStateForFrame",
4699 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504700 // The state update affects the last NavigationEntry associated with the given
4701 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4702 // in the case of an UpdateState from a frame being swapped out). We track
4703 // which entry this is in the RenderFrameHost's nav_entry_id.
4704 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4705 if (!entry)
4706 return;
4707
4708 FrameNavigationEntry* frame_entry =
4709 entry->GetFrameEntry(rfhi->frame_tree_node());
4710 if (!frame_entry)
4711 return;
4712
4713 // The SiteInstance might not match if we do a cross-process navigation with
4714 // replacement (e.g., auto-subframe), in which case the swap out of the old
4715 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4716 // has already been replaced and destroyed.
4717 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4718 return;
4719
4720 if (page_state == frame_entry->page_state())
4721 return; // Nothing to update.
4722
4723 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4724
4725 // The document_sequence_number and item_sequence_number recorded in the
4726 // FrameNavigationEntry should not differ from the one coming with the update,
4727 // since it must come from the same document. Do not update it if a difference
4728 // is detected, as this indicates that |frame_entry| is not the correct one.
4729 blink::ExplodedPageState exploded_state;
4730 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4731 return;
4732
4733 if (exploded_state.top.document_sequence_number !=
4734 frame_entry->document_sequence_number() ||
4735 exploded_state.top.item_sequence_number !=
4736 frame_entry->item_sequence_number()) {
4737 return;
4738 }
4739
4740 frame_entry->SetPageState(page_state);
4741 NotifyEntryChanged(entry);
4742}
4743
Nate Chapina2c881f52023-11-07 17:02:094744namespace {
4745
4746// The caller is responsible for ensuring the entry is same-origin to the
4747// origin to be committed.
4748blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4749 FrameNavigationEntry* frame_entry,
4750 int64_t pending_document_sequence_number) {
4751 blink::ExplodedPageState exploded_state;
4752 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4753 &exploded_state)) {
4754 return nullptr;
4755 }
4756 blink::ExplodedFrameState frame_state = exploded_state.top;
4757
4758 // If the document represented by this FNE hid its full url from appearing in
4759 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4760 // in the navigation API as well (unless we're navigating to that document).
4761 std::u16string url;
4762 if (pending_document_sequence_number ==
4763 frame_entry->document_sequence_number() ||
4764 !frame_entry->protect_url_in_navigation_api()) {
4765 url = frame_state.url_string.value_or(std::u16string());
4766 }
4767
4768 return blink::mojom::NavigationApiHistoryEntry::New(
4769 frame_state.navigation_api_key.value_or(std::u16string()),
4770 frame_state.navigation_api_id.value_or(std::u16string()), url,
4771 frame_state.item_sequence_number, frame_state.document_sequence_number,
4772 frame_state.navigation_api_state);
4773}
4774
4775} // namespace
4776
Domenic Denicolacd30f5f82022-03-16 21:48:014777std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4778NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574779 Direction direction,
4780 int entry_index,
4781 const url::Origin& pending_origin,
4782 FrameTreeNode* node,
4783 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304784 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094785 int64_t pending_document_sequence_number,
4786 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014787 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454788 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174789 // Don't process the initial entry.
4790 DCHECK_EQ(GetEntryCount(), 1);
4791 return entries;
4792 }
Nate Chapind1fe3612021-04-16 20:45:574793 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304794 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574795 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4796 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094797 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574798 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414799 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574800 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014801 // An entry should only appear in the navigation API entries if it is for
4802 // the same origin as the document being committed. Check the committed
4803 // origin, or if that is not available (during restore), check against the
4804 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584805 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094806 // once we can be sure that entries with the same ISN will never be
4807 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414808 url::Origin frame_entry_origin =
4809 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4810 frame_entry->url(),
4811 frame_entry->initiator_origin().value_or(url::Origin())));
4812 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574813 break;
4814 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4815 continue;
Nate Chapina2c881f52023-11-07 17:02:094816 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4817 ToNavigationApiHistoryEntry(frame_entry,
4818 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304819 DCHECK(entry->url.empty() ||
4820 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574821 entries.push_back(std::move(entry));
4822 previous_item_sequence_number = frame_entry->item_sequence_number();
4823 }
4824 }
4825 // If |entries| was constructed by iterating backwards from
4826 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4827 // earliest-at-the-front. Reverse it.
4828 if (direction == Direction::kBack)
4829 std::reverse(entries.begin(), entries.end());
4830 return entries;
4831}
4832
Domenic Denicolacd30f5f82022-03-16 21:48:014833blink::mojom::NavigationApiHistoryEntryArraysPtr
4834NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554835 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574836 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404837 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444838 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404839 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574840
Nate Chapind1fe3612021-04-16 20:45:574841 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554842 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574843
Nate Chapine82339d02022-05-03 23:48:254844 // NOTE: |entry_index| is the index where this entry will commit if no
4845 // modifications are made between now and DidCommitNavigation. This is used to
4846 // walk |entries_| and determine which entries should be exposed by the
4847 // navigation API. It is important to calculate this correctly, because blink
4848 // will cancel a same-document history commit if it's not present in the
4849 // entries blink knows about.
4850 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574851 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304852 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254853 bool will_create_new_entry = false;
4854 if (GetPendingEntryIndex() != -1) {
4855 entry_index = GetPendingEntryIndex();
4856 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4857 pending_item_sequence_number = frame_entry->item_sequence_number();
4858 pending_document_sequence_number =
4859 frame_entry->document_sequence_number();
4860 }
4861 } else if (request &&
4862 !NavigationTypeUtils::IsReload(
4863 request->common_params().navigation_type) &&
4864 !NavigationTypeUtils::IsHistory(
4865 request->common_params().navigation_type) &&
4866 !request->common_params().should_replace_current_entry &&
4867 !request->common_params()
4868 .is_history_navigation_in_new_child_frame) {
4869 will_create_new_entry = true;
4870 entry_index = GetLastCommittedEntryIndex() + 1;
4871 // Don't set pending_item_sequence_number or
4872 // pending_document_sequence_number in this case - a new unique isn/dsn will
4873 // be calculated in the renderer later.
4874 } else if (GetLastCommittedEntryIndex() != -1) {
4875 entry_index = GetLastCommittedEntryIndex();
4876 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574877 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304878 pending_document_sequence_number =
4879 frame_entry->document_sequence_number();
4880 }
Nate Chapind1fe3612021-04-16 20:45:574881 }
4882
Domenic Denicolacd30f5f82022-03-16 21:48:014883 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254884 if (entry_index == -1) {
4885 // TODO(rakina): Exit early when there is no last committed entry.
4886 // Remove when InitialNavigationEntry ships.
4887 return entry_arrays;
4888 }
4889
Nate Chapina2c881f52023-11-07 17:02:094890 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014891 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574892 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094893 pending_item_sequence_number, pending_document_sequence_number,
4894 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574895
4896 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094897 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574898 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014899 entry_arrays->forward_entries =
4900 PopulateSingleNavigationApiHistoryEntryVector(
4901 Direction::kForward, entry_index, pending_origin, node,
4902 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094903 pending_document_sequence_number, forwardmost_index);
4904 }
4905
4906 // If the previous entry is within the block of contiguous entries being
4907 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254908 FrameNavigationEntry* previous_entry = nullptr;
4909 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:054910 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4911 .initiator_frame_tree_node_id();
4912 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:254913 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4914 previous_entry = initiator_node->frame_tree()
4915 .controller()
4916 .GetLastCommittedEntry()
4917 ->GetFrameEntry(initiator_node);
4918 }
4919 } else if (GetLastCommittedEntryIndex() != -1 &&
4920 GetLastCommittedEntryIndex() >= backmost_index &&
4921 GetLastCommittedEntryIndex() <= forwardmost_index) {
4922 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4923 }
4924 if (previous_entry) {
4925 url::Origin previous_entry_origin =
4926 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4927 previous_entry->url(),
4928 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:584929 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:254930 // once we can be sure that entries with the same ISN will never be
4931 // cross-origin.
4932 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4933 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4934 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094935 }
Nate Chapind1fe3612021-04-16 20:45:574936 }
Nate Chapinc06cf80a2023-11-18 01:12:254937
Nate Chapin4e657a472022-02-06 03:38:374938 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574939}
4940
Nate Chapinfbfe5af2021-06-10 17:22:084941NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574942NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084943 FrameNavigationEntry* current_entry,
4944 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574945 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084946 if (!target_entry || !target_entry->committed_origin())
4947 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084948 if (!current_entry->committed_origin()->IsSameOriginWith(
4949 *target_entry->committed_origin())) {
4950 return HistoryNavigationAction::kStopLooking;
4951 }
4952
4953 // NOTE: We don't actually care between kSameDocument and
4954 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574955 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084956 return HistoryNavigationAction::kDifferentDocument;
4957 return HistoryNavigationAction::kKeepLooking;
4958}
4959
Domenic Denicolacc094fb2022-03-16 23:40:574960void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204961 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374962 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144963 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574964 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204965 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084966 FrameNavigationEntry* current_entry =
4967 GetLastCommittedEntry()->GetFrameEntry(node);
Nate Chapin0dbc93af2025-03-28 17:02:524968 if (!current_entry || !current_entry->committed_origin()) {
Nate Chapinfbfe5af2021-06-10 17:22:084969 return;
Nate Chapin0dbc93af2025-03-28 17:02:524970 }
Nate Chapinfbfe5af2021-06-10 17:22:084971
Alison Gale47d1537d2024-04-19 21:31:464972 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:134973 // when `navigation.traverseTo()` is called.
4974
Nate Chapinfbfe5af2021-06-10 17:22:084975 // We want to find the nearest matching entry that is contiguously
4976 // same-instance and same-origin. Check back first, then forward.
4977 // TODO(japhet): Link spec here once it exists.
4978 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574979 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084980 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4981 if (result == HistoryNavigationAction::kStopLooking)
4982 break;
4983 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144984 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084985 return;
4986 }
4987 }
4988 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574989 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084990 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4991 if (result == HistoryNavigationAction::kStopLooking)
4992 break;
4993 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144994 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084995 return;
4996 }
4997 }
Nate Chapinbf682fa32022-09-26 22:41:204998
4999 // If we fall through to here, a matching NavigationEntry couldn't be found.
5000 // Notify the renderer that the navigation was cancelled.
5001 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
5002 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:085003}
5004
Domenic Denicolacc094fb2022-03-16 23:40:575005bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:305006 network::mojom::ReferrerPolicy referrer_policy) {
5007 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
5008 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
5009}
5010
shivanigithubf405bf0d2021-11-05 17:58:335011bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
5012 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:315013 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:335014 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:545015 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:465016 // The preview mode appears as prerendered page in renderers, and
5017 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:035018 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:515019 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:335020 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:545021}
5022
Julie Jeongeun Kim0e242242022-11-30 10:45:095023void NavigationControllerImpl::DidChangeReferrerPolicy(
5024 FrameTreeNode* node,
5025 network::mojom::ReferrerPolicy referrer_policy) {
5026 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
5027 if (!entry)
5028 return;
5029
5030 // The FrameNavigationEntry may want to change whether to protect its url
5031 // in the navigation API when the referrer policy changes.
5032 entry->set_protect_url_in_navigation_api(
5033 ShouldProtectUrlInNavigationApi(referrer_policy));
5034}
5035
Minoru Chikamune646eba42025-04-14 01:25:035036void NavigationControllerImpl::CheckPotentialNavigationReentrancy() {
5037 // DumpWithoutCrashing will be reported just once in one Chrome session since
5038 // we want to avoid too many reports.
5039 static bool has_dumped_without_crashing = false;
5040 if (can_be_in_navigate_to_pending_entry_ && !has_dumped_without_crashing) {
5041 has_dumped_without_crashing = true;
5042 // This DumpWithoutCrashing is an investigation code for
5043 // https://crbug.com/396998476.
5044 base::debug::DumpWithoutCrashing();
5045 }
5046}
5047
Andrew Verge754c70a2025-04-17 17:19:195048std::unique_ptr<NavigationRequest>
5049NavigationControllerImpl::CreateNavigationRequestForErrorPage(
5050 RenderFrameHostImpl* render_frame_host_impl,
5051 const GURL& url,
5052 const std::string& error_page_html,
5053 bool is_post_commit_error_page) {
5054 // Only active documents can load error pages:
5055 // - If the document is in pending deletion, the browser already committed to
5056 // destroying this RenderFrameHost so ignore loading the error page.
5057 // - If the document is in back-forward cache, it's not allowed to navigate as
5058 // it should remain frozen. Ignore the request and evict the document from
5059 // back-forward cache.
5060 // - If the document is prerendering, it can navigate but when loading error
5061 // pages, cancel prerendering.
5062 if (render_frame_host_impl->IsInactiveAndDisallowActivation(
5063 is_post_commit_error_page
5064 ? DisallowActivationReasonId::kLoadPostCommitErrorPage
5065 : DisallowActivationReasonId::kBrowserInitiatedErrorPage)) {
5066 return nullptr;
5067 }
5068
5069 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
5070
5071 blink::mojom::CommonNavigationParamsPtr common_params =
5072 blink::CreateCommonNavigationParams();
5073 // |url| might be empty, such as when this method is called before
5074 // the frame actually committed (e.g. iframe with "src" set to a
5075 // slow-responding URL). We should rewrite the URL to about:blank in this
5076 // case, as the renderer will only think a page is an error page if it has a
5077 // non-empty unreachable URL.
5078 common_params->url = url.is_empty() ? GURL("about:blank") : url;
5079
5080 // Loading an error page via LoadPostCommitErrorPage() performs a temporary
5081 // replacement of the entire NavigationEntry and swaps it back in later.
5082 // All other error page types should permanently replace the current entry.
5083 if (!is_post_commit_error_page) {
5084 common_params->should_replace_current_entry = true;
5085 }
5086
5087 blink::mojom::CommitNavigationParamsPtr commit_params =
5088 blink::CreateCommitNavigationParams();
5089 commit_params->original_url = common_params->url;
5090
5091 commit_params->navigation_timing->system_entropy_at_navigation_start =
5092 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
5093 node, blink::mojom::SystemEntropy::kNormal);
5094
5095 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
5096 // error pages.
5097 commit_params->frame_policy = node->pending_frame_policy();
5098
5099 std::unique_ptr<NavigationRequest> navigation_request =
5100 NavigationRequest::CreateBrowserInitiated(
5101 node, std::move(common_params), std::move(commit_params),
5102 false /* was_opener_suppressed */, "" /* extra_headers */,
5103 nullptr /* frame_entry */, nullptr /* entry */,
5104 false /* is_form_submission */, nullptr /* navigation_ui_data */,
5105 std::nullopt /* impression */, false /* is_pdf */);
5106 if (is_post_commit_error_page) {
5107 navigation_request->set_browser_initiated_error_navigation_type(
5108 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit);
5109 } else {
5110 navigation_request->set_browser_initiated_error_navigation_type(
5111 NavigationRequest::BrowserInitiatedErrorNavigationType::kRegular);
5112 }
5113 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
5114 navigation_request->set_error_page_html(error_page_html);
5115 return navigation_request;
5116}
5117
[email protected]8ff00d72012-10-23 19:12:215118} // namespace content