blob: d47f38b6fe85fbfa7b9113d838da556a4dc137df [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 Chikamune13ab4de2025-05-14 21:54:072621 // If `was_failure` is true, it means that the pending entry was discarded by
2622 // a `PendingEntryRefDeleted` call within `OnRequestFailedInternal`, in
2623 // response to a navigation request failure. This case is not at risk for
2624 // re-entrancy when `can_be_in_navigate_to_pending_entry_` is true, because
2625 // that code also creates another `PendingEntryRef` that would prevent the
2626 // `DiscardPendingEntry` call if the PostTask were skipped. See
2627 // https://crbug.com/411855273.
2628 if (!was_failure && can_be_in_navigate_to_pending_entry_ &&
Minoru Chikamune646eba42025-04-14 01:25:032629 !frame_tree_->IsBeingDestroyed()) {
2630 CheckPotentialNavigationReentrancy();
2631 }
clamy987a3752018-05-03 17:36:262632
2633 if (was_failure && pending_entry_) {
2634 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2635 } else {
2636 failed_pending_entry_id_ = 0;
2637 }
2638
2639 if (pending_entry_) {
2640 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332641 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262642 pending_entry_index_ = -1;
2643 pending_entry_ = nullptr;
2644 }
arthursonzogni66f711c2019-10-08 14:40:362645
2646 // Ensure any refs to the current pending entry are ignored if they get
2647 // deleted, by clearing the set of known refs. All future pending entries will
2648 // only be affected by new refs.
2649 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262650}
2651
2652void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2653 if (pending_entry_)
2654 pending_entry_->set_ssl_error(error);
2655}
2656
Xiaohan Wang7f8052e02022-01-14 18:44:282657#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422658// static
2659bool NavigationControllerImpl::ValidateDataURLAsString(
2660 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2661 if (!data_url_as_string)
2662 return false;
2663
2664 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2665 return false;
2666
2667 // The number of characters that is enough for validating a data: URI.
2668 // From the GURL's POV, the only important part here is scheme, it doesn't
2669 // check the actual content. Thus we can take only the prefix of the url, to
2670 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562671 constexpr size_t kDataUriPrefixMaxLen = 64;
2672 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2673 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422674 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2675 return false;
2676
2677 return true;
2678}
2679#endif
2680
Shivani Sharma194877032019-03-07 17:52:472681void NavigationControllerImpl::NotifyUserActivation() {
2682 // When a user activation occurs, ensure that all adjacent entries for the
2683 // same document clear their skippable bit, so that the history manipulation
2684 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012685 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172686 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012687 // If the value of CanGoBack changes as a result of making some entries
2688 // non-skippable, then we must let the delegate know to update its UI state.
2689 // See https://crbug.com/1477784.
2690 if (!can_go_back && CanGoBack()) {
2691 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2692 }
Shivani Sharma194877032019-03-07 17:52:472693}
2694
clamy987a3752018-05-03 17:36:262695bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2696 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332697 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2698 blink::LocalFrameToken initiator_frame_token,
2699 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262700 NavigationEntryImpl* entry =
2701 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2702 if (!entry)
2703 return false;
2704
2705 FrameNavigationEntry* frame_entry =
2706 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2707 if (!frame_entry)
2708 return false;
2709
Camille Lamy5193caa2018-10-12 11:59:422710 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572711 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232712 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332713 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2714 initiator_process_id);
clamyea99ea12018-05-28 13:54:232715
2716 if (!request)
2717 return false;
2718
arthursonzognif046d4a2019-12-12 19:08:102719 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412720
Rakina Zata Amni1c83b082023-02-08 01:09:002721 SCOPED_CRASH_KEY_STRING256(
2722 "Bug1400009", "req_url",
2723 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2724 SCOPED_CRASH_KEY_NUMBER(
2725 "Bug1400009", "nav_entry_si",
2726 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2727 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2728 frame_entry->site_instance()
2729 ? ((int)frame_entry->site_instance()->GetId())
2730 : -1);
2731 bool has_sig =
2732 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2733 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2734 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2735 has_sig ? (!!frame_tree_->GetRenderViewHost(
2736 frame_entry->site_instance()->group()))
2737 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052738 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2739 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232740
2741 return true;
clamy987a3752018-05-03 17:36:262742}
2743
Tsuyoshi Horo52fd08e2020-07-07 07:03:452744bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2745 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2746 if (!entry)
2747 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432748
2749 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2750 // We should never navigate to an existing initial NavigationEntry that is
2751 // the initial NavigationEntry for the initial empty document that hasn't
2752 // been overridden by the synchronous about:blank commit, to preserve
2753 // legacy behavior where trying to reload when the main frame is on the
2754 // initial empty document won't result in a navigation. See also
2755 // https://crbug.com/1277414.
2756 return false;
2757 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452758 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2759 if (!frame_entry)
2760 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142761 ReloadType reload_type = ReloadType::NORMAL;
2762 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452763 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142764 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452765 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432766 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372767 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332768 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452769 if (!request)
2770 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052771 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452772 return true;
2773}
2774
clamy987a3752018-05-03 17:36:262775void NavigationControllerImpl::NavigateFromFrameProxy(
2776 RenderFrameHostImpl* render_frame_host,
2777 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022778 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452779 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372780 const std::optional<url::Origin>& initiator_origin,
2781 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262782 bool is_renderer_initiated,
2783 SiteInstance* source_site_instance,
2784 const Referrer& referrer,
2785 ui::PageTransition page_transition,
2786 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252787 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262788 const std::string& method,
2789 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092790 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142791 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212792 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502793 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372794 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292795 blink::mojom::NavigationInitiatorActivationAndAdStatus
2796 initiator_activation_and_ad_status,
Charlie Reise1d9b8182025-04-02 04:32:122797 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:222798 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492799 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462800 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452801 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582802 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032803 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342804 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372805 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582806 if (is_renderer_initiated)
2807 DCHECK(initiator_origin.has_value());
2808
clamy987a3752018-05-03 17:36:262809 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582810
Rakina Zata Amni2322f4f82022-01-24 13:24:242811 // Don't allow an entry replacement if there is no entry to replace.
2812 // http://crbug.com/457149
2813 if (GetEntryCount() == 0)
2814 should_replace_current_entry = false;
2815
clamy987a3752018-05-03 17:36:262816 // Create a NavigationEntry for the transfer, without making it the pending
2817 // entry. Subframe transfers should have a clone of the last committed entry
2818 // with a FrameNavigationEntry for the target frame. Main frame transfers
2819 // should have a new NavigationEntry.
2820 // TODO(creis): Make this unnecessary by creating (and validating) the params
2821 // directly, passing them to the destination RenderFrameHost. See
2822 // https://crbug.com/536906.
2823 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262824 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262825 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452826 DCHECK(GetLastCommittedEntry());
2827 entry = GetLastCommittedEntry()->Clone();
2828 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172829 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2830 // Renderer-initiated navigation that target a remote frame are currently
2831 // classified as browser-initiated when this one has already navigated.
2832 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372833 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2834 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2835 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2836 // same-document navigation), they will still be present in the
2837 // committed NavigationEntry that will be referenced to construct the new
2838 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262839 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082840 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582841 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372842 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212843 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152844 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262845 } else {
2846 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172847 // If `node` is the outermost main frame, it rewrites a virtual url in order
2848 // to adjust the original input url if needed. For inner frames such as
2849 // fenced frames or subframes, they don't rewrite urls as the urls are not
2850 // input urls by users.
2851 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372852 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322853 if (source_site_instance && source_site_instance->HasProcess()) {
2854 source_process_site_url =
2855 source_site_instance->GetProcess()->GetProcessLock().site_url();
2856 }
clamy987a3752018-05-03 17:36:262857 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212858 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322859 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212860 extra_headers, browser_context_, blob_url_loader_factory,
2861 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262862 entry->root_node()->frame_entry->set_source_site_instance(
2863 static_cast<SiteInstanceImpl*>(source_site_instance));
2864 entry->root_node()->frame_entry->set_method(method);
2865 }
clamy987a3752018-05-03 17:36:262866
Camille Lamy5193caa2018-10-12 11:59:422867 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452868 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262869 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422870 override_user_agent = true;
clamy987a3752018-05-03 17:36:262871 }
2872 // TODO(creis): Set user gesture and intent received timestamp on Android.
2873
2874 // We may not have successfully added the FrameNavigationEntry to |entry|
2875 // above (per https://crbug.com/608402), in which case we create it from
2876 // scratch. This works because we do not depend on |frame_entry| being inside
2877 // |entry| during NavigateToEntry. This will go away when we shortcut this
2878 // further in https://crbug.com/536906.
2879 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2880 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452881 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082882 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582883 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372884 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212885 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152886 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572887 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262888 }
2889
Camille Lamy5193caa2018-10-12 11:59:422890 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022891 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452892 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292893 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212894 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422895 params.source_site_instance = source_site_instance;
2896 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2897 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032898 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422899 params.referrer = referrer;
2900 /* params.redirect_chain: skip */
2901 params.extra_headers = extra_headers;
2902 params.is_renderer_initiated = is_renderer_initiated;
2903 params.override_user_agent = UA_OVERRIDE_INHERIT;
2904 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542905 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422906 /* params.data_url_as_string: skip */
2907 params.post_data = post_body;
2908 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582909 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422910 /* params.frame_name: skip */
2911 // TODO(clamy): See if user gesture should be propagated to this function.
2912 params.has_user_gesture = false;
2913 params.should_clear_history_list = false;
2914 params.started_from_context_menu = false;
2915 /* params.navigation_ui_data: skip */
2916 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222917 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542918 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212919 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412920 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502921 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292922 params.initiator_activation_and_ad_status =
2923 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032924 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422925
2926 std::unique_ptr<NavigationRequest> request =
2927 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032928 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142929 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392930 ReloadType::NONE, entry.get(), frame_entry.get(),
Charlie Reise1d9b8182025-04-02 04:32:122931 actual_navigation_start_time, navigation_start_time,
2932 is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582933 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:342934 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232935
2936 if (!request)
2937 return;
2938
Garrett Tanzerbb8db412022-09-27 21:59:462939 // Force the navigation to take place in a new browsing instance.
2940 // This is used by _unfencedTop in fenced frames to ensure that navigations
2941 // leaving the fenced context create a new browsing instance.
2942 if (force_new_browsing_instance) {
2943 request->coop_status().ForceBrowsingInstanceSwap();
2944 }
2945
Arthur Hemery948742762019-09-18 10:06:242946 // At this stage we are proceeding with this navigation. If this was renderer
2947 // initiated with user gesture, we need to make sure we clear up potential
2948 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2949 DiscardNonCommittedEntries();
2950
Lukasz Anforowicz9ee83c272020-12-01 20:14:052951 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262952}
2953
[email protected]d1198fd2012-08-13 22:50:192954void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252955 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212956 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192957 if (!session_storage_namespace)
2958 return;
2959
2960 // We can't overwrite an existing SessionStorage without violating spec.
2961 // Attempts to do so may give a tab access to another tab's session storage
2962 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152963 bool successful_insert =
2964 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252965 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052966 static_cast<SessionStorageNamespaceImpl*>(
2967 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302968 .second;
2969 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192970}
2971
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572972bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452973 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032974 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462975}
2976
Aran Gilman37d11632019-10-08 23:07:152977SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252978 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302979 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252980 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032981 DOMStorageContextWrapper* context_wrapper =
2982 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2983
2984 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252985 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032986 if (it != session_storage_namespace_map_.end()) {
2987 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152988 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2989 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472990
michaelnbacbcbd2016-02-09 00:32:032991 return it->second.get();
2992 }
2993
2994 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102995 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2996 SessionStorageNamespaceImpl::Create(context_wrapper);
2997 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2998 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252999 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:103000 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:303001
Daniel Murphy31bbb8b12018-02-07 21:44:103002 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:303003}
3004
3005SessionStorageNamespace*
3006NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:253007 return GetSessionStorageNamespace(
3008 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:303009}
3010
3011const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573012NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303013 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553014}
[email protected]d202a7c2012-01-04 07:53:473015
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573016bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563017 return needs_reload_;
3018}
[email protected]a26023822011-12-29 00:23:553019
[email protected]46bb5e9c2013-10-03 22:16:473020void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413021 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3022}
3023
3024void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473025 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413026 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543027
3028 if (last_committed_entry_index_ != -1) {
3029 entries_[last_committed_entry_index_]->SetTransitionType(
3030 ui::PAGE_TRANSITION_RELOAD);
3031 }
[email protected]46bb5e9c2013-10-03 22:16:473032}
3033
[email protected]d202a7c2012-01-04 07:53:473034void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573035 DCHECK_LT(index, GetEntryCount());
3036 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313037 DiscardNonCommittedEntries();
3038
Nate Chapin9eb16be72022-09-23 22:54:313039 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313040 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123041 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313042 last_committed_entry_index_--;
3043}
3044
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573045NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273046 // If there is no pending_entry_, there should be no pending_entry_index_.
3047 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3048
3049 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363050 // at that index. An exception is while a reload of a post commit error page
3051 // is ongoing; in that case pending entry will point to the entry replaced
3052 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273053 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363054 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3055 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273056
[email protected]022af742011-12-28 18:37:253057 return pending_entry_;
3058}
3059
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573060int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273061 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273062 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553063 return pending_entry_index_;
3064}
3065
avi25764702015-06-23 15:43:373066void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573067 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363068 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313069 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003070 bool in_fenced_frame_tree,
3071 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313072 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3073 // set because:
3074 // 1) They don't influence the history of the outer page.
3075 // 2) They are always replace only navigation (there is always only one entry
3076 // in their history stack).
3077 // 3) Are not top level navigations and appear similar to iframes.
3078 // Navigations of the fenced frame might create a new NavigationEntry, which
3079 // will call this function. Non fenced frame navigations will never have
3080 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3081 // InsertOrReplaceEntry.
3082 DCHECK_EQ(in_fenced_frame_tree,
3083 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3084 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203085
avi5cad4912015-06-19 05:25:443086 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3087 // need to keep continuity with the pending entry, so copy the pending entry's
3088 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3089 // then the renderer navigated on its own, independent of the pending entry,
3090 // so don't copy anything.
3091 if (pending_entry_ && pending_entry_index_ == -1)
3092 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203093
Rakina Zata Amnia4e27222021-12-22 01:05:003094 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203095
creisee17e932015-07-17 17:56:223096 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453097 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103098 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573099 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363100 // If the new entry is a post-commit error page, we store the current last
3101 // committed entry to the side so that we can put it back when navigating
3102 // away from the error.
3103 if (was_post_commit_error) {
3104 DCHECK(!entry_replaced_by_post_commit_error_);
3105 entry_replaced_by_post_commit_error_ =
3106 std::move(entries_[last_committed_entry_index_]);
3107 }
dcheng36b6aec92015-12-26 06:16:363108 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223109 return;
3110 }
[email protected]765b35502008-08-21 00:51:203111
creis37979a62015-08-04 19:48:183112 // We shouldn't see replace == true when there's no committed entries.
3113 DCHECK(!replace);
3114
Michael Thiessen9b14d512019-09-23 21:19:473115 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203116
Shivani Sharmad8c8d652019-02-13 17:27:573117 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203118
dcheng36b6aec92015-12-26 06:16:363119 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203120 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293121}
3122
Shivani Sharmad8c8d652019-02-13 17:27:573123void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163124 if (entries_.size() < max_entry_count())
3125 return;
3126
3127 DCHECK_EQ(max_entry_count(), entries_.size());
3128 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573129 CHECK_EQ(pending_entry_index_, -1);
3130
3131 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423132 // Retrieve the oldest skippable entry.
3133 for (; index < GetEntryCount(); index++) {
3134 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3135 break;
Shivani Sharmad8c8d652019-02-13 17:27:573136 }
3137
3138 // If there is no skippable entry or if it is the last committed entry then
3139 // fall back to pruning the oldest entry. It is not safe to prune the last
3140 // committed entry.
3141 if (index == GetEntryCount() || index == last_committed_entry_index_)
3142 index = 0;
3143
3144 bool should_succeed = RemoveEntryAtIndex(index);
3145 DCHECK_EQ(true, should_succeed);
3146
3147 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253148}
3149
William Liu62ae26c2024-08-08 14:28:163150std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273151NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163152 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203153 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373154 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133155 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203156 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503157 TRACE_EVENT0("navigation",
3158 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273159 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023160 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363161 if (pending_entry_index_ != -1) {
3162 // The pending entry may not be in entries_ if a post-commit error page is
3163 // showing.
3164 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3165 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3166 }
Gyuyoung Kim107c2a02021-04-13 01:49:303167 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573168 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013169 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033170 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573171 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133172 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3173 // the same as the top level frame being navigated.
3174 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373175 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133176 }
Arthur Sonzogni620cec62018-12-13 13:08:573177
[email protected]83c2e232011-10-07 21:36:463178 // If we were navigating to a slow-to-commit page, and the user performs
3179 // a session history navigation to the last committed page, RenderViewHost
3180 // will force the throbber to start, but WebKit will essentially ignore the
3181 // navigation, and won't send a message to stop the throbber. To prevent this
3182 // from happening, we drop the navigation here and stop the slow-to-commit
3183 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023184 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083185 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273186 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033187 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123188
[email protected]83c2e232011-10-07 21:36:463189 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163190 return {};
[email protected]83c2e232011-10-07 21:36:463191 }
3192
Arthur Sonzognic686e8f2024-01-11 08:36:373193 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333194 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3195 if (initiator_rfh) {
3196 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543197 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333198 DCHECK(initiator_frame_token);
3199 }
3200
creisce0ef3572017-01-26 17:53:083201 // Compare FrameNavigationEntries to see which frames in the tree need to be
3202 // navigated.
clamy3cb9bea92018-07-10 12:42:023203 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3204 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333205 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3206 initiator_process_id, soft_navigation_heuristics_task_id,
3207 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303208
3209 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573210 // We were unable to match any frames to navigate. This can happen if a
3211 // history navigation targets a subframe that no longer exists
3212 // (https://crbug.com/705550). In this case, we need to update the current
3213 // history entry to the pending one but keep the main document loaded. We
3214 // also need to ensure that observers are informed about the updated
3215 // current history entry (e.g., for greying out back/forward buttons), and
Charlie Reis99b2eba22025-01-31 19:18:573216 // that renderer processes update their history indices. The easiest way
Alex Moshchuk3a4e77a2020-05-29 21:32:573217 // to do all that is to schedule a "redundant" same-document navigation in
3218 // the main frame.
3219 //
3220 // Note that we don't want to remove this history entry, as it might still
3221 // be valid later, since a frame that it's targeting may be recreated.
3222 //
3223 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3224 // need to repeat history navigations until finding the one that works.
3225 // Consider changing this behavior to keep looking for the first valid
3226 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023227 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423228 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573229 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573230 ReloadType::NONE /* reload_type */,
3231 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433232 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333233 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023234 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573235 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023236 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163237 return {};
clamy3cb9bea92018-07-10 12:42:023238 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573239 same_document_loads.push_back(std::move(navigation_request));
3240
3241 // Sanity check that we never take this branch for any kinds of reloads,
3242 // as those should've queued a different-document load in the main frame.
3243 DCHECK(!is_forced_reload);
3244 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303245 }
3246
Nate Chapinbf682fa32022-09-26 22:41:203247 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163248 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203249 if (initiator_rfh && initiator_rfh->IsSandboxed(
3250 network::mojom::WebSandboxFlags::kTopNavigation)) {
3251 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3252 initiator_rfh, same_document_loads) &&
3253 DoesSandboxNavigationStayWithinSubtree(
3254 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503255 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163256 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203257 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3258 initiator_rfh,
3259 navigates_inside_tree
3260 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3261 : blink::mojom::WebFeature::
3262 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523263
3264 // If the navigation occurred outside the tree discard it because
3265 // the sandboxed frame didn't have permission to navigate outside
3266 // its tree. If it is possible that the navigation is both inside and
3267 // outside the frame tree and we discard it entirely because we don't
3268 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143269 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203270 // If a |navigation_api_key| was provided, this navigation originated from
3271 // the navigation API. Notify the renderer that the navigation was
3272 // cancelled so the navigation API can fire an error event and reject the
3273 // relevant promise.
3274 if (navigation_api_key) {
3275 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3276 *navigation_api_key,
3277 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3278 }
Dave Tapuska855c1e12019-08-23 20:45:523279 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133280
3281 for (auto& unused_request : same_document_loads) {
3282 unused_request->set_navigation_discard_reason(
3283 NavigationDiscardReason::kNeverStarted);
3284 }
3285 for (auto& unused_request : different_document_loads) {
3286 unused_request->set_navigation_discard_reason(
3287 NavigationDiscardReason::kNeverStarted);
3288 }
William Liu62ae26c2024-08-08 14:28:163289 return {};
Dave Tapuska855c1e12019-08-23 20:45:523290 }
Dave Tapuska8bfd84c2019-03-26 20:47:163291 }
3292
Nate Chapin6c43c022023-02-13 23:32:423293 // If it is possible that this traverse may involve a same-document navigation
3294 // in the initiator and there is a Navigation API key involved, then we may
3295 // need to notify the initiator if it fails. (The early returns above either
3296 // do not involve these cases or already notify the initiator.)
3297 // The event only needs to fire for the initiator, and only if the initiator
3298 // itself is performing a same-document navigation (because the event will not
3299 // fire if it navigates cross-document).
3300 if (navigation_api_key) {
3301 for (auto& item : same_document_loads) {
3302 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3303 item->set_pending_navigation_api_key(*navigation_api_key);
3304 break;
3305 }
3306 }
3307 }
3308
Carlos Caballero539a421c2020-07-06 10:25:573309 // BackForwardCache:
3310 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563311 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573312 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3313 DCHECK_EQ(reload_type, ReloadType::NONE);
3314 auto navigation_request = CreateNavigationRequestFromEntry(
3315 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3316 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333317 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3318 initiator_process_id);
William Liuec04e382024-05-23 18:03:273319 base::WeakPtr<NavigationRequest> request = navigation_request->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053320 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Rakina Zata Amni58681c62024-06-25 06:32:133321
3322 for (auto& unused_request : same_document_loads) {
3323 unused_request->set_navigation_discard_reason(
3324 NavigationDiscardReason::kNeverStarted);
3325 }
3326 for (auto& unused_request : different_document_loads) {
3327 unused_request->set_navigation_discard_reason(
3328 NavigationDiscardReason::kNeverStarted);
3329 }
3330
William Liu62ae26c2024-08-08 14:28:163331 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_request;
3332 if (request) {
3333 bf_cache_request.push_back(std::move(request));
3334 }
3335 return bf_cache_request;
Carlos Caballero539a421c2020-07-06 10:25:573336 }
3337
3338 // History navigation might try to reuse a specific BrowsingInstance, already
3339 // used by a page in the cache. To avoid having two different main frames that
3340 // live in the same BrowsingInstance, evict the all pages with this
3341 // BrowsingInstance from the cache.
3342 //
3343 // For example, take the following scenario:
3344 //
3345 // A1 = Some page on a.com
3346 // A2 = Some other page on a.com
3347 // B3 = An uncacheable page on b.com
3348 //
3349 // Then the following navigations occur:
3350 // A1->A2->B3->A1
3351 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3352 // take its place) and A1 will be created in the same BrowsingInstance (and
3353 // SiteInstance), as A2.
3354 //
3355 // If we didn't do anything, both A1 and A2 would remain alive in the same
3356 // BrowsingInstance/SiteInstance, which is unsupported by
3357 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3358 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483359 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3360 pending_entry_->site_instance()
3361 ? pending_entry_->site_instance()->GetId().value()
3362 : -1);
3363 SCOPED_CRASH_KEY_NUMBER(
3364 "rvh_double", "pending_entry_bi",
3365 pending_entry_->site_instance()
3366 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3367 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573368 if (pending_entry_->site_instance()) {
3369 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3370 pending_entry_->site_instance());
3371 }
3372
Rakina Zata Amnid605d462022-06-01 10:17:033373 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3374 pending_entry_ && pending_entry_->IsRestored());
3375 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3376 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3377 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3378 pending_entry_index_);
3379 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3380 last_committed_entry_index_);
3381 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3382 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3383 pending_entry_ && pending_entry_->IsInitialEntry());
3384 SCOPED_CRASH_KEY_BOOL(
3385 "nav_reentrancy", "pending_entry_initial2",
3386 pending_entry_ &&
3387 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3388 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3389 IsInitialNavigation());
3390 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3391 IsInitialBlankNavigation());
3392 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3393 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3394 (int)pending_reload_);
3395
clamy3cb9bea92018-07-10 12:42:023396 // This call does not support re-entrancy. See http://crbug.com/347742.
3397 CHECK(!in_navigate_to_pending_entry_);
3398 in_navigate_to_pending_entry_ = true;
Minoru Chikamune646eba42025-04-14 01:25:033399 CheckPotentialNavigationReentrancy();
creis4e2ecb72015-06-20 00:46:303400
Rakina Zata Amnid605d462022-06-01 10:17:033401 // If the navigation-reentrancy is caused by calling
3402 // NavigateToExistingPendingEntry twice, this will note the previous call's
3403 // pending entry's ID.
3404 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3405 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3406
arthursonzogni66f711c2019-10-08 14:40:363407 // It is not possible to delete the pending NavigationEntry while navigating
3408 // to it. Grab a reference to delay potential deletion until the end of this
3409 // function.
3410 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3411
Nate Chapin154b14b2023-02-17 18:28:163412 // If there is a main-frame same-document history navigation, we may defer
3413 // the subframe history navigations in order to give JS in the main frame the
3414 // opportunity to cancel the entire traverse via the navigate event. In that
3415 // case, we need to stash the main frame request's navigation token on the
3416 // subframes, so they can look up the main frame request and defer themselves
3417 // until it completes.
3418 if (!same_document_loads.empty() &&
3419 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3420 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3421 // The token will only be returned in cases where deferring the navigation
3422 // is necessary.
3423 if (auto main_frame_same_document_token =
3424 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3425 for (auto& item : same_document_loads) {
3426 if (item.get() != main_frame_request) {
3427 item->set_main_frame_same_document_history_token(
3428 main_frame_same_document_token);
3429 }
3430 }
3431 for (auto& item : different_document_loads) {
3432 item->set_main_frame_same_document_history_token(
3433 main_frame_same_document_token);
3434 }
3435 }
3436 }
3437
William Liu122754942024-01-18 22:34:393438 if (!initiator_rfh) {
3439 // A browser-initiated navigation won't have a `initiator_rfh`.
3440 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3441 different_document_loads, same_document_loads);
3442 }
3443
William Liu62ae26c2024-08-08 14:28:163444 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3445 all_requests.reserve(same_document_loads.size() +
3446 different_document_loads.size());
3447 bool seen_primary_main_frame_request = false;
3448
creis4e2ecb72015-06-20 00:46:303449 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023450 for (auto& item : same_document_loads) {
3451 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273452 // The request could be destroyed before `navigator().Navigate()` returns.
3453 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053454 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163455 if (request) {
3456 // Can only have one primary main frame request.
3457 CHECK(!seen_primary_main_frame_request ||
3458 !request->IsInPrimaryMainFrame());
3459 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3460 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273461 }
creis4e2ecb72015-06-20 00:46:303462 }
clamy3cb9bea92018-07-10 12:42:023463 for (auto& item : different_document_loads) {
3464 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273465 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053466 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163467 if (request) {
3468 // Can only have one primary main frame request.
3469 CHECK(!seen_primary_main_frame_request ||
3470 !request->IsInPrimaryMainFrame());
3471 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3472 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273473 }
creis4e2ecb72015-06-20 00:46:303474 }
clamy3cb9bea92018-07-10 12:42:023475
3476 in_navigate_to_pending_entry_ = false;
William Liuec04e382024-05-23 18:03:273477
William Liu62ae26c2024-08-08 14:28:163478 return all_requests;
creis4e2ecb72015-06-20 00:46:303479}
3480
Alex Moshchuk3a4e77a2020-05-29 21:32:573481NavigationControllerImpl::HistoryNavigationAction
3482NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303483 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573484 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423485 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583486 // Only active and prerendered documents are allowed to navigate in their
3487 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423488 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013489 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583490 // - If the document is in pending deletion, the browser already committed
3491 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3492 // - If the document is in back-forward cache, it's not allowed to navigate
3493 // as it should remain frozen. Ignore the request and evict the document
3494 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423495 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583496 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423497 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113498 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3499 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423500 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113501 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423502 }
arthursonzogni03f76152019-02-12 10:35:203503
Alex Moshchuk3a4e77a2020-05-29 21:32:573504 // Reloads should result in a different-document load. Note that reloads may
3505 // also happen via the |needs_reload_| mechanism where the reload_type is
3506 // NONE, so detect this by comparing whether we're going to the same
3507 // entry that we're currently on. Similarly to above, only main frames
3508 // should reach this. Note that subframes support reloads, but that's done
3509 // via a different path that doesn't involve FindFramesToNavigate (see
3510 // RenderFrameHost::Reload()).
3511 if (reload_type != ReloadType::NONE ||
3512 pending_entry_index_ == last_committed_entry_index_) {
3513 DCHECK(frame->IsMainFrame());
3514 return HistoryNavigationAction::kDifferentDocument;
3515 }
3516
Alex Moshchuk47d1a4bd2020-06-01 22:15:343517 // If there is no new FrameNavigationEntry for the frame, ignore the
3518 // load. For example, this may happen when going back to an entry before a
3519 // frame was created. Suppose we commit a same-document navigation that also
3520 // results in adding a new subframe somewhere in the tree. If we go back,
3521 // the new subframe will be missing a FrameNavigationEntry in the previous
3522 // NavigationEntry, but we shouldn't delete or change what's loaded in
3523 // it.
3524 //
Alex Moshchuke65c39272020-06-03 17:55:373525 // Note that in this case, there is no need to keep looking for navigations
3526 // in subframes, which would be missing FrameNavigationEntries as well.
3527 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343528 // It's important to check this before checking |old_item| below, since both
3529 // might be null, and in that case we still shouldn't change what's loaded in
3530 // this frame. Note that scheduling any loads assumes that |new_item| is
3531 // non-null. See https://crbug.com/1088354.
3532 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3533 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373534 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343535
Charlie Reisa474fb62022-03-17 02:31:363536 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3537 // which history item it is currently on, since this may be different than the
3538 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3539 // (e.g., if a history navigation is targeting multiple frames and only some
3540 // have committed so far).
creis4e2ecb72015-06-20 00:46:303541 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363542 frame->current_frame_host()->last_committed_frame_entry();
3543 if (!old_item) {
3544 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3545 // fall back to the last committed NavigationEntry's record for this frame.
3546 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583547 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363548 // accurate FrameNavigationEntry and eliminate this case.
3549 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3550 }
3551 // If neither approach finds a FrameNavigationEntry, schedule a
3552 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583553 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573554 if (!old_item)
3555 return HistoryNavigationAction::kDifferentDocument;
3556
Alex Moshchuk3a4e77a2020-05-29 21:32:573557 // If the new item is not in the same SiteInstance, schedule a
3558 // different-document load. Newly restored items may not have a SiteInstance
3559 // yet, in which case it will be assigned on first commit.
3560 if (new_item->site_instance() &&
3561 new_item->site_instance() != old_item->site_instance())
3562 return HistoryNavigationAction::kDifferentDocument;
3563
Charlie Reis71e4ae32025-01-29 21:37:573564 // If the origins of the new and old items are both present but don't match,
3565 // schedule a different document load even if the document sequence numbers
3566 // somehow match.
3567 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3568 // committed origin on `new_item`, and update the Blink DSN computation to
3569 // avoid a cross-origin DSN match when possible.
3570 if (new_item->committed_origin().has_value() &&
3571 old_item->committed_origin().has_value() &&
3572 !new_item->committed_origin()->IsSameOriginWith(
3573 old_item->committed_origin().value())) {
3574 return HistoryNavigationAction::kDifferentDocument;
3575 }
3576
Alex Moshchuk3a4e77a2020-05-29 21:32:573577 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313578 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3579 // that we do this even if the history navigation would not be modifying this
3580 // frame were it live.
3581 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573582 return HistoryNavigationAction::kDifferentDocument;
3583
3584 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313585 // Starting a navigation after a crash early-promotes the speculative
3586 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3587 // committed yet, so we can not possibly perform a same-document history
3588 // navigation. The frame would need to be reloaded with a cross-document
3589 // navigation.
3590 if (!frame->current_frame_host()->has_committed_any_navigation())
3591 return HistoryNavigationAction::kDifferentDocument;
3592
creis54131692016-08-12 18:32:253593 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493594 // sequence number but different item sequence number.
3595 if (new_item->document_sequence_number() ==
3596 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573597 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493598 }
avib48cb312016-05-05 21:35:003599
Alex Moshchuk3a4e77a2020-05-29 21:32:573600 // Otherwise, if both item and document sequence numbers differ, this
3601 // should be a different document load.
3602 return HistoryNavigationAction::kDifferentDocument;
3603 }
3604
3605 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373606 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573607 DCHECK_EQ(new_item->document_sequence_number(),
3608 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373609 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573610}
3611
3612void NavigationControllerImpl::FindFramesToNavigate(
3613 FrameTreeNode* frame,
3614 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373615 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333616 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373617 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133618 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573619 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3620 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3621 DCHECK(pending_entry_);
3622 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3623
3624 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3625
3626 if (action == HistoryNavigationAction::kSameDocument) {
3627 std::unique_ptr<NavigationRequest> navigation_request =
3628 CreateNavigationRequestFromEntry(
3629 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133630 /*is_same_document_history_load=*/true,
3631 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333632 initiator_frame_token, initiator_process_id,
3633 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573634 if (navigation_request) {
3635 // Only add the request if was properly created. It's possible for the
3636 // creation to fail in certain cases, e.g. when the URL is invalid.
3637 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303638 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573639 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473640 std::unique_ptr<NavigationRequest> navigation_request =
3641 CreateNavigationRequestFromEntry(
3642 frame, pending_entry_, new_item, reload_type,
3643 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433644 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333645 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473646 if (navigation_request) {
3647 // Only add the request if was properly created. It's possible for the
3648 // creation to fail in certain cases, e.g. when the URL is invalid.
3649 different_document_loads->push_back(std::move(navigation_request));
3650 }
3651 // For a different document, the subframes will be destroyed, so there's
3652 // no need to consider them.
3653 return;
Alex Moshchuke65c39272020-06-03 17:55:373654 } else if (action == HistoryNavigationAction::kStopLooking) {
3655 return;
creis4e2ecb72015-06-20 00:46:303656 }
3657
Yoav Weiss8c573952022-11-17 17:35:133658 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3659 // we currently only support soft navigation heuristics for the top level
3660 // frame.
creis4e2ecb72015-06-20 00:46:303661 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333662 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3663 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373664 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433665 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303666 }
3667}
3668
Harkiran Bolariaba823e42021-05-21 18:30:363669base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243670 const LoadURLParams& params) {
3671 // Find the appropriate FrameTreeNode.
3672 FrameTreeNode* node = nullptr;
Avi Drissmanbd153642024-09-03 18:58:053673 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3674 node = params.frame_tree_node_id
Ali Hijazid87307d2022-11-07 20:15:033675 ? frame_tree_->FindByID(params.frame_tree_node_id)
3676 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503677 DCHECK(!node || &node->frame_tree() == &frame_tree());
Kevin McNee37a109792025-04-14 21:16:383678 if (!node && params.frame_tree_node_id) {
3679 // If the specified FrameTreeNode exists in another FrameTree, the caller
3680 // is using the wrong NavigationController.
3681 CHECK(!FrameTreeNode::GloballyFindByID(params.frame_tree_node_id),
3682 base::NotFatalUntil::M140);
3683 }
clamy21718cc22018-06-13 13:34:243684 }
3685
3686 // If no FrameTreeNode was specified, navigate the main frame.
3687 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033688 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243689
Camille Lamy5193caa2018-10-12 11:59:423690 // Compute overrides to the LoadURLParams for |override_user_agent|,
3691 // |should_replace_current_entry| and |has_user_gesture| that will be used
3692 // both in the creation of the NavigationEntry and the NavigationRequest.
3693 // Ideally, the LoadURLParams themselves would be updated, but since they are
3694 // passed as a const reference, this is not possible.
3695 // TODO(clamy): When we only create a NavigationRequest, move this to
3696 // CreateNavigationRequestFromLoadURLParams.
3697 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3698 GetLastCommittedEntry());
3699
Rakina Zata Amnie2d31312022-11-18 03:38:453700 // An entry replacement must happen if the current browsing context should
3701 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333702 bool should_replace_current_entry =
3703 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453704 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423705
clamy21718cc22018-06-13 13:34:243706 // Javascript URLs should not create NavigationEntries. All other navigations
3707 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243708 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373709 std::unique_ptr<NavigationEntryImpl> entry =
3710 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3711 should_replace_current_entry,
3712 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243713 DiscardPendingEntry(false);
3714 SetPendingEntry(std::move(entry));
3715 }
3716
Tim Judkins59548192023-05-17 17:51:203717 // Renderer-debug URLs are sent to the current renderer process immediately
3718 // for processing and don't need to create a NavigationRequest. Note: this
3719 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243720 // renderer-debug URLs.
3721 // Note: we intentionally leave the pending entry in place for renderer debug
3722 // URLs, unlike the cases below where we clear it if the navigation doesn't
3723 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303724 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483725 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3726 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153727 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203728 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483729 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363730 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483731 }
3732
clamy21718cc22018-06-13 13:34:243733 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363734 return nullptr;
clamy21718cc22018-06-13 13:34:243735 }
3736
Antonio Sartori78a749f2020-11-30 12:03:393737 DCHECK(pending_entry_);
3738
clamy21718cc22018-06-13 13:34:243739 // Convert navigations to the current URL to a reload.
3740 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3741 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3742 // DevTools sometimes issues navigations to main frames that they do not
3743 // expect to see treated as reload, and it only works because they pass a
3744 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3745 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543746 ReloadType reload_type = params.reload_type;
3747 if (reload_type == ReloadType::NONE &&
3748 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043749 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243750 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243751 params.load_type ==
3752 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543753 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243754 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473755 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393756
3757 // If this is a reload of an existing FrameNavigationEntry and we had a
3758 // policy container for it, then we should copy it into the pending entry,
3759 // so that it is copied to the navigation request in
3760 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453761 FrameNavigationEntry* previous_frame_entry =
3762 GetLastCommittedEntry()->GetFrameEntry(node);
3763 if (previous_frame_entry &&
3764 previous_frame_entry->policy_container_policies()) {
3765 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3766 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393767 }
3768 }
3769
3770 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173771 // document, then we should copy the document polices from RenderFrameHost's
3772 // PolicyContainerHost. The NavigationRequest will create a new
3773 // PolicyContainerHost with the document policies from the |pending_entry_|,
3774 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3775 // the navigation. This way, we ensure that we keep enforcing the right
3776 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453777 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393778 if (node->current_frame_host() &&
3779 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193780 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163781 node->current_frame_host()
3782 ->policy_container_host()
3783 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233784 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393785 }
clamy21718cc22018-06-13 13:34:243786 }
3787
3788 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263789 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243790
Tsuyoshi Horo167ca6432022-03-09 05:16:393791 // This will be used to set the Navigation Timing API navigationStart
3792 // parameter for browser navigations in new tabs (intents, tabs opened through
3793 // "Open link in new tab"). If the navigation must wait on the current
3794 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3795 // will be updated when the BeforeUnload ack is received.
3796 const auto navigation_start_time = base::TimeTicks::Now();
Charlie Reise1d9b8182025-04-02 04:32:123797 // For now, treat this as the actual navigation start time as well, even
3798 // though a fair amount of work is done in the browser process between the
3799 // various ways to start a navigation and reaching here (e.g., sending
3800 // OpenURLParams through the embedder and converting them to LoadURLParams).
3801 // Note that this may be used for some renderer-initiated navigations that go
3802 // through RenderFrameHostImpl::OpenURL as well.
3803 // TODO(crbug.com/385170155): Consider whether tracking this earlier work with
3804 // an earlier start time is worthwhile for metrics.
3805 const auto actual_navigation_start_time = navigation_start_time;
Tsuyoshi Horo167ca6432022-03-09 05:16:393806
Camille Lamy5193caa2018-10-12 11:59:423807 std::unique_ptr<NavigationRequest> request =
3808 CreateNavigationRequestFromLoadParams(
3809 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143810 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393811 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
Charlie Reise1d9b8182025-04-02 04:32:123812 actual_navigation_start_time, navigation_start_time);
clamy21718cc22018-06-13 13:34:243813
3814 // If the navigation couldn't start, return immediately and discard the
3815 // pending NavigationEntry.
3816 if (!request) {
3817 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363818 return nullptr;
clamy21718cc22018-06-13 13:34:243819 }
3820
Camille Lamy5193caa2018-10-12 11:59:423821#if DCHECK_IS_ON()
3822 // Safety check that NavigationRequest and NavigationEntry match.
3823 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3824#endif
3825
clamy21718cc22018-06-13 13:34:243826 // This call does not support re-entrancy. See http://crbug.com/347742.
3827 CHECK(!in_navigate_to_pending_entry_);
3828 in_navigate_to_pending_entry_ = true;
Minoru Chikamune646eba42025-04-14 01:25:033829 CheckPotentialNavigationReentrancy();
clamy21718cc22018-06-13 13:34:243830
arthursonzogni66f711c2019-10-08 14:40:363831 // It is not possible to delete the pending NavigationEntry while navigating
3832 // to it. Grab a reference to delay potential deletion until the end of this
3833 // function.
3834 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3835
Harkiran Bolariaba823e42021-05-21 18:30:363836 base::WeakPtr<NavigationHandle> created_navigation_handle(
3837 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053838 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243839
3840 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363841 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243842}
3843
clamyea99ea12018-05-28 13:54:233844void NavigationControllerImpl::HandleRendererDebugURL(
3845 FrameTreeNode* frame_tree_node,
3846 const GURL& url) {
3847 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243848 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3849 // the renderer process is not live, unless it is the initial navigation
3850 // of the tab.
clamyea99ea12018-05-28 13:54:233851 if (!IsInitialNavigation()) {
3852 DiscardNonCommittedEntries();
3853 return;
3854 }
Fergal Dalyecd3b0202020-06-25 01:57:373855 // The current frame is always a main frame. If IsInitialNavigation() is
3856 // true then there have been no navigations and any frames of this tab must
3857 // be in the same renderer process. If that has crashed then the only frame
3858 // that can be revived is the main frame.
3859 frame_tree_node->render_manager()
3860 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233861 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223862
3863 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3864 // notification, so set is loading to true here to properly surface it when
3865 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313866 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223867 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223868 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223869 }
clamyea99ea12018-05-28 13:54:233870 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3871}
3872
clamy21718cc22018-06-13 13:34:243873std::unique_ptr<NavigationEntryImpl>
3874NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3875 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423876 const LoadURLParams& params,
3877 bool override_user_agent,
3878 bool should_replace_current_entry,
3879 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393880 // Browser initiated navigations might not have a blob_url_loader_factory set
3881 // in params even if the navigation is to a blob URL. If that happens, lookup
3882 // the correct url loader factory to use here.
3883 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483884 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473885 // Resolve the blob URL in the storage partition associated with the target
3886 // frame. This is the storage partition the URL will be loaded in, and only
3887 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393888 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473889 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393890 }
3891
clamy21718cc22018-06-13 13:34:243892 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443893 // extra_headers in params are \n separated; navigation entries want \r\n.
3894 std::string extra_headers_crlf;
3895 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243896
3897 // For subframes, create a pending entry with a corresponding frame entry.
3898 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453899 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243900 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083901 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243902 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373903 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213904 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3905 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393906 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163907 // a conversion of a new navigation into a reload, we will set the right
3908 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193909 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243910 } else {
3911 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173912 // If `node` is the outermost main frame, it rewrites a virtual url in order
3913 // to adjust the original input url if needed. For inner frames such as
3914 // fenced frames or subframes, they don't rewrite urls as the urls are not
3915 // input urls by users.
3916 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323917 scoped_refptr<SiteInstance> source_site_instance =
3918 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373919 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323920 if (source_site_instance && source_site_instance->HasProcess()) {
3921 source_process_site_url =
3922 source_site_instance->GetProcess()->GetProcessLock().site_url();
3923 }
clamy21718cc22018-06-13 13:34:243924 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063925 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323926 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213927 params.transition_type, params.is_renderer_initiated,
3928 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3929 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243930 entry->set_source_site_instance(
3931 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3932 entry->SetRedirectChain(params.redirect_chain);
3933 }
3934
3935 // Set the FTN ID (only used in non-site-per-process, for tests).
3936 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243937 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423938 entry->SetIsOverridingUserAgent(override_user_agent);
3939 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543940 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243941
clamy21718cc22018-06-13 13:34:243942 switch (params.load_type) {
3943 case LOAD_TYPE_DEFAULT:
3944 break;
3945 case LOAD_TYPE_HTTP_POST:
3946 entry->SetHasPostData(true);
3947 entry->SetPostData(params.post_data);
3948 break;
3949 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:543950 // LoadDataWithBaseURL is a special case that needs to assign both a base
3951 // URL and a virtual URL, while loading the actual content from a data
3952 // URL.
clamy21718cc22018-06-13 13:34:243953 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:543954 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:283955#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243956 entry->SetDataURLAsString(params.data_url_as_string);
3957#endif
3958 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3959 break;
Shu Yang112ad492024-07-25 17:11:543960#if BUILDFLAG(IS_ANDROID)
3961 case LOAD_TYPE_PDF_ANDROID:
3962 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
3963 // internal URL is used for the navigation URL.
3964 entry->SetVirtualURL(params.virtual_url_for_special_cases);
3965 break;
3966#endif
clamy21718cc22018-06-13 13:34:243967 }
3968
3969 // TODO(clamy): NavigationEntry is meant for information that will be kept
3970 // after the navigation ended and therefore is not appropriate for
3971 // started_from_context_menu. Move started_from_context_menu to
3972 // NavigationUIData.
3973 entry->set_started_from_context_menu(params.started_from_context_menu);
3974
3975 return entry;
3976}
3977
clamyea99ea12018-05-28 13:54:233978std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423979NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3980 FrameTreeNode* node,
3981 const LoadURLParams& params,
3982 bool override_user_agent,
3983 bool should_replace_current_entry,
3984 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143985 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423986 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573987 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393988 FrameNavigationEntry* frame_entry,
Charlie Reise1d9b8182025-04-02 04:32:123989 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:223990 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493991 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453992 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583993 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343994 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:373995 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573996 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:523997
3998 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
3999 // subframes have FrameNavigationEntries associated with them. Until then,
4000 // there may be cases where a subframe navigation is missing `frame_entry`
4001 // (e.g., see https://crbug.com/358084015).
4002
Nasko Oskov3c2f9e252019-01-10 17:45:534003 // All renderer-initiated navigations must have an initiator_origin.
4004 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:514005
Camille Lamy5193caa2018-10-12 11:59:424006 GURL url_to_load;
4007 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:324008
Camille Lamy2baa8022018-10-19 16:43:174009 // For main frames, rewrite the URL if necessary and compute the virtual URL
4010 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:264011 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424012 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:174013 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424014 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:424015
Shu Yang112ad492024-07-25 17:11:544016 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
4017 // that need to define a virtual URL to display, which differs from the
4018 // navigation URL.
4019 if (params.load_type == LOAD_TYPE_DATA) {
4020 virtual_url = params.virtual_url_for_special_cases;
4021 }
4022#if BUILDFLAG(IS_ANDROID)
4023 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
4024 virtual_url = params.virtual_url_for_special_cases;
4025 }
4026#endif
Camille Lamy5193caa2018-10-12 11:59:424027
Camille Lamy2baa8022018-10-19 16:43:174028 if (virtual_url.is_empty())
4029 virtual_url = url_to_load;
4030
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574031 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:284032
Aran Gilman249eb122019-12-02 23:32:464033 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
4034 // behavior: it is possible for two calls to RewriteUrlForNavigation to
4035 // return different results, leading to a different URL in the
4036 // NavigationRequest and FrameEntry. This will be fixed once we remove the
4037 // pending NavigationEntry, as we'll only make one call to
4038 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:524039 if (frame_entry) {
4040 VLOG_IF(1, (url_to_load != frame_entry->url()))
4041 << "NavigationRequest and FrameEntry have different URLs: "
4042 << url_to_load << " vs " << frame_entry->url();
4043 }
Camille Lamyb9ed3c52018-11-19 15:34:284044
Camille Lamy2baa8022018-10-19 16:43:174045 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424046 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174047 // NavigationRequest.
4048 } else {
4049 url_to_load = params.url;
4050 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244051 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174052 }
Camille Lamy5193caa2018-10-12 11:59:424053
Ehsan Karamad44fc72112019-02-26 18:15:474054 if (node->render_manager()->is_attaching_inner_delegate()) {
4055 // Avoid starting any new navigations since this node is now preparing for
4056 // attaching an inner delegate.
4057 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204058 }
Camille Lamy5193caa2018-10-12 11:59:424059
Alex Moshchuk99242832023-05-22 17:21:444060 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424061 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444062 }
Camille Lamy5193caa2018-10-12 11:59:424063
danakjd83d706d2020-11-25 22:11:124064 // Look for a pending commit that is to another document in this
4065 // FrameTreeNode. If one exists, then the last committed URL will not be the
4066 // current URL by the time this navigation commits.
4067 bool has_pending_cross_document_commit =
4068 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214069 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124070
Minggang Wangb9f3fa92021-07-01 15:30:314071 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494072 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524073 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494074 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134075 /*is_same_document_history_load=*/false,
4076 is_embedder_initiated_fenced_frame_navigation,
4077 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424078
4079 // Create the NavigationParams based on |params|.
4080
Hiroki Nakagawa4ed61282021-06-18 05:37:234081 bool is_view_source_mode = entry->IsViewSourceMode();
4082 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294083
Antonio Sartori6984c742021-08-26 08:03:414084 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294085
Hiroki Nakagawa4ed61282021-06-18 05:37:234086 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294087 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254088 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294089
Charlie Reisf21cd182024-08-09 21:44:524090 std::string page_state_data =
4091 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4092
Minggang Wangb9f3fa92021-07-01 15:30:314093 blink::mojom::CommonNavigationParamsPtr common_params =
4094 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214095 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514096 blink::mojom::Referrer::New(params.referrer.url,
4097 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214098 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514099 should_replace_current_entry, params.base_url_for_data_url,
Charlie Reise1d9b8182025-04-02 04:32:124100 actual_navigation_start_time, navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514101 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144102 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414103 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274104 false /* has_text_fragment_token */,
4105 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4106 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514107 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054108 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424109
Minggang Wangb9f3fa92021-07-01 15:30:314110 blink::mojom::CommitNavigationParamsPtr commit_params =
4111 blink::mojom::CommitNavigationParams::New(
Diana Quae845bf2025-04-03 20:12:374112 url::Origin(),
Ari Chivukulac7533522024-05-14 21:52:344113 // The correct storage key will be computed before committing the
4114 // navigation.
4115 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324116 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504117 std::vector<net::RedirectInfo>(), params.post_content_type,
4118 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524119 params.can_load_local_resources, page_state_data,
4120 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134121 /*intended_as_new_entry=*/true,
Charlie Reis99b2eba22025-01-31 19:18:574122 /*pending_history_list_index=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144123 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4124 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134125 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314126 params.should_clear_history_list,
4127 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224128 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134129 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514130 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284131#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134132 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144133#endif
Yoav Weiss8c573952022-11-17 17:35:134134 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154135 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134136 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074137 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134138 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4139 /*origin_agent_cluster=*/false,
4140 /*origin_agent_cluster_left_as_default=*/true,
4141 /*enabled_client_hints=*/
4142 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264143 /*is_cross_site_cross_browsing_context_group=*/false,
4144 /*should_have_sticky_user_activation=*/false,
4145 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134146 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014147 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134148 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584149 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134150 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134151 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284152 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134153 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444154 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424155 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374156 /*view_transition_state=*/std::nullopt,
4157 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054158 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464159 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374160 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054161 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094162 /*load_with_storage_access=*/
4163 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374164 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374165 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484166 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314167 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164168 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174169 node->current_frame_host()->GetCachedPermissionStatuses(),
Charlie Reiscdb798342025-02-14 22:04:464170 /*should_skip_screentshot=*/false,
Alex Moshchukd0d759c22025-05-09 18:18:354171 /*force_new_document_sequence_number=*/false,
4172 /*navigation_metrics_token=*/base::UnguessableToken::Create());
Xiaohan Wang7f8052e02022-01-14 18:44:284173#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424174 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564175 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424176 }
4177#endif
4178
Lucas Furukawa Gadania9c45682019-07-31 22:05:144179 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074180 commit_params->navigation_timing->system_entropy_at_navigation_start =
4181 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4182 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424183
Camille Lamy5193caa2018-10-12 11:59:424184 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4185 std::string extra_headers_crlf;
4186 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094187
Alex Moshchuk9321e6a2022-12-07 21:58:314188 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144189 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084190 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094191 params.initiator_frame_token, params.initiator_process_id,
4192 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214193 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294194 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454195 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344196 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034197 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134198
4199 if (!navigation_request) {
4200 return nullptr;
4201 }
4202
Yao Xiaodc5ed102019-06-04 19:19:094203 navigation_request->set_from_download_cross_origin_redirect(
4204 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554205 navigation_request->set_force_new_browsing_instance(
4206 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514207 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434208 if (params.force_no_https_upgrade) {
4209 navigation_request->set_force_no_https_upgrade();
4210 }
Yao Xiaodc5ed102019-06-04 19:19:094211 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424212}
4213
4214std::unique_ptr<NavigationRequest>
4215NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234216 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574217 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234218 FrameNavigationEntry* frame_entry,
4219 ReloadType reload_type,
4220 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434221 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374222 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334223 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374224 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134225 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344226 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234227 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434228 // We should never navigate to an existing initial NavigationEntry that is the
4229 // initial NavigationEntry for the initial empty document that hasn't been
4230 // overridden by the synchronous about:blank commit, to preserve previous
4231 // behavior where trying to reload when the main frame is on the initial empty
4232 // document won't result in a navigation.
4233 // See also https://crbug.com/1277414.
4234 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324235
clamyea99ea12018-05-28 13:54:234236 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234237
Ehsan Karamad44fc72112019-02-26 18:15:474238 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4239 // Avoid starting any new navigations since this node is now preparing for
4240 // attaching an inner delegate.
4241 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204242 }
4243
Alex Moshchuk99242832023-05-22 17:21:444244 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4245 dest_url)) {
clamyea99ea12018-05-28 13:54:234246 return nullptr;
4247 }
4248
clamyea99ea12018-05-28 13:54:234249 // This will be used to set the Navigation Timing API navigationStart
4250 // parameter for browser navigations in new tabs (intents, tabs opened through
4251 // "Open link in new tab"). If the navigation must wait on the current
4252 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4253 // will be updated when the BeforeUnload ack is received.
Charlie Reise1d9b8182025-04-02 04:32:124254 // TODO(crbug.com/385170155): Consider whether to track an earlier
4255 // `actual_navigation_start` by plumbing it from the the initiator (e.g.,
4256 // for renderer-initiated history navigations, etc).
clamyea99ea12018-05-28 13:54:234257 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074258 const auto navigation_start_system_entropy =
4259 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4260 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234261
danakjd83d706d2020-11-25 22:11:124262 // Look for a pending commit that is to another document in this
4263 // FrameTreeNode. If one exists, then the last committed URL will not be the
4264 // current URL by the time this navigation commits.
4265 bool has_pending_cross_document_commit =
4266 frame_tree_node->render_manager()
4267 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494268 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214269 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124270
Minggang Wangb9f3fa92021-07-01 15:30:314271 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124272 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524273 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494274 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494275 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134276 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494277 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424278
4279 // A form submission may happen here if the navigation is a
4280 // back/forward/reload navigation that does a form resubmission.
4281 scoped_refptr<network::ResourceRequestBody> request_body;
4282 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394283 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504284 // entry. This way, it could be directly retrieved here. Right now, it is only
4285 // partially recovered when request.method == "POST" and request.body exists.
4286 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424287 if (frame_entry->method() == "POST") {
4288 request_body = frame_entry->GetPostData(&post_content_type);
4289 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304290 post_content_type = std::string(
4291 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504292 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424293 }
4294
4295 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314296 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514297 entry->ConstructCommonNavigationParams(
4298 *frame_entry, request_body, dest_url,
4299 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Charlie Reise1d9b8182025-04-02 04:32:124300 navigation_type, /*actual_navigation_start=*/navigation_start,
4301 navigation_start,
4302 /*input_start=*/base::TimeTicks());
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514303 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554304 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424305
4306 // TODO(clamy): |intended_as_new_entry| below should always be false once
4307 // Reload no longer leads to this being called for a pending NavigationEntry
4308 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314309 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144310 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404311 *frame_entry, common_params->url, common_params->method,
4312 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144313 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534314 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484315 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134316 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074317 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144318 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074319 commit_params->navigation_timing->system_entropy_at_navigation_start =
4320 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4321 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164322 commit_params->initial_permission_statuses =
4323 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424324
W. James MacLeanb7d6092682022-10-05 15:23:264325 if (common_params->url.IsAboutSrcdoc()) {
4326 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4327 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594328 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264329 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334330 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314331 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144332 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434333 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334334 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4335 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374336 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294337 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4338 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474339 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234340}
4341
[email protected]d202a7c2012-01-04 07:53:474342void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214343 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274344 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404345
Takashi Toyoshimaea534ef22021-07-21 03:27:594346 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404347 // location bar will have up-to-date information about the security style
4348 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134349 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404350
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374351 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574352 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294353}
4354
initial.commit09911bf2008-07-26 23:55:294355// static
[email protected]d202a7c2012-01-04 07:53:474356size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234357 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154358 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214359 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234360}
4361
[email protected]d202a7c2012-01-04 07:53:474362void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224363 if (is_active && needs_reload_)
4364 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214365
4366 if (frame_tree_->is_primary();
4367 auto* cache = GetNavigationEntryScreenshotCache()) {
4368 cache->SetVisible(is_active);
4369 }
initial.commit09911bf2008-07-26 23:55:294370}
4371
[email protected]d202a7c2012-01-04 07:53:474372void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034373 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4374 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294375 if (!needs_reload_)
4376 return;
4377
Bo Liucdfa4b12018-11-06 00:21:444378 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4379 needs_reload_type_);
4380
initial.commit09911bf2008-07-26 23:55:294381 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004382 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294383 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004384 if (entry_replaced_by_post_commit_error_) {
4385 // If the current entry is a post commit error, we reload the entry it
4386 // replaced instead. We leave the error entry in place until a commit
4387 // replaces it, but the pending entry points to the original entry in the
4388 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4389 // case that pending_entry_ != entries_[pending_entry_index_].
4390 // Note that this handling is similar to
4391 // `NavigationControllerImpl::Reload()`.
4392 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4393 pending_entry_index_ = GetCurrentEntryIndex();
4394 NavigateToExistingPendingEntry(
4395 ReloadType::NONE,
4396 /*initiator_rfh=*/nullptr,
4397 /*soft_navigation_heuristics_task_id=*/std::nullopt,
4398 /*navigation_api_key=*/nullptr);
4399 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134400 NavigateToExistingPendingEntry(
4401 ReloadType::NONE,
4402 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374403 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134404 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454405 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434406 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274407 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344408 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134409 NavigateToExistingPendingEntry(
4410 ReloadType::NONE,
4411 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374412 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134413 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344414 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434415 // We should never navigate to an existing initial NavigationEntry that is
4416 // the initial NavigationEntry for the initial empty document that hasn't
4417 // been overridden by the synchronous about:blank commit, to preserve
4418 // legacy behavior where trying to reload when the main frame is on the
4419 // initial empty document won't result in a navigation. See also
4420 // https://crbug.com/1277414. If there is something to reload, the
4421 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4422 // it here.
avicc872d7242015-08-19 21:26:344423 needs_reload_ = false;
4424 }
initial.commit09911bf2008-07-26 23:55:294425}
4426
Kevin McNeeccca6172021-10-19 17:11:144427base::WeakPtr<NavigationHandle>
4428NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364429 RenderFrameHost* render_frame_host,
4430 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364431 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134432 RenderFrameHostImpl* rfhi =
4433 static_cast<RenderFrameHostImpl*>(render_frame_host);
Andrew Verge754c70a2025-04-17 17:19:194434 std::unique_ptr<NavigationRequest> navigation_request =
4435 CreateNavigationRequestForErrorPage(rfhi, url, error_page_html,
4436 /*is_post_commit_error_page=*/true);
4437 if (!navigation_request) {
Kevin McNeeccca6172021-10-19 17:11:144438 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114439 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584440
Rakina Zata Amni919b7922020-12-11 09:03:134441 FrameTreeNode* node = rfhi->frame_tree_node();
Charlie Reis09952ee2022-12-08 16:35:074442 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414443 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144444
Andrew Verge754c70a2025-04-17 17:19:194445 // TODO(crbug.com/406729265): LoadPostCommitErrorPage() does not initiate a
4446 // navigation via Navigator::Navigate(). We should fix that, so that
4447 // post-commit error page navigations don't bypass other important checks in
4448 // this function.
Kevin McNeeccca6172021-10-19 17:11:144449 // Calling BeginNavigation may destroy the NavigationRequest.
4450 base::WeakPtr<NavigationRequest> created_navigation_request(
4451 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414452 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144453 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414454}
4455
Andrew Verge754c70a2025-04-17 17:19:194456void NavigationControllerImpl::NavigateFrameToErrorPage(
4457 RenderFrameHostImpl* render_frame_host_impl,
4458 const GURL& url,
4459 const std::string& error_page_html) {
4460 // For now, this function can only be used for fenced frame roots. In the
4461 // future, it will be updated to work for any frame.
4462 // TODO(crbug.com/406729265): Implement this method for all types of frames,
4463 // including main frames and other subframe types.
4464 CHECK(render_frame_host_impl->IsFencedFrameRoot());
4465
4466 std::unique_ptr<NavigationRequest> navigation_request =
4467 CreateNavigationRequestForErrorPage(render_frame_host_impl, url,
4468 error_page_html,
4469 /*is_post_commit_error_page=*/false);
4470 if (!navigation_request) {
4471 return;
4472 }
4473
4474 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
4475 node->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
4476}
4477
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574478void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214479 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094480 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154481 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144482 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294483}
4484
[email protected]d202a7c2012-01-04 07:53:474485void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364486 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584487 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474488 // represent a no-committed-entry state.
4489 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364490 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584491 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474492 // if `entries_` contains pre-existing entries from the NavigationController
4493 // before restore, which would not be removed and will be at the front of the
4494 // entries list, causing the index to be off by the amount of pre-existing
4495 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294496 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294497}
[email protected]765b35502008-08-21 00:51:204498
arthursonzogni69a6a1b2019-09-17 09:23:004499void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004500 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4501}
4502
4503void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4504 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474505 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104506 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4507 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294508 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474509 return;
Michael Thiessenc5676d22019-09-25 22:32:104510 }
avi45a72532015-04-07 21:01:454511 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314512
4513 if (!delegate_)
4514 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374515 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484516}
4517
avi7c6f35e2015-05-08 17:52:384518int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4519 int nav_entry_id) const {
4520 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4521 if (entries_[i]->GetUniqueID() == nav_entry_id)
4522 return i;
4523 }
4524 return -1;
4525}
4526
[email protected]d202a7c2012-01-04 07:53:474527void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574528 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254529 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574530 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594531 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254532 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374533 // Normally, cloning a NavigationEntryImpl results in sharing
4534 // FrameNavigationEntries between the original and the clone. However, when
4535 // cloning from a different NavigationControllerImpl, we want to fork the
4536 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374537 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594538 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254539 }
Rakina Zata Amnie2d31312022-11-18 03:38:454540 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274541 DCHECK(pending_entry_index_ == -1 ||
4542 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254543}
[email protected]c5b88d82012-10-06 17:03:334544
4545void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184546 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334547 get_timestamp_callback_ = get_timestamp_callback;
4548}
[email protected]8ff00d72012-10-23 19:12:214549
Shivani Sharmaffb32b82019-04-09 16:58:474550// History manipulation intervention:
4551void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474552 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564553 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404554 bool is_renderer_initiated,
4555 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564556 // Note that for a subframe,
4557 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454558 // gesture happened in any subframe (propagated to main frame) or in the main
4559 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564560 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274561 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474562 return;
4563 }
4564 if (last_committed_entry_index_ == -1)
4565 return;
4566
Shivani Sharmac4cc8922019-04-18 03:11:174567 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474568
Alexander Timine3ec4192020-04-20 16:39:404569 // Log UKM with the URL we are navigating away from.
4570 ukm::builders::HistoryManipulationIntervention(
4571 previous_page_load_ukm_source_id)
4572 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474573}
4574
Shivani Sharmac4cc8922019-04-18 03:11:174575void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4576 int reference_index,
4577 bool skippable) {
4578 auto* reference_entry = GetEntryAtIndex(reference_index);
4579 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4580
4581 int64_t document_sequence_number =
4582 reference_entry->root_node()->frame_entry->document_sequence_number();
4583 for (int index = 0; index < GetEntryCount(); index++) {
4584 auto* entry = GetEntryAtIndex(index);
4585 if (entry->root_node()->frame_entry->document_sequence_number() ==
4586 document_sequence_number) {
4587 entry->set_should_skip_on_back_forward_ui(skippable);
4588 }
4589 }
4590}
4591
arthursonzogni66f711c2019-10-08 14:40:364592std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4593NavigationControllerImpl::ReferencePendingEntry() {
4594 DCHECK(pending_entry_);
4595 auto pending_entry_ref =
4596 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4597 pending_entry_refs_.insert(pending_entry_ref.get());
4598 return pending_entry_ref;
4599}
4600
4601void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4602 // Ignore refs that don't correspond to the current pending entry.
4603 auto it = pending_entry_refs_.find(ref);
4604 if (it == pending_entry_refs_.end())
4605 return;
4606 pending_entry_refs_.erase(it);
4607
4608 if (!pending_entry_refs_.empty())
4609 return;
4610
4611 // The pending entry may be deleted before the last PendingEntryRef.
4612 if (!pending_entry_)
4613 return;
4614
4615 // We usually clear the pending entry when the matching NavigationRequest
4616 // fails, so that an arbitrary URL isn't left visible above a committed page.
4617 //
4618 // However, we do preserve the pending entry in some cases, such as on the
4619 // initial navigation of an unmodified blank tab. We also allow the delegate
4620 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4621 // user edit the URL and try again. This may be useful in cases that the
4622 // committed page cannot be attacker-controlled. In these cases, we still
4623 // allow the view to clear the pending entry and typed URL if the user
4624 // requests (e.g., hitting Escape with focus in the address bar).
4625 //
4626 // Do not leave the pending entry visible if it has an invalid URL, since this
4627 // might be formatted in an unexpected or unsafe way.
4628 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364629 bool should_preserve_entry =
4630 (pending_entry_ == GetVisibleEntry()) &&
4631 pending_entry_->GetURL().is_valid() &&
4632 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4633 if (should_preserve_entry)
4634 return;
4635
4636 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374637 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364638}
4639
Titouan Rigoudy6ec70402021-02-02 15:42:194640std::unique_ptr<PolicyContainerPolicies>
4641NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394642 RenderFrameHostImpl* rfh,
4643 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214644 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174645 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214646 if (navigation_encountered_error) {
4647 // We should never reload the policy container of an error page from
4648 // history, see https://crbug.com/364773822.
4649 return nullptr;
4650 }
4651
Antonio Sartori78a749f2020-11-30 12:03:394652 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454653 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394654 FrameNavigationEntry* previous_frame_entry =
4655 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4656
Alison Gale770f3fc2024-04-27 00:39:584657 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394658 // ensure we always have a FrameNavigationEntry here.
4659 if (!previous_frame_entry)
4660 return nullptr;
4661
Titouan Rigoudy6ec70402021-02-02 15:42:194662 const PolicyContainerPolicies* previous_policies =
4663 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394664
Titouan Rigoudy6ec70402021-02-02 15:42:194665 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394666 return nullptr;
4667
4668 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234669 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394670 }
4671
Titouan Rigoudy72f892d2022-05-02 18:21:234672 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394673}
4674
Charlie Reis99b2eba22025-01-31 19:18:574675void NavigationControllerImpl::BroadcastHistoryIndexAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504676 OPTIONAL_TRACE_EVENT2(
Charlie Reis99b2eba22025-01-31 19:18:574677 "content", "NavigationControllerImpl::BroadcastHistoryIndexAndLength",
4678 "history_index", GetLastCommittedEntryIndex(), "history_length",
Hayato Ito2c8c08d02021-06-23 03:38:434679 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504680
Charlie Reis99b2eba22025-01-31 19:18:574681 int history_index = GetLastCommittedEntryIndex();
Kevin McNee7705fe82024-11-07 18:56:314682 int history_length = GetEntryCount();
Charlie Reis99b2eba22025-01-31 19:18:574683 auto callback = [history_index, history_length](RenderViewHostImpl* rvh) {
Kevin McNee7705fe82024-11-07 18:56:314684 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
Charlie Reis99b2eba22025-01-31 19:18:574685 broadcast->SetHistoryIndexAndLength(history_index, history_length);
Kevin McNee7705fe82024-11-07 18:56:314686 }
4687 };
Ali Hijazid87307d2022-11-07 20:15:034688 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504689}
4690
4691void NavigationControllerImpl::DidAccessInitialMainDocument() {
4692 // We may have left a failed browser-initiated navigation in the address bar
4693 // to let the user edit it and try again. Clear it now that content might
4694 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034695 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504696 DiscardPendingEntry(false);
4697
4698 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374699 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504700}
4701
4702void NavigationControllerImpl::UpdateStateForFrame(
4703 RenderFrameHostImpl* rfhi,
4704 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564705 OPTIONAL_TRACE_EVENT1("content",
4706 "NavigationControllerImpl::UpdateStateForFrame",
4707 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504708 // The state update affects the last NavigationEntry associated with the given
4709 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4710 // in the case of an UpdateState from a frame being swapped out). We track
4711 // which entry this is in the RenderFrameHost's nav_entry_id.
4712 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4713 if (!entry)
4714 return;
4715
4716 FrameNavigationEntry* frame_entry =
4717 entry->GetFrameEntry(rfhi->frame_tree_node());
4718 if (!frame_entry)
4719 return;
4720
4721 // The SiteInstance might not match if we do a cross-process navigation with
4722 // replacement (e.g., auto-subframe), in which case the swap out of the old
4723 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4724 // has already been replaced and destroyed.
4725 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4726 return;
4727
4728 if (page_state == frame_entry->page_state())
4729 return; // Nothing to update.
4730
4731 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4732
4733 // The document_sequence_number and item_sequence_number recorded in the
4734 // FrameNavigationEntry should not differ from the one coming with the update,
4735 // since it must come from the same document. Do not update it if a difference
4736 // is detected, as this indicates that |frame_entry| is not the correct one.
4737 blink::ExplodedPageState exploded_state;
4738 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4739 return;
4740
4741 if (exploded_state.top.document_sequence_number !=
4742 frame_entry->document_sequence_number() ||
4743 exploded_state.top.item_sequence_number !=
4744 frame_entry->item_sequence_number()) {
4745 return;
4746 }
4747
4748 frame_entry->SetPageState(page_state);
4749 NotifyEntryChanged(entry);
4750}
4751
Nate Chapina2c881f52023-11-07 17:02:094752namespace {
4753
4754// The caller is responsible for ensuring the entry is same-origin to the
4755// origin to be committed.
4756blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4757 FrameNavigationEntry* frame_entry,
4758 int64_t pending_document_sequence_number) {
4759 blink::ExplodedPageState exploded_state;
4760 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4761 &exploded_state)) {
4762 return nullptr;
4763 }
4764 blink::ExplodedFrameState frame_state = exploded_state.top;
4765
4766 // If the document represented by this FNE hid its full url from appearing in
4767 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4768 // in the navigation API as well (unless we're navigating to that document).
4769 std::u16string url;
4770 if (pending_document_sequence_number ==
4771 frame_entry->document_sequence_number() ||
4772 !frame_entry->protect_url_in_navigation_api()) {
4773 url = frame_state.url_string.value_or(std::u16string());
4774 }
4775
4776 return blink::mojom::NavigationApiHistoryEntry::New(
4777 frame_state.navigation_api_key.value_or(std::u16string()),
4778 frame_state.navigation_api_id.value_or(std::u16string()), url,
4779 frame_state.item_sequence_number, frame_state.document_sequence_number,
4780 frame_state.navigation_api_state);
4781}
4782
4783} // namespace
4784
Domenic Denicolacd30f5f82022-03-16 21:48:014785std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4786NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574787 Direction direction,
4788 int entry_index,
4789 const url::Origin& pending_origin,
4790 FrameTreeNode* node,
4791 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304792 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094793 int64_t pending_document_sequence_number,
4794 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014795 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454796 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174797 // Don't process the initial entry.
4798 DCHECK_EQ(GetEntryCount(), 1);
4799 return entries;
4800 }
Nate Chapind1fe3612021-04-16 20:45:574801 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304802 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574803 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4804 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094805 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574806 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414807 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574808 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014809 // An entry should only appear in the navigation API entries if it is for
4810 // the same origin as the document being committed. Check the committed
4811 // origin, or if that is not available (during restore), check against the
4812 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584813 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094814 // once we can be sure that entries with the same ISN will never be
4815 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414816 url::Origin frame_entry_origin =
4817 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4818 frame_entry->url(),
4819 frame_entry->initiator_origin().value_or(url::Origin())));
4820 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574821 break;
4822 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4823 continue;
Nate Chapina2c881f52023-11-07 17:02:094824 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4825 ToNavigationApiHistoryEntry(frame_entry,
4826 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304827 DCHECK(entry->url.empty() ||
4828 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574829 entries.push_back(std::move(entry));
4830 previous_item_sequence_number = frame_entry->item_sequence_number();
4831 }
4832 }
4833 // If |entries| was constructed by iterating backwards from
4834 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4835 // earliest-at-the-front. Reverse it.
4836 if (direction == Direction::kBack)
4837 std::reverse(entries.begin(), entries.end());
4838 return entries;
4839}
4840
Domenic Denicolacd30f5f82022-03-16 21:48:014841blink::mojom::NavigationApiHistoryEntryArraysPtr
4842NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554843 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574844 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404845 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444846 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404847 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574848
Nate Chapind1fe3612021-04-16 20:45:574849 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554850 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574851
Nate Chapine82339d02022-05-03 23:48:254852 // NOTE: |entry_index| is the index where this entry will commit if no
4853 // modifications are made between now and DidCommitNavigation. This is used to
4854 // walk |entries_| and determine which entries should be exposed by the
4855 // navigation API. It is important to calculate this correctly, because blink
4856 // will cancel a same-document history commit if it's not present in the
4857 // entries blink knows about.
4858 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574859 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304860 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254861 bool will_create_new_entry = false;
4862 if (GetPendingEntryIndex() != -1) {
4863 entry_index = GetPendingEntryIndex();
4864 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4865 pending_item_sequence_number = frame_entry->item_sequence_number();
4866 pending_document_sequence_number =
4867 frame_entry->document_sequence_number();
4868 }
4869 } else if (request &&
4870 !NavigationTypeUtils::IsReload(
4871 request->common_params().navigation_type) &&
4872 !NavigationTypeUtils::IsHistory(
4873 request->common_params().navigation_type) &&
4874 !request->common_params().should_replace_current_entry &&
4875 !request->common_params()
4876 .is_history_navigation_in_new_child_frame) {
4877 will_create_new_entry = true;
4878 entry_index = GetLastCommittedEntryIndex() + 1;
4879 // Don't set pending_item_sequence_number or
4880 // pending_document_sequence_number in this case - a new unique isn/dsn will
4881 // be calculated in the renderer later.
4882 } else if (GetLastCommittedEntryIndex() != -1) {
4883 entry_index = GetLastCommittedEntryIndex();
4884 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574885 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304886 pending_document_sequence_number =
4887 frame_entry->document_sequence_number();
4888 }
Nate Chapind1fe3612021-04-16 20:45:574889 }
4890
Domenic Denicolacd30f5f82022-03-16 21:48:014891 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254892 if (entry_index == -1) {
4893 // TODO(rakina): Exit early when there is no last committed entry.
4894 // Remove when InitialNavigationEntry ships.
4895 return entry_arrays;
4896 }
4897
Nate Chapina2c881f52023-11-07 17:02:094898 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014899 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574900 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094901 pending_item_sequence_number, pending_document_sequence_number,
4902 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574903
4904 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094905 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574906 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014907 entry_arrays->forward_entries =
4908 PopulateSingleNavigationApiHistoryEntryVector(
4909 Direction::kForward, entry_index, pending_origin, node,
4910 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094911 pending_document_sequence_number, forwardmost_index);
4912 }
4913
4914 // If the previous entry is within the block of contiguous entries being
4915 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254916 FrameNavigationEntry* previous_entry = nullptr;
4917 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:054918 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4919 .initiator_frame_tree_node_id();
4920 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:254921 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4922 previous_entry = initiator_node->frame_tree()
4923 .controller()
4924 .GetLastCommittedEntry()
4925 ->GetFrameEntry(initiator_node);
4926 }
4927 } else if (GetLastCommittedEntryIndex() != -1 &&
4928 GetLastCommittedEntryIndex() >= backmost_index &&
4929 GetLastCommittedEntryIndex() <= forwardmost_index) {
4930 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4931 }
4932 if (previous_entry) {
4933 url::Origin previous_entry_origin =
4934 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4935 previous_entry->url(),
4936 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:584937 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:254938 // once we can be sure that entries with the same ISN will never be
4939 // cross-origin.
4940 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4941 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4942 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094943 }
Nate Chapind1fe3612021-04-16 20:45:574944 }
Nate Chapinc06cf80a2023-11-18 01:12:254945
Nate Chapin4e657a472022-02-06 03:38:374946 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574947}
4948
Nate Chapinfbfe5af2021-06-10 17:22:084949NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574950NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084951 FrameNavigationEntry* current_entry,
4952 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574953 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084954 if (!target_entry || !target_entry->committed_origin())
4955 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084956 if (!current_entry->committed_origin()->IsSameOriginWith(
4957 *target_entry->committed_origin())) {
4958 return HistoryNavigationAction::kStopLooking;
4959 }
4960
4961 // NOTE: We don't actually care between kSameDocument and
4962 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574963 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084964 return HistoryNavigationAction::kDifferentDocument;
4965 return HistoryNavigationAction::kKeepLooking;
4966}
4967
Domenic Denicolacc094fb2022-03-16 23:40:574968void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204969 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374970 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144971 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574972 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204973 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084974 FrameNavigationEntry* current_entry =
4975 GetLastCommittedEntry()->GetFrameEntry(node);
Nate Chapin0dbc93af2025-03-28 17:02:524976 if (!current_entry || !current_entry->committed_origin()) {
Nate Chapinfbfe5af2021-06-10 17:22:084977 return;
Nate Chapin0dbc93af2025-03-28 17:02:524978 }
Nate Chapinfbfe5af2021-06-10 17:22:084979
Alison Gale47d1537d2024-04-19 21:31:464980 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:134981 // when `navigation.traverseTo()` is called.
4982
Nate Chapinfbfe5af2021-06-10 17:22:084983 // We want to find the nearest matching entry that is contiguously
4984 // same-instance and same-origin. Check back first, then forward.
4985 // TODO(japhet): Link spec here once it exists.
4986 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574987 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084988 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4989 if (result == HistoryNavigationAction::kStopLooking)
4990 break;
4991 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144992 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084993 return;
4994 }
4995 }
4996 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574997 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084998 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4999 if (result == HistoryNavigationAction::kStopLooking)
5000 break;
5001 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:145002 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:085003 return;
5004 }
5005 }
Nate Chapinbf682fa32022-09-26 22:41:205006
5007 // If we fall through to here, a matching NavigationEntry couldn't be found.
5008 // Notify the renderer that the navigation was cancelled.
5009 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
5010 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:085011}
5012
Domenic Denicolacc094fb2022-03-16 23:40:575013bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:305014 network::mojom::ReferrerPolicy referrer_policy) {
5015 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
5016 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
5017}
5018
shivanigithubf405bf0d2021-11-05 17:58:335019bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
5020 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:315021 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:335022 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:545023 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:465024 // The preview mode appears as prerendered page in renderers, and
5025 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:035026 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:515027 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:335028 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:545029}
5030
Julie Jeongeun Kim0e242242022-11-30 10:45:095031void NavigationControllerImpl::DidChangeReferrerPolicy(
5032 FrameTreeNode* node,
5033 network::mojom::ReferrerPolicy referrer_policy) {
5034 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
5035 if (!entry)
5036 return;
5037
5038 // The FrameNavigationEntry may want to change whether to protect its url
5039 // in the navigation API when the referrer policy changes.
5040 entry->set_protect_url_in_navigation_api(
5041 ShouldProtectUrlInNavigationApi(referrer_policy));
5042}
5043
Minoru Chikamune646eba42025-04-14 01:25:035044void NavigationControllerImpl::CheckPotentialNavigationReentrancy() {
Minoru Chikamune13ab4de2025-05-14 21:54:075045 if (can_be_in_navigate_to_pending_entry_) {
Minoru Chikamune646eba42025-04-14 01:25:035046 // This DumpWithoutCrashing is an investigation code for
5047 // https://crbug.com/396998476.
5048 base::debug::DumpWithoutCrashing();
5049 }
5050}
5051
Andrew Verge754c70a2025-04-17 17:19:195052std::unique_ptr<NavigationRequest>
5053NavigationControllerImpl::CreateNavigationRequestForErrorPage(
5054 RenderFrameHostImpl* render_frame_host_impl,
5055 const GURL& url,
5056 const std::string& error_page_html,
5057 bool is_post_commit_error_page) {
5058 // Only active documents can load error pages:
5059 // - If the document is in pending deletion, the browser already committed to
5060 // destroying this RenderFrameHost so ignore loading the error page.
5061 // - If the document is in back-forward cache, it's not allowed to navigate as
5062 // it should remain frozen. Ignore the request and evict the document from
5063 // back-forward cache.
5064 // - If the document is prerendering, it can navigate but when loading error
5065 // pages, cancel prerendering.
5066 if (render_frame_host_impl->IsInactiveAndDisallowActivation(
5067 is_post_commit_error_page
5068 ? DisallowActivationReasonId::kLoadPostCommitErrorPage
5069 : DisallowActivationReasonId::kBrowserInitiatedErrorPage)) {
5070 return nullptr;
5071 }
5072
5073 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
5074
5075 blink::mojom::CommonNavigationParamsPtr common_params =
5076 blink::CreateCommonNavigationParams();
5077 // |url| might be empty, such as when this method is called before
5078 // the frame actually committed (e.g. iframe with "src" set to a
5079 // slow-responding URL). We should rewrite the URL to about:blank in this
5080 // case, as the renderer will only think a page is an error page if it has a
5081 // non-empty unreachable URL.
5082 common_params->url = url.is_empty() ? GURL("about:blank") : url;
5083
5084 // Loading an error page via LoadPostCommitErrorPage() performs a temporary
5085 // replacement of the entire NavigationEntry and swaps it back in later.
5086 // All other error page types should permanently replace the current entry.
5087 if (!is_post_commit_error_page) {
5088 common_params->should_replace_current_entry = true;
5089 }
5090
5091 blink::mojom::CommitNavigationParamsPtr commit_params =
5092 blink::CreateCommitNavigationParams();
5093 commit_params->original_url = common_params->url;
5094
5095 commit_params->navigation_timing->system_entropy_at_navigation_start =
5096 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
5097 node, blink::mojom::SystemEntropy::kNormal);
5098
5099 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
5100 // error pages.
5101 commit_params->frame_policy = node->pending_frame_policy();
5102
5103 std::unique_ptr<NavigationRequest> navigation_request =
5104 NavigationRequest::CreateBrowserInitiated(
5105 node, std::move(common_params), std::move(commit_params),
5106 false /* was_opener_suppressed */, "" /* extra_headers */,
5107 nullptr /* frame_entry */, nullptr /* entry */,
5108 false /* is_form_submission */, nullptr /* navigation_ui_data */,
5109 std::nullopt /* impression */, false /* is_pdf */);
5110 if (is_post_commit_error_page) {
5111 navigation_request->set_browser_initiated_error_navigation_type(
5112 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit);
5113 } else {
5114 navigation_request->set_browser_initiated_error_navigation_type(
5115 NavigationRequest::BrowserInitiatedErrorNavigationType::kRegular);
5116 }
5117 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
5118 navigation_request->set_error_page_html(error_page_html);
5119 return navigation_request;
5120}
5121
[email protected]8ff00d72012-10-23 19:12:215122} // namespace content