blob: a87f8dd78e750d85944f0b27336668624e974c76 [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
Charlie Reis655c8f02025-05-15 01:16:17126// Feature to skip a redundant NavigationRequest creation for bfcache
127// activations, per https://crbug.com/417251428.
128BASE_FEATURE(kSkipExtraBfcacheNavigationRequest,
129 "SkipExtraBfcacheNavigationRequest",
130 base::FEATURE_ENABLED_BY_DEFAULT);
131
[email protected]e9ba4472008-09-14 15:42:43132// Invoked when entries have been pruned, or removed. For example, if the
133// current entries are [google, digg, yahoo], with the current entry google,
134// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47135void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50136 int index,
[email protected]c12bf1a12008-09-17 16:28:49137 int count) {
[email protected]8ff00d72012-10-23 19:12:21138 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50139 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49140 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14141 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43142}
143
[email protected]e9ba4472008-09-14 15:42:43144// Configure all the NavigationEntries in entries for restore. This resets
145// the transition type to reload and makes sure the content state isn't empty.
146void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57147 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48148 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47149 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43150 // Use a transition type of reload so that we don't incorrectly increase
151 // the typed count.
Lei Zhang96031532019-10-10 19:05:47152 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
153 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43154 }
155}
156
[email protected]bf70edce2012-06-20 22:32:22157// Determines whether or not we should be carrying over a user agent override
158// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57159bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22160 return last_entry && last_entry->GetIsOverridingUserAgent();
161}
162
Camille Lamy5193caa2018-10-12 11:59:42163// Determines whether to override user agent for a navigation.
164bool ShouldOverrideUserAgent(
165 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57166 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42167 switch (override_user_agent) {
168 case NavigationController::UA_OVERRIDE_INHERIT:
169 return ShouldKeepOverride(last_committed_entry);
170 case NavigationController::UA_OVERRIDE_TRUE:
171 return true;
172 case NavigationController::UA_OVERRIDE_FALSE:
173 return false;
Camille Lamy5193caa2018-10-12 11:59:42174 }
Peter Boströmfc7ddc182024-10-31 19:37:21175 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42176}
177
Rakina Zata Amni312822d72021-06-04 16:13:37178// Returns true if this navigation should be treated as a reload. For e.g.
Liang Zhao0351d762024-11-13 00:10:07179// clicking on a link which results in a navigation to the last committed URL
180// (but wasn't converted to do a replacement navigation in the renderer), etc.
181// This intentionally excludes navigating to the last committed URL via the
182// address bar, so that the current scroll position is not restored.
Fergal Daly766177d2020-07-07 07:54:04183// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
184// |base_url_for_data_url|, |transition_type| correspond to the new navigation
185// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
186// navigation that committed.
187bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
188 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57189 const GURL& virtual_url,
190 const GURL& base_url_for_data_url,
191 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57192 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37193 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57194 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37195 // Navigations intended to do a replacement shouldn't be converted to do a
196 // reload.
197 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28198 return false;
clamy0a656e42018-02-06 18:18:28199 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45200 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55201 return false;
202
arthursonzogni7a8243682017-12-14 16:41:42203 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28204 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42205 return false;
206
Liang Zhao0351d762024-11-13 00:10:07207 // Same URL navigations from the address bar should only be treated as reloads
208 // if PAGE_TRANSITION_RELOAD is set (not for PAGE_TRANSITION_TYPED or
209 // PAGE_TRANSITION_LINK). In non-address-bar cases, PAGE_TRANSITION_TYPED
210 // and PAGE_TRANSITION_LINK can be treated as reloads.
clamy0a656e42018-02-06 18:18:28211 bool transition_type_can_be_converted = false;
Liang Zhao0351d762024-11-13 00:10:07212 if (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
213 if (ui::PageTransitionCoreTypeIs(transition_type,
214 ui::PAGE_TRANSITION_RELOAD)) {
215 transition_type_can_be_converted = true;
216 }
217 } else {
218 if (ui::PageTransitionCoreTypeIs(transition_type,
219 ui::PAGE_TRANSITION_TYPED) ||
220 ui::PageTransitionCoreTypeIs(transition_type,
221 ui::PAGE_TRANSITION_LINK)) {
222 transition_type_can_be_converted = true;
223 }
ananta3bdd8ae2016-12-22 17:11:55224 }
clamy0a656e42018-02-06 18:18:28225 if (!transition_type_can_be_converted)
226 return false;
227
228 // This check is required for cases like view-source:, etc. Here the URL of
229 // the navigation entry would contain the url of the page, while the virtual
230 // URL contains the full URL including the view-source prefix.
231 if (virtual_url != last_committed_entry->GetVirtualURL())
232 return false;
233
Fergal Daly766177d2020-07-07 07:54:04234 // Check that the URLs match.
235 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
236 // If there's no frame entry then by definition the URLs don't match.
237 if (!frame_entry)
238 return false;
239
240 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28241 return false;
242
243 // This check is required for Android WebView loadDataWithBaseURL. Apps
244 // can pass in anything in the base URL and we need to ensure that these
245 // match before classifying it as a reload.
246 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
247 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
248 return false;
ananta3bdd8ae2016-12-22 17:11:55249 }
250
clamy0a656e42018-02-06 18:18:28251 // Skip entries with SSL errors.
252 if (last_committed_entry->ssl_error())
253 return false;
254
255 // Don't convert to a reload when the last navigation was a POST or the new
256 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04257 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28258 return false;
259
260 return true;
ananta3bdd8ae2016-12-22 17:11:55261}
262
Arthur Sonzognic686e8f2024-01-11 08:36:37263std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12264 const mojom::DidCommitProvisionalLoadParams& params,
265 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32266 // Error pages commit in an opaque origin, yet have the real URL that resulted
267 // in an error as the |params.url|. Since successful reload of an error page
268 // should commit in the correct origin, setting the opaque origin on the
269 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17270 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37271 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32272
Arthur Sonzognic686e8f2024-01-11 08:36:37273 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32274}
275
Alex Moshchuk99242832023-05-22 17:21:44276bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42277 const GURL& virtual_url,
278 const GURL& dest_url) {
279 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44280 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
281 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42282 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
283 << virtual_url.possibly_invalid_spec();
284 return false;
285 }
286
287 // Don't attempt to navigate to non-empty invalid URLs.
288 if (!dest_url.is_valid() && !dest_url.is_empty()) {
289 LOG(WARNING) << "Refusing to load invalid URL: "
290 << dest_url.possibly_invalid_spec();
291 return false;
292 }
293
294 // The renderer will reject IPC messages with URLs longer than
295 // this limit, so don't attempt to navigate with a longer URL.
296 if (dest_url.spec().size() > url::kMaxURLChars) {
297 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
298 << " characters.";
299 return false;
300 }
301
Aaron Colwell33109c592020-04-21 21:31:19302 // Reject renderer debug URLs because they should have been handled before
303 // we get to this point. This check handles renderer debug URLs
304 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
305 // provides defense-in-depth if a renderer debug URL manages to get here via
306 // some other path. We want to reject the navigation here so it doesn't
307 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30308 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19309 LOG(WARNING) << "Refusing to load renderer debug URL: "
310 << dest_url.possibly_invalid_spec();
311 return false;
312 }
313
Alex Moshchuk99242832023-05-22 17:21:44314 // Guests only support navigations to known-safe schemes. This check already
315 // exists in the extensions layer, where it also dispatches proper events to
316 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
317 // for defense-in-depth to ensure that no other places in the codebase
318 // accidentally navigate guests to schemes such as WebUI, which is not
319 // supported. See https://crbug.com/1444221.
320 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
321 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
322 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
323 !dest_url.SchemeIs(url::kAboutScheme)) {
324 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
325 << dest_url.possibly_invalid_spec();
326 return false;
327 }
328 }
329
Camille Lamy5193caa2018-10-12 11:59:42330 return true;
331}
332
Mikel Astizba9cf2fd2017-12-17 10:38:10333// See replaced_navigation_entry_data.h for details: this information is meant
334// to ensure |*output_entry| keeps track of its original URL (landing page in
335// case of server redirects) as it gets replaced (e.g. history.replaceState()),
336// without overwriting it later, for main frames.
337void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57338 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10339 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17340 if (output_entry->GetReplacedEntryData().has_value() ||
341 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10342 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17343 }
Mikel Astizba9cf2fd2017-12-17 10:38:10344
345 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57346 data.first_committed_url = replaced_entry->GetURL();
347 data.first_timestamp = replaced_entry->GetTimestamp();
348 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29349 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10350}
351
Minggang Wangb9f3fa92021-07-01 15:30:31352blink::mojom::NavigationType GetNavigationType(
353 const GURL& old_url,
354 const GURL& new_url,
355 ReloadType reload_type,
356 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52357 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31358 bool has_pending_cross_document_commit,
359 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49360 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13361 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49362 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23363 // Reload navigations
364 switch (reload_type) {
365 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31366 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23367 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31368 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23369 case ReloadType::NONE:
370 break; // Fall through to rest of function.
371 }
372
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08373 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31374 return entry->GetHasPostData()
375 ? blink::mojom::NavigationType::RESTORE_WITH_POST
376 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23377 }
378
danakjb952ef12021-01-14 19:58:49379 const bool can_be_same_document =
380 // A pending cross-document commit means this navigation will not occur in
381 // the current document, as that document would end up being replaced in
382 // the meantime.
383 !has_pending_cross_document_commit &&
384 // If the current document is an error page, we should always treat it as
385 // a different-document navigation so that we'll attempt to load the
386 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49387 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13388 // If the navigation is an embedder-initiated navigation of a fenced
389 // frame root (i.e. enters a fenced frame tree from outside),
390 // same-document navigations should be disabled because we don't want to
391 // allow information to be joined across multiple embedder-initiated
392 // fenced frame navigations (which may contain separate cross-site data).
393 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49394 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
395 // same-document navigations should be disabled because we want to force
396 // the creation of a new browsing context group.
397 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12398
clamyea99ea12018-05-28 13:54:23399 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52400 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12401 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31402 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
403 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23404 }
405 DCHECK(!is_same_document_history_load);
406
407 // A same-document fragment-navigation happens when the only part of the url
408 // that is modified is after the '#' character.
409 //
410 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12411 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23412 //
413 // Note: this check is only valid for navigations that are not history
414 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
415 // history navigation from 'A#foo' to 'A#bar' is not a same-document
416 // navigation, but a different-document one. This is why history navigation
417 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47418 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52419 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12420
421 // The one case where we do the wrong thing here and incorrectly choose
422 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
423 // the renderer is a frameset. All frameset navigations should be
424 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
425 // navigation would do the right thing, as it would send it to the browser and
426 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
427 // into this method). But since we can't tell that case here for browser-
428 // initiated navigations, we have to get the renderer involved. In that case
429 // the navigation would be restarted due to the renderer spending a reply of
430 // mojom::CommitResult::RestartCrossDocument.
431
432 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31433 ? blink::mojom::NavigationType::SAME_DOCUMENT
434 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23435}
436
Camille Lamy5193caa2018-10-12 11:59:42437// Adjusts the original input URL if needed, to get the URL to actually load and
438// the virtual URL, which may differ.
439void RewriteUrlForNavigation(const GURL& original_url,
440 BrowserContext* browser_context,
441 GURL* url_to_load,
442 GURL* virtual_url,
443 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42444 // Allow the browser URL handler to rewrite the URL. This will, for example,
445 // remove "view-source:" from the beginning of the URL to get the URL that
446 // will actually be loaded. This real URL won't be shown to the user, just
447 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31448 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42449 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
450 url_to_load, browser_context, reverse_on_redirect);
451}
452
453#if DCHECK_IS_ON()
454// Helper sanity check function used in debug mode.
455void ValidateRequestMatchesEntry(NavigationRequest* request,
456 NavigationEntryImpl* entry) {
457 if (request->frame_tree_node()->IsMainFrame()) {
458 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
459 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31460 ui::PageTransitionFromInt(request->common_params().transition),
461 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42462 }
Nasko Oskovc36327d2019-01-03 23:23:04463 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42464 entry->should_clear_history_list());
465 DCHECK_EQ(request->common_params().has_user_gesture,
466 entry->has_user_gesture());
467 DCHECK_EQ(request->common_params().base_url_for_data_url,
468 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04469 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42470 entry->GetCanLoadLocalResources());
471 DCHECK_EQ(request->common_params().started_from_context_menu,
472 entry->has_started_from_context_menu());
473
474 FrameNavigationEntry* frame_entry =
475 entry->GetFrameEntry(request->frame_tree_node());
476 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52477 // TODO(https://crbug.com/40467594): This case should be unreachable once
478 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42479 return;
480 }
481
Camille Lamy5193caa2018-10-12 11:59:42482 DCHECK_EQ(request->common_params().method, frame_entry->method());
483
Nasko Oskovc36327d2019-01-03 23:23:04484 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42485 if (redirect_size == frame_entry->redirect_chain().size()) {
486 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04487 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42488 frame_entry->redirect_chain()[i]);
489 }
490 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21491 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42492 }
493}
494#endif // DCHECK_IS_ON()
495
Dave Tapuska8bfd84c2019-03-26 20:47:16496// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20497// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16498bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20499 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16500 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20501 DCHECK(sandboxed_initiator_rfh);
502 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
503 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16504 for (auto& item : navigations) {
505 bool within_subtree = false;
506 // Check whether this NavigationRequest affects a frame within the
507 // sandboxed frame's subtree by walking up the tree looking for the
508 // sandboxed frame.
509 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03510 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20511 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16512 within_subtree = true;
513 break;
514 }
515 }
516 if (!within_subtree)
517 return false;
518 }
519 return true;
520}
521
William Liu122754942024-01-18 22:34:39522// Used for "Navigation.SessionHistoryCount" histogram.
523enum class HistoryNavTypeForHistogram {
524 // A same-doc or cross-doc navigation of the main frame. We can only have one
525 // main frame request per `NavigationController::GoToIndex()`.
526 kMainFrame = 0,
527 // `NavigationController::GoToIndex()` creates one main frame request and
528 // one or more subframe requests.
529 kMainFrameAndSubframe,
530 // `NavigationController::GoToIndex()` creates one or more subframe requests.
531 kSubframe,
532 // Used for histogram boundary.
533 kCount
534};
535
536void CountRequests(
537 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
538 int& mutable_main_frame_cnt,
539 int& mutable_subframe_cnt) {
540 for (const auto& req : requests) {
541 if (req->IsInPrimaryMainFrame()) {
542 // We can only have one main frame navigation at a time.
543 CHECK_EQ(mutable_main_frame_cnt, 0);
544 ++mutable_main_frame_cnt;
545 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
546 ++mutable_subframe_cnt;
547 }
548 }
549}
550
551// Record the number of different types of navigations as histograms. See
552// `HistoryNavTypeForHistogram` for the types.
553void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
554 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
555 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
556 // We must have one request.
557 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
558
559 int main_frame_cnt = 0;
560 int subframe_cnt = 0;
561 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
562 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
563
564 std::optional<HistoryNavTypeForHistogram> history_nav_type;
565 if (main_frame_cnt > 0) {
566 if (subframe_cnt == 0) {
567 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
568 } else {
569 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
570 }
571 } else if (subframe_cnt > 0) {
572 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
573 }
574 if (history_nav_type.has_value()) {
575 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
576 history_nav_type.value(),
577 HistoryNavTypeForHistogram::kCount);
578 }
579}
580
[email protected]e9ba4472008-09-14 15:42:43581} // namespace
582
arthursonzogni66f711c2019-10-08 14:40:36583// NavigationControllerImpl::PendingEntryRef------------------------------------
584
585NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
586 base::WeakPtr<NavigationControllerImpl> controller)
587 : controller_(controller) {}
588
589NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
590 if (!controller_) // Can be null with interstitials.
591 return;
592
593 controller_->PendingEntryRefDeleted(this);
594}
595
Charlie Reisd3e4fef2025-05-20 02:04:17596// NavigationControllerImpl::ScopedPendingEntryReentrancyGuard------------------
597
598NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
599 ScopedPendingEntryReentrancyGuard(
600 base::SafeRef<NavigationControllerImpl> controller)
601 : controller_(controller) {
602 // Navigations that involve pending entries do not support re-entrancy.
603 // Encountering this CHECK failure means the caller is attempting to start
604 // another navigation while a navigation to an existing pending entry is on
605 // the stack. In most cases, the new navigation should be done from a posted
606 // task instead. See http://crbug.com/40353566 for context.
607 CHECK(!controller->in_navigate_to_pending_entry_);
608
609 controller->in_navigate_to_pending_entry_ = true;
610 controller->CheckPotentialNavigationReentrancy();
611
612 // It must not be possible to delete the pending NavigationEntry while
613 // navigating to it. Grab a reference to delay potential deletion until
614 // this scoped object is deleted at the end of the relevant function call.
615 pending_entry_ref_ = controller->ReferencePendingEntry();
616}
617
618NavigationControllerImpl::ScopedPendingEntryReentrancyGuard::
619 ~ScopedPendingEntryReentrancyGuard() {
620 controller_->in_navigate_to_pending_entry_ = false;
621}
622
[email protected]d202a7c2012-01-04 07:53:47623// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29624
[email protected]23a918b2014-07-15 09:51:36625const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23626
[email protected]765b35502008-08-21 00:51:20627// static
[email protected]d202a7c2012-01-04 07:53:47628size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23629 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20630
[email protected]e6fec472013-05-14 05:29:02631// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20632// when testing.
633static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29634
[email protected]71fde352011-12-29 03:29:56635// static
dcheng9bfa5162016-04-09 01:00:57636std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
637 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10638 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37639 std::optional<url::Origin> initiator_origin,
640 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10641 ui::PageTransition transition,
642 bool is_renderer_initiated,
643 const std::string& extra_headers,
644 BrowserContext* browser_context,
645 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
646 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21647 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37648 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32649 is_renderer_initiated, extra_headers, browser_context,
650 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10651}
652
653// static
654std::unique_ptr<NavigationEntryImpl>
655NavigationControllerImpl::CreateNavigationEntry(
656 const GURL& url,
657 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37658 std::optional<url::Origin> initiator_origin,
659 std::optional<GURL> initiator_base_url,
660 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57661 ui::PageTransition transition,
662 bool is_renderer_initiated,
663 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09664 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17665 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
666 bool rewrite_virtual_urls) {
667 GURL url_to_load = url;
668 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56669 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17670 if (rewrite_virtual_urls) {
671 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
672 &reverse_on_redirect);
673 }
Lukasz Anforowicz641234d52019-11-07 21:07:10674 // Let the NTP override the navigation params and pretend that this is a
675 // browser-initiated, bookmark-like navigation.
676 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32677 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21678 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10679
Patrick Monettef507e982019-06-19 20:18:06680 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28681 nullptr, // The site instance for tabs is sent on navigation
682 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21683 url_to_load, referrer, initiator_origin, initiator_base_url,
684 std::u16string(), transition, is_renderer_initiated,
685 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17686 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42687 entry->SetVirtualURL(virtual_url);
688 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56689 entry->set_update_virtual_url_with_url(reverse_on_redirect);
690 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06691 return entry;
[email protected]71fde352011-12-29 03:29:56692}
693
[email protected]cdcb1dee2012-01-04 00:46:20694// static
695void NavigationController::DisablePromptOnRepost() {
696 g_check_for_repost = false;
697}
698
[email protected]c5b88d82012-10-06 17:03:33699base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
700 base::Time t) {
701 // If |t| is between the water marks, we're in a run of duplicates
702 // or just getting out of it, so increase the high-water mark to get
703 // a time that probably hasn't been used before and return it.
704 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35705 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33706 return high_water_mark_;
707 }
708
709 // Otherwise, we're clear of the last duplicate run, so reset the
710 // water marks.
711 low_water_mark_ = high_water_mark_ = t;
712 return t;
713}
714
ckitagawa0faa5e42020-06-17 17:30:54715NavigationControllerImpl::ScopedShowRepostDialogForTesting::
716 ScopedShowRepostDialogForTesting()
717 : was_disallowed_(g_check_for_repost) {
718 g_check_for_repost = true;
719}
720
721NavigationControllerImpl::ScopedShowRepostDialogForTesting::
722 ~ScopedShowRepostDialogForTesting() {
723 g_check_for_repost = was_disallowed_;
724}
725
Nate Chapin9eb16be72022-09-23 22:54:31726NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
727 base::SafeRef<NavigationControllerImpl> controller)
728 : controller_(controller) {
729 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
730 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
731 frame_tree_node_id_to_keys_.insert(
732 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
733 if (auto* frame_entry = frame_tree_node->current_frame_host()
734 ->last_committed_frame_entry()) {
735 frame_tree_node_id_to_doc_seq_nos_.insert(
736 {frame_tree_node->frame_tree_node_id(),
737 frame_entry->document_sequence_number()});
738 }
739 }
740 PopulateKeySet(Direction::kBack);
741 PopulateKeySet(Direction::kForward);
742}
743
744void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
745 Direction direction) {
746 // Keep track of which FrameTreeNodes may still have relevant API keys in
747 // additional FrameNavigationEntries.
748 std::set<FrameTreeNode*> nodes_to_process;
749 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
750 nodes_to_process.insert(node);
751 }
752
753 const int offset = direction == Direction::kForward ? 1 : -1;
754 const int start = direction == Direction::kForward
755 ? controller_->GetLastCommittedEntryIndex()
756 : controller_->GetLastCommittedEntryIndex() - 1;
757 for (int i = start;
758 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
759 i += offset) {
760 std::set<FrameTreeNode*> nodes_to_continue_processing;
761
762 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
763 entry->ForEachFrameEntry([this, &nodes_to_process,
764 &nodes_to_continue_processing,
765 &entry](FrameNavigationEntry* frame_entry) {
766 // Find the |node| that matches |frame_entry|, if any.
767 FrameTreeNode* node = nullptr;
768 if (frame_entry == entry->root_node()->frame_entry) {
769 node = controller_->frame_tree().root();
770 } else {
771 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
772 if (it == names_to_nodes_.end())
773 return;
774 node = it->second;
775 }
776
777 // Skip this node if a previous step determine there are no longer
778 // relevant navigation API keys in this direction.
779 if (nodes_to_process.find(node) == nodes_to_process.end())
780 return;
781
782 // Stop processing |node| if we reach a point where it's cross-origin.
783 // See also PopulateSingleNavigationApiHistoryEntryVector().
784 url::Origin frame_entry_origin =
785 frame_entry->committed_origin().value_or(url::Origin::Resolve(
786 frame_entry->url(),
787 frame_entry->initiator_origin().value_or(url::Origin())));
788 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
789 return;
790
791 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
792 frame_entry->navigation_api_key());
793 // Mark |node| as needing more processing for the next entry.
794 nodes_to_continue_processing.insert(node);
795
796 // Check whether |node| went cross-document. If so, its children are
797 // no longer the same conceptual iframe as the current one, and
798 // should no longer be processed. This check is intentionally done
799 // after processing the current |node|, which may still have relevant
800 // discarded API keys.
801 if (frame_entry->document_sequence_number() !=
802 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50803 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31804 nodes_to_process.erase(descendant);
805 }
806 });
807
808 nodes_to_process.swap(nodes_to_continue_processing);
809 }
810}
811
812NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
813 std::set<std::string> all_keys;
814 // Find all remaining navigation API keys after some entries have been
815 // removed.
816 for (auto& entry : controller_->entries_) {
817 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
818 all_keys.insert(frame_entry->navigation_api_key());
819 });
820 }
821
822 // Notify each frame in the renderer of any disposed navigation API keys.
823 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
824 std::vector<std::string> disposed_keys;
825 for (const auto& key : id_to_keys.second) {
826 if (all_keys.find(key) == all_keys.end())
827 disposed_keys.push_back(key);
828 }
829 if (disposed_keys.empty())
830 continue;
831
832 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
833 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
834 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
835 }
836}
837
[email protected]d202a7c2012-01-04 07:53:47838NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00839 BrowserContext* browser_context,
840 FrameTree& frame_tree,
841 NavigationControllerDelegate* delegate)
842 : frame_tree_(frame_tree),
843 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57844 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22845 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37846 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
847 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37848 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29849}
850
[email protected]d202a7c2012-01-04 07:53:47851NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00852 // The NavigationControllerImpl might be called inside its delegate
853 // destructor. Calling it is not valid anymore.
854 delegate_ = nullptr;
855 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29856}
857
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57858BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55859 return browser_context_;
860}
861
[email protected]d202a7c2012-01-04 07:53:47862void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30863 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36864 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57865 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47866 // Note that it's possible for `entries_` to contain multiple entries at this
867 // point, as Restore() might be called on a NavigationController that is
868 // already used (e.g. due to WebView's restoreState() API), not only for fresh
869 // NavigationControllers. These entries are not cleared to preserve legacy
870 // behavior and also because `pending_entry_` might point to one of the
871 // pre-existing entries. An exception for this is when `entries_` contains
872 // only the initial NavigationEntry, which must be removed.
873
874 // Do not proceed if selected_navigation will be out of bounds for the updated
875 // entries_ list, since it will be assigned to last_committed_entry_index_ and
876 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58877 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47878 // is empty, since there should be no work to do (rather than marking the
879 // existing entries as needing reload). Also consider returning early if the
880 // selected index is -1, which represents a no-committed-entry state.
881 if (selected_navigation < -1 ||
882 selected_navigation >=
883 base::checked_cast<int>(entries->size() + entries_.size())) {
884 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24885 }
Charlie Reis23c26da2022-01-29 00:57:47886
Rakina Zata Amni46087a12022-11-11 08:28:38887 // There will always be at least one entry (new NavigationControllers will
888 // have the initial NavigationEntry).
889 if (selected_navigation == -1)
890 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47891
Rakina Zata Amni46087a12022-11-11 08:28:38892 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
893 // If we are on the initial NavigationEntry, it must be the only entry in
894 // the list. Since it's impossible to do a history navigation to the
895 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
896 // `pending_entry` might be set for a new non-history navigation).
897 // Note that we should not clear `entries_` if `entries` is empty (when
898 // InitialNavigationEntry mode is enabled), since that would leave us
899 // without any NavigationEntry.
900 CHECK_EQ(1, GetEntryCount());
901 CHECK_EQ(-1, pending_entry_index_);
902 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47903 }
[email protected]ce3fa3c2009-04-20 19:55:57904
[email protected]ce3fa3c2009-04-20 19:55:57905 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44906 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03907 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47908 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43909 if (entry->GetURL().is_empty()) {
910 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01911 // persisting the initial NavigationEntry [which is no longer possible but
912 // some old persisted sessions might still contain it] or when the
913 // serializer failed to write the URL because it's too long). Trying to
914 // restore and navigate to an entry with an empty URL will result in
915 // crashes, so change the URL to about:blank. See also
916 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43917 entry->SetURL(GURL(url::kAboutBlankURL));
918 }
dcheng36b6aec92015-12-26 06:16:36919 entries_.push_back(
920 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47921 }
avif16f85a72015-11-13 18:25:03922
923 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
924 // cleared out safely.
925 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57926
927 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36928 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57929}
930
toyoshim6142d96f2016-12-19 09:07:25931void NavigationControllerImpl::Reload(ReloadType reload_type,
932 bool check_for_repost) {
Charlie Reisf4d51f402025-05-23 18:00:49933 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:03934 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
935 (int)reload_type);
936 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
937 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28938 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28939 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32940 int current_index = -1;
941
Carlos IL42b416592019-10-07 23:10:36942 if (entry_replaced_by_post_commit_error_) {
943 // If there is an entry that was replaced by a currently active post-commit
944 // error navigation, this can't be the initial navigation.
945 DCHECK(!IsInitialNavigation());
946 // If the current entry is a post commit error, we reload the entry it
947 // replaced instead. We leave the error entry in place until a commit
948 // replaces it, but the pending entry points to the original entry in the
949 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
950 // case that pending_entry_ != entries_[pending_entry_index_].
951 entry = entry_replaced_by_post_commit_error_.get();
952 current_index = GetCurrentEntryIndex();
953 } else if (IsInitialNavigation() && pending_entry_) {
954 // If we are reloading the initial navigation, just use the current
955 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32956 entry = pending_entry_;
957 // The pending entry might be in entries_ (e.g., after a Clone), so we
958 // should also update the current_index.
959 current_index = pending_entry_index_;
960 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00961 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32962 current_index = GetCurrentEntryIndex();
963 if (current_index != -1) {
creis3da03872015-02-20 21:12:32964 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32965 }
[email protected]979a4bc2013-04-24 01:27:15966 }
[email protected]241db352013-04-22 18:04:05967
[email protected]59167c22013-06-03 18:07:32968 // If we are no where, then we can't reload. TODO(darin): We should add a
969 // CanReload method.
970 if (!entry)
971 return;
972
Rakina Zata Amnif297a802022-01-18 03:53:43973 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
974 // We should never navigate to an existing initial NavigationEntry that is
975 // the initial NavigationEntry for the initial empty document that hasn't
976 // been overridden by the synchronous about:blank commit, to preserve
977 // legacy behavior where trying to reload when the main frame is on the
978 // initial empty document won't result in a navigation. See also
979 // https://crbug.com/1277414.
980 return;
981 }
982
Aran Gilman37d11632019-10-08 23:07:15983 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30984 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07985 // they really want to do this. If they do, the dialog will call us back
986 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57987 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02988
[email protected]106a0812010-03-18 00:15:12989 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57990 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47991 return;
initial.commit09911bf2008-07-26 23:55:29992 }
Lei Zhang96031532019-10-10 19:05:47993
Wang Huia25efabc2022-09-24 17:27:22994 // Set ReloadType for |entry|.
995 entry->set_reload_type(reload_type);
996
Lei Zhang96031532019-10-10 19:05:47997 if (!IsInitialNavigation())
998 DiscardNonCommittedEntries();
999
1000 pending_entry_ = entry;
1001 pending_entry_index_ = current_index;
1002 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
1003
Nate Chapin45f620582021-09-30 17:45:431004 // location.reload() goes through BeginNavigation, so all reloads triggered
1005 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:131006 NavigateToExistingPendingEntry(
1007 reload_type,
1008 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371009 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491010 /*navigation_api_key=*/nullptr, actual_navigation_start);
initial.commit09911bf2008-07-26 23:55:291011}
1012
[email protected]d202a7c2012-01-04 07:53:471013void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:481014 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121015}
1016
[email protected]d202a7c2012-01-04 07:53:471017void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:491018 // If the pending reload type has been cleared by another navigation
1019 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:481020 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:491021 return;
[email protected]106a0812010-03-18 00:15:121022 }
Wang Hui96ab1012022-10-11 02:05:491023 Reload(pending_reload_, false);
1024 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:121025}
1026
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571027bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:091028 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:111029}
1030
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571031bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:381032 // Check that we're on the initial NavigationEntry and that this is not a
1033 // cloned tab.
1034 return IsInitialNavigation() && GetEntryCount() == 1 &&
1035 GetLastCommittedEntry()->IsInitialEntry() &&
1036 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401037}
1038
Aran Gilman37d11632019-10-08 23:07:151039NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1040 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581041 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031042 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581043}
1044
Adithya Srinivasan9b0c99c2021-08-10 15:19:451045NavigationEntryImpl*
1046NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1047 int nav_entry_id) const {
1048 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1049 if (entry)
1050 return entry;
1051 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521052 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451053 : nullptr;
1054}
1055
W. James MacLeanc07dc41b2022-07-25 18:52:161056void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571057 const url::Origin& origin) {
1058 for (int i = 0; i < GetEntryCount(); i++) {
1059 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161060 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571061 }
1062 if (entry_replaced_by_post_commit_error_) {
1063 // It's possible we could come back to this entry if the error
1064 // page/interstitial goes away.
1065 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161066 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571067 }
W. James MacLean1c40862c2020-04-27 21:05:571068}
1069
avi25764702015-06-23 15:43:371070void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571071 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001072 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371073 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271074 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201075}
1076
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571077NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471078 if (pending_entry_)
1079 return pending_entry_;
1080 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201081}
1082
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571083NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321084 // The pending entry is safe to return for new (non-history), browser-
1085 // initiated navigations. Most renderer-initiated navigations should not
1086 // show the pending entry, to prevent URL spoof attacks.
1087 //
1088 // We make an exception for renderer-initiated navigations in new tabs, as
1089 // long as no other page has tried to access the initial empty document in
1090 // the new tab. If another page modifies this blank page, a URL spoof is
1091 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321092 bool safe_to_show_pending =
1093 pending_entry_ &&
1094 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091095 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321096 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461097 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321098
1099 // Also allow showing the pending entry for history navigations in a new tab,
1100 // such as Ctrl+Back. In this case, no existing page is visible and no one
1101 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151102 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1103 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321104 safe_to_show_pending = true;
1105
1106 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191107 return pending_entry_;
1108 return GetLastCommittedEntry();
1109}
1110
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571111int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201112 if (pending_entry_index_ != -1)
1113 return pending_entry_index_;
1114 return last_committed_entry_index_;
1115}
1116
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571117NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381118 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031119 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201120}
1121
Elad Alon32044f532025-03-04 22:16:031122const NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry()
1123 const {
1124 CHECK_NE(last_committed_entry_index_, -1);
1125 return entries_[last_committed_entry_index_].get();
1126}
1127
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571128bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351129 const std::string& mime_type = frame_tree_->root()
1130 ->current_frame_host()
1131 ->GetPage()
1132 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531133 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1134 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271135 NavigationEntry* visible_entry = GetVisibleEntry();
1136 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391137 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161138}
1139
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571140int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271141 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451142 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271143 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551144 return last_committed_entry_index_;
1145}
1146
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571147int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451148 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291149 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551150 return static_cast<int>(entries_.size());
1151}
1152
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571153NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371154 if (index < 0 || index >= GetEntryCount())
1155 return nullptr;
1156
avif16f85a72015-11-13 18:25:031157 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251158}
1159
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571160NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471161 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201162}
1163
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571164int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461165 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031166}
1167
Arthur Sonzognic686e8f2024-01-11 08:36:371168std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031169 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591170 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1171 return index;
1172 }
Shivani Sharma298d12852019-01-22 20:04:031173 }
Arthur Sonzognic686e8f2024-01-11 08:36:371174 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591175}
1176
1177bool NavigationControllerImpl::CanGoBack() {
1178 return GetIndexForGoBack().has_value();
1179}
1180
Arthur Sonzognic686e8f2024-01-11 08:36:371181std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591182 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1183 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1184 return index;
1185 }
1186 }
Arthur Sonzognic686e8f2024-01-11 08:36:371187 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201188}
1189
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571190bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591191 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201192}
1193
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571194bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031195 int index = GetIndexForOffset(offset);
1196 return index >= 0 && index < GetEntryCount();
1197}
1198
Xiaohan Wang7f8052e02022-01-14 18:44:281199#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151200bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151201 if (offset == 0)
1202 return true;
1203 int increment = offset > 0 ? 1 : -1;
1204 int non_skippable_entries = 0;
1205 for (int index = GetIndexForOffset(increment);
1206 index >= 0 && index < GetEntryCount(); index += increment) {
1207 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1208 non_skippable_entries++;
1209
1210 if (non_skippable_entries == std::abs(offset))
1211 return true;
1212 }
1213 return false;
1214}
1215#endif
1216
David Bokanb8e0df02025-05-14 22:03:481217NavigationController::WeakNavigationHandleVector
1218NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371219 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061220
Kevin McNeeedc481c2023-04-27 22:30:581221 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211222
David Bokanb8e0df02025-05-14 22:03:481223 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201224}
1225
David Bokanb8e0df02025-05-14 22:03:481226NavigationController::WeakNavigationHandleVector
1227NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161228 // Note that at least one entry (the last one) will be non-skippable since
1229 // entries are marked skippable only when they add another entry because of
1230 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371231 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591232
Kevin McNeeedc481c2023-04-27 22:30:581233 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591234
David Bokanb8e0df02025-05-14 22:03:481235 return GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201236}
1237
David Bokanb8e0df02025-05-14 22:03:481238NavigationController::WeakNavigationHandleVector
1239NavigationControllerImpl::GoToIndex(int index) {
1240 std::vector<base::WeakPtr<NavigationRequest>> requests =
1241 GoToIndex(index, /*initiator_rfh=*/nullptr,
1242 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491243 /*navigation_api_key=*/nullptr,
1244 /*actual_navigation_start=*/base::TimeTicks::Now());
David Bokanb8e0df02025-05-14 22:03:481245 std::vector<base::WeakPtr<NavigationHandle>> handles;
1246 std::ranges::move(requests, std::back_inserter(handles));
1247 return handles;
Dave Tapuska8bfd84c2019-03-26 20:47:161248}
1249
William Liu62ae26c2024-08-08 14:28:161250std::vector<base::WeakPtr<NavigationRequest>>
1251NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201252 int index,
1253 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371254 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131255 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491256 const std::string* navigation_api_key,
1257 base::TimeTicks actual_navigation_start) {
sunjian30574a62017-03-21 21:39:441258 TRACE_EVENT0("browser,navigation,benchmark",
1259 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501260 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1261 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1262 entries_.size());
1263 // Indices should have have been validated by the caller.
1264 CHECK_GE(index, 0);
1265 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201266
Rakina Zata Amnif297a802022-01-18 03:53:431267 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1268 // We should never navigate to an existing initial NavigationEntry that is
1269 // the initial NavigationEntry for the initial empty document that hasn't
1270 // been overridden by the synchronous about:blank commit, to preserve
1271 // legacy behavior where trying to reload when the main frame is on the
1272 // initial empty document won't result in a navigation. See also
1273 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161274 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431275 }
1276
[email protected]cbab76d2008-10-13 22:42:471277 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201278
arthursonzogni5c4c202d2017-04-25 23:41:271279 DCHECK_EQ(nullptr, pending_entry_);
1280 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431281
arthursonzogni5c4c202d2017-04-25 23:41:271282 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201283 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271284 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1285 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Charlie Reisf4d51f402025-05-23 18:00:491286 return NavigateToExistingPendingEntry(
1287 ReloadType::NONE, initiator_rfh, soft_navigation_heuristics_task_id,
1288 navigation_api_key, actual_navigation_start);
[email protected]765b35502008-08-21 00:51:201289}
1290
[email protected]d202a7c2012-01-04 07:53:471291void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121292 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031293 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201294 return;
1295
[email protected]9ba14052012-06-22 23:50:031296 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201297}
1298
Nate Chapinbf682fa32022-09-26 22:41:201299void NavigationControllerImpl::GoToOffsetFromRenderer(
1300 int offset,
Yoav Weiss8c573952022-11-17 17:35:131301 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371302 std::optional<blink::scheduler::TaskAttributionId>
Charlie Reisf4d51f402025-05-23 18:00:491303 soft_navigation_heuristics_task_id,
1304 base::TimeTicks actual_navigation_start) {
Nate Chapinbb74c5a52023-07-21 23:13:351305 // Note: This is actually reached in unit tests.
1306 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431307 return;
1308
Nate Chapinbf682fa32022-09-26 22:41:201309 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131310 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:491311 /*navigation_api_key=*/nullptr, actual_navigation_start);
Nate Chapin45f620582021-09-30 17:45:431312}
1313
William Liu62ae26c2024-08-08 14:28:161314std::vector<base::WeakPtr<NavigationRequest>>
1315NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271316 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1317 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:491318 /*navigation_api_key=*/nullptr,
1319 /*actual_navigation_start=*/base::TimeTicks::Now());
William Liuec04e382024-05-23 18:03:271320}
1321
Xiaohan Wang7f8052e02022-01-14 18:44:281322#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151323void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1324 // Note: This is actually reached in unit tests.
1325 if (!CanGoToOffsetWithSkipping(offset))
1326 return;
1327
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421328 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151329 GoToIndex(GetIndexForOffset(offset));
1330 return;
1331 }
1332 int increment = offset > 0 ? 1 : -1;
1333 // Find the offset without counting skippable entries.
1334 int target_index = GetIndexForOffset(increment);
1335 int non_skippable_entries = 0;
1336 for (int index = target_index; index >= 0 && index < GetEntryCount();
1337 index += increment) {
1338 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1339 non_skippable_entries++;
1340
1341 if (non_skippable_entries == std::abs(offset)) {
1342 target_index = index;
1343 break;
1344 }
1345 }
1346
1347 GoToIndex(target_index);
1348}
1349#endif
1350
[email protected]41374f12013-07-24 02:49:281351bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151352 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281353 return false;
[email protected]6a13a6c2011-12-20 21:47:121354
[email protected]43032342011-03-21 14:10:311355 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281356 return true;
[email protected]cbab76d2008-10-13 22:42:471357}
1358
Michael Thiessen9b14d512019-09-23 21:19:471359void NavigationControllerImpl::PruneForwardEntries() {
1360 DiscardNonCommittedEntries();
1361 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471362 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471363 if (num_removed <= 0)
1364 return;
Nate Chapin9eb16be72022-09-23 22:54:311365 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471366 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1367 NotifyPrunedEntries(this, remove_start_index /* start index */,
1368 num_removed /* count */);
1369}
1370
Aran Gilman37d11632019-10-08 23:07:151371void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1372 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321373 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311374 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511375 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1376 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321377 }
1378}
1379
Harkiran Bolariaba823e42021-05-21 18:30:361380base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1381 const GURL& url,
1382 const Referrer& referrer,
1383 ui::PageTransition transition,
1384 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471385 LoadURLParams params(url);
1386 params.referrer = referrer;
1387 params.transition_type = transition;
1388 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361389 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471390}
1391
Harkiran Bolariaba823e42021-05-21 18:30:361392base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1393 const LoadURLParams& params) {
Charlie Reisf4d51f402025-05-23 18:00:491394 // For now, treat this as the actual navigation start time, even though a fair
1395 // amount of work is done in the browser process between the various ways to
1396 // start a navigation and reaching here (e.g., sending OpenURLParams through
1397 // the embedder and converting them to LoadURLParams). Note that this may be
1398 // used for some renderer-initiated navigations that go through
1399 // RenderFrameHostImpl::OpenURL as well.
1400 // TODO(crbug.com/385170155): Consider whether tracking this earlier work with
1401 // an earlier start time is worthwhile for metrics.
1402 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
1403
Lukasz Anforowicz435bcb582019-07-12 20:50:061404 if (params.is_renderer_initiated)
1405 DCHECK(params.initiator_origin.has_value());
1406
naskob8744d22014-08-28 17:07:431407 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151408 "NavigationControllerImpl::LoadURLWithParams", "url",
1409 params.url.possibly_invalid_spec());
Emmanuel Arias Soto9e159652025-05-16 07:53:551410
1411 if (IsDebugURL(params.url)) {
1412 // Browser-debug URLs won't go through NavigationThrottles so we have to
1413 // check them explicitly. See crbug.com/40605746.
1414 ContentBrowserClient* client = GetContentClient()->browser();
1415 if (client->ShouldBlockRendererDebugURL(
1416 params.url, browser_context_,
1417 GetTargetFrameTreeNodeForNavigation(params)
1418 ->current_frame_host())) {
1419 DiscardPendingEntry(false);
1420 return nullptr;
1421 }
1422 HandleDebugURL(params.url, params.transition_type,
1423 client->IsExplicitNavigation(params.transition_type));
[email protected]47752982014-07-29 08:01:431424 // If Telemetry is running, allow the URL load to proceed as if it's
1425 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491426 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181427 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361428 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181429 }
[email protected]47752982014-07-29 08:01:431430 }
[email protected]8bf1048012012-02-08 01:22:181431
[email protected]cf002332012-08-14 19:17:471432 // Checks based on params.load_type.
1433 switch (params.load_type) {
1434 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431435 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541436#if BUILDFLAG(IS_ANDROID)
1437 case LOAD_TYPE_PDF_ANDROID:
1438#endif
[email protected]cf002332012-08-14 19:17:471439 break;
1440 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261441 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211442 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471443 }
1444 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461445 }
[email protected]e47ae9472011-10-13 19:48:341446
[email protected]e47ae9472011-10-13 19:48:341447 // The user initiated a load, we don't need to reload anymore.
1448 needs_reload_ = false;
1449
Charlie Reisf4d51f402025-05-23 18:00:491450 return NavigateWithoutEntry(params, actual_navigation_start);
[email protected]132e281a2012-07-31 18:32:441451}
1452
Charlie Reis4c53a962023-06-21 23:17:531453void NavigationControllerImpl::LoadOriginalRequestURL() {
1454 // If the original request URL is not valid, matches the current URL, or
1455 // involves POST data, then simply reload. The POST check avoids issues with
1456 // sending data to the wrong page.
1457 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1458 const GURL& original_request_url =
1459 GetLastCommittedEntry()->GetOriginalRequestURL();
1460 if (!original_request_url.is_valid() ||
1461 original_request_url == last_committed_url ||
1462 GetLastCommittedEntry()->GetHasPostData()) {
1463 Reload(ReloadType::NORMAL, true);
1464 return;
1465 }
1466
1467 // Otherwise, attempt to load the original request URL without any of the
1468 // other data from the current NavigationEntry, replacing the current entry.
1469 // Loading the original URL is useful in cases such as modifying the user
1470 // agent.
1471 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1472 std::make_unique<NavigationController::LoadURLParams>(
1473 original_request_url);
1474 load_params->should_replace_current_entry = true;
1475 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1476 LoadURLWithParams(*load_params.get());
1477}
1478
Mohamed Abdelhalim833de902019-09-16 17:41:451479bool NavigationControllerImpl::PendingEntryMatchesRequest(
1480 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191481 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451482 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191483}
1484
[email protected]d202a7c2012-01-04 07:53:471485bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321486 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071487 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331488 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441489 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251490 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561491 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131492 NavigationRequest* navigation_request) {
1493 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331494
1495 // Note: validation checks and renderer kills due to invalid commit messages
1496 // must happen before getting here, in
1497 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1498 // effects of the navigation have already occurred.
1499
[email protected]cd2e15742013-03-08 04:08:311500 is_initial_navigation_ = false;
1501
Wang Hui96ab1012022-10-11 02:05:491502 // Any pending request to repost a form submission is no longer valid, since a
1503 // different NavigationEntry is committing.
1504 pending_reload_ = ReloadType::NONE;
1505
[email protected]0e8db942008-09-24 21:21:481506 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431507 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451508 if (entry_replaced_by_post_commit_error_) {
1509 // Same document navigation events with a post-commit error should already
1510 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1511 // reaching here.
1512 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331513
Xinghui Lub9e86a352024-05-17 16:29:421514 if (pending_entry_) {
1515 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1516 // `pending_entry_` isn't pointing to the last committed entry.
1517 // Instead, all reload approaches (e.g., in `Reload` and
1518 // `LoadIfNecessary`) should attempt to load the
1519 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1520 // entry itself.
1521 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1522 << "Incorrectly reloading the post commit error page entry.";
1523 }
Xinghui Lue4e50be2024-05-15 21:46:001524
Rakina Zata Amnie2d31312022-11-18 03:38:451525 // Any commit while a post-commit error page is showing should put the
1526 // original entry back, replacing the error page's entry. This includes
1527 // reloads, where the original entry was used as the pending entry and
1528 // should now be at the correct index at commit time.
1529 entries_[last_committed_entry_index_] =
1530 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481531 }
Rakina Zata Amnie2d31312022-11-18 03:38:451532 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1533 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001534 // Must honor user agent overrides in the |navigation_request|, such as
1535 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1536 // result, besides comparing |pending_entry_|'s user agent against
1537 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1538 // agent against LastCommittedEntry's.
1539 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541540 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1541 (PendingEntryMatchesRequest(navigation_request) &&
1542 pending_entry_->GetIsOverridingUserAgent() !=
1543 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001544 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451545 }
[email protected]ecd9d8702008-08-28 22:10:171546
Dave Tapuskaa2ab4f252021-07-08 21:31:281547 bool is_main_frame_navigation = !rfh->GetParent();
1548
Alexander Timind2f2e4f22019-04-02 20:04:531549 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1550 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281551 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141552 // BackForwardCacheMetrics to be associated with the new navigation's
1553 // NavigationEntry, by either creating a new object or reusing the previous
1554 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281555 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211556 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141557 back_forward_cache_metrics = BackForwardCacheMetrics::
1558 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281559 GetLastCommittedEntry(), is_main_frame_navigation,
1560 params.document_sequence_number);
1561 }
Yuzu Saijo29f96ca92022-12-08 04:54:121562
Alexander Timind2f2e4f22019-04-02 20:04:531563 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281564 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451565 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1566 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531567 }
1568 }
1569
Rakina Zata Amnifd8370b2022-11-14 13:32:251570 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1571 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091572 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251573 details->did_replace_entry =
1574 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091575
fdegans9caf66a2015-07-30 21:10:421576 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111577 // except for restored entries. This should be true even if the current commit
1578 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291579 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481580 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081581 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111582
1583 // Only make changes based on the pending entry if the NavigationRequest
1584 // matches it. Otherwise, the pending entry may be for a different request
1585 // (e.g., if a slow history navigation is pending while an auto-subframe
1586 // commit occurs).
1587 if (PendingEntryMatchesRequest(navigation_request)) {
1588 // It is no longer necessary to consider the pending entry as restored.
1589 if (pending_entry_->IsRestored()) {
1590 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1591 was_restored = true;
1592 }
[email protected]e9ba4472008-09-14 15:42:431593
Charlie Reisf8cde712022-10-20 16:25:091594 // If the SiteInstance has changed from the matching pending entry, this
1595 // must be treated as a new navigation with replacement. Set the replacement
1596 // bit here and ClassifyNavigation will identify this case and return
1597 // NEW_ENTRY.
1598 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1599 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1600 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251601 // TODO(nasko,creis,rakina): Move this to happen before committing the
1602 // navigation. This is a bit complicated because we don't currently
1603 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091604 details->did_replace_entry = true;
1605 }
Nasko Oskovaee2f862018-06-15 00:05:521606 }
[email protected]bcd904482012-02-01 01:54:221607
[email protected]e9ba4472008-09-14 15:42:431608 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101609 NavigationType navigation_type =
1610 ClassifyNavigation(rfh, params, navigation_request);
1611 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451612
Rakina Zata Amnie2d31312022-11-18 03:38:451613 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451614 // Ensure that this navigation does not add a navigation entry, since
1615 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1616 // beyond the last committed one. Therefore, `should_replace_current_entry`
1617 // should be set, which replaces the current entry, or this should be a
1618 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251619 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331620 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451621 }
1622
Rakina Zata Amnie2d31312022-11-18 03:38:451623 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551624 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241625 // This is a subframe navigation on the initial empty document, which used
1626 // to not have a NavigationEntry to attach to. Now it can attach to the
1627 // initial NavigationEntry, and we must ensure that its NavigationEntry
1628 // will keep the "initial NavigationEntry" status and won't append a new
1629 // NavigationEntry (it should always do replacement instead).
1630 // See also https://crbug.com/1277414.
1631 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551632 // Subframe navigation on initial NavigationEntry must not append a new
1633 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1634 // means every subframe navigation that happens while we're on the initial
1635 // NavigationEntry will always reuse the existing NavigationEntry and
1636 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101637 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1638 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551639 // This is a navigation that modifies the initial NavigationEntry, either
1640 // for a replacement or a reload. The initial NavigationEntry should
1641 // retain its "initial NavigationEntry" status in this case.
1642 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241643 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251644 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1645 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241646 // This is a synchronous about:blank navigation on the main frame, which
1647 // used to not create a NavigationEntry when we have no NavigationEntry on
1648 // FrameTree creation. We now have the initial NavigationEntry and are on
1649 // the initial NavigationEntry. To preserve old behavior, we should still
1650 // keep the "initial" status for the new NavigationEntry that we will
1651 // create for this navigation, so that subframe navigations under the
1652 // synchronously committed about:blank document will never append new
1653 // NavigationEntry, and instead will just reuse the initial
1654 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1655 // See also https://crbug.com/1277414.
1656 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551657 }
1658 }
1659 DCHECK(!details->should_stay_as_initial_entry ||
1660 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201661
eugenebutee08663a2017-04-27 17:43:121662 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441663 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121664
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071665 details->is_prerender_activation =
1666 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241667 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1668 ->GetOutermostMainFrame()
1669 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071670
Peter Boströmd7592132019-01-30 04:50:311671 // Make sure we do not discard the pending entry for a different ongoing
1672 // navigation when a same document commit comes in unexpectedly from the
1673 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1674 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581675 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061676 bool keep_pending_entry =
1677 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101678 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061679 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311680
Miyoung Shin3299cbf2022-11-22 01:41:101681 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061682 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491683 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051684 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561685 previous_document_had_history_intervention_activation,
1686 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431687 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061688 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491689 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1690 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001691 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431692 break;
[email protected]8ff00d72012-10-23 19:12:211693 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471694 RendererDidNavigateNewSubframe(
1695 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561696 previous_document_had_history_intervention_activation,
1697 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431698 break;
[email protected]8ff00d72012-10-23 19:12:211699 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391700 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251701 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001702 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081703 // We don't send a notification about auto-subframe PageState during
1704 // UpdateStateForFrame, since it looks like nothing has changed. Send
1705 // it here at commit time instead.
1706 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431707 return false;
creis59d5a47cb2016-08-24 23:57:191708 }
[email protected]e9ba4472008-09-14 15:42:431709 break;
Aran Gilman37d11632019-10-08 23:07:151710 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211711 NOTREACHED();
[email protected]765b35502008-08-21 00:51:201712 }
1713
[email protected]688aa65c62012-09-28 04:32:221714 // At this point, we know that the navigation has just completed, so
1715 // record the time.
1716 //
1717 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261718 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331719 base::Time timestamp =
1720 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1721 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131722 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221723
Peter Boströmd7592132019-01-30 04:50:311724 // If we aren't keeping the pending entry, there shouldn't be one at this
1725 // point. Clear it again in case any error cases above forgot to do so.
1726 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1727 // been cleared instead of protecting against it.
1728 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551729 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141730
[email protected]e9ba4472008-09-14 15:42:431731 // All committed entries should have nonempty content state so WebKit doesn't
1732 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471733 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321734 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221735 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441736 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141737
Alexander Timind2f2e4f22019-04-02 20:04:531738 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1739 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281740 if (back_forward_cache_metrics &&
1741 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531742 active_entry->set_back_forward_cache_metrics(
1743 std::move(back_forward_cache_metrics));
1744 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281745
1746 // `back_forward_cache_metrics()` may return null as we do not record
1747 // back-forward cache metrics for navigations in non-primary frame trees.
1748 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581749 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141750 // These are both only available from details at this point, so we capture
1751 // them here.
1752 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101753 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141754 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1755 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281756 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1757 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321758 IsBackForwardCacheEnabled() &&
1759 rfh->delegate()->IsBackForwardCacheSupported() &&
1760 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281761 }
naskoc7533512016-05-06 17:01:121762
Charles Reisc0507202017-09-21 00:40:021763 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1764 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1765 // A mismatch can occur if the renderer lies or due to a unique name collision
1766 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121767 FrameNavigationEntry* frame_entry =
1768 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021769 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1770 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031771 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081772 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1773 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031774 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201775
1776 // Remember the bindings the renderer process has at this point, so that
1777 // we do not grant this entry additional bindings if we come back to it.
1778 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301779 }
[email protected]132e281a2012-07-31 18:32:441780
[email protected]97d8f0d2013-10-29 16:49:211781 // Once it is committed, we no longer need to track several pieces of state on
1782 // the entry.
naskoc7533512016-05-06 17:01:121783 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131784
[email protected]49bd30e62011-03-22 20:12:591785 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221786 // TODO(creis): This check won't pass for subframes until we create entries
1787 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001788 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421789 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591790
[email protected]e9ba4472008-09-14 15:42:431791 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001792 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001793 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311794 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531795
arthursonzogni7ddc6542021-04-09 09:16:501796 active_entry->SetIsOverridingUserAgent(
1797 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031798
[email protected]93f230e02011-06-01 14:40:001799 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291800
aelias100c9192017-01-13 00:01:431801 if (overriding_user_agent_changed)
1802 delegate_->UpdateOverridingUserAgent();
1803
creis03b48002015-11-04 00:54:561804 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1805 // one knows the latest NavigationEntry it is showing (whether it has
1806 // committed anything in this navigation or not). This allows things like
1807 // state and title updates from RenderFrames to apply to the latest relevant
1808 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381809 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031810 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381811 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431812
1813 if (navigation_request->IsPrerenderedPageActivation()) {
Charlie Reis99b2eba22025-01-31 19:18:571814 BroadcastHistoryIndexAndLength();
Alison Gale47d1537d2024-04-19 21:31:461815 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431816 // is activated. As a result, a "prerenderingchange" event listener sees the
1817 // history.length which is not updated yet. We should guarantee that
Charlie Reis99b2eba22025-01-31 19:18:571818 // history's length and index should be updated before a
Hayato Ito2c8c08d02021-06-23 03:38:431819 // "prerenderingchange" event listener runs. One possible approach is to use
1820 // the same IPC which "prerenderingchange" uses, and propagate history's
Charlie Reis99b2eba22025-01-31 19:18:571821 // length and index together with that.
Hayato Ito2c8c08d02021-06-23 03:38:431822 }
1823
[email protected]e9ba4472008-09-14 15:42:431824 return true;
initial.commit09911bf2008-07-26 23:55:291825}
1826
[email protected]8ff00d72012-10-23 19:12:211827NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321828 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101829 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241830 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591831 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511832 "ClassifyNavigation");
1833
avi7c6f35e2015-05-08 17:52:381834 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241835 // A new entry. We may or may not have a corresponding pending entry, and
1836 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001837 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491838 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061839 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381840 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241841 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511842 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381843 return NAVIGATION_TYPE_NEW_SUBFRAME;
1844 }
1845
Charlie Reisc0f17d2d2021-01-12 18:52:491846 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381847 DCHECK(!params.history_list_was_cleared);
1848
avi39c1edd32015-06-04 20:06:001849 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381850 // All manual subframes would be did_create_new_entry and handled above, so
1851 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081852 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1853 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381854 }
1855
Rakina Zata Amnif6950d552020-11-24 03:26:101856 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1857 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381858 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1859 // create a new page.
1860
Hayato Ito2ae49442021-07-02 02:59:251861 // This main frame navigation is not a history navigation (since
1862 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1863 // reload or a replacement navigation, which will modify the existing entry.
1864 //
Nasko Oskov332593c2018-08-16 17:21:341865 // TODO(nasko): With error page isolation, reloading an existing session
1866 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491867 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341868 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511869 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491870 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061871 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381872 }
1873
Charlie Reisf8cde712022-10-20 16:25:091874 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521875 // If the SiteInstance of the |pending_entry_| does not match the
1876 // SiteInstance that got committed, treat this as a new navigation with
1877 // replacement. This can happen if back/forward/reload encounters a server
1878 // redirect to a different site or an isolated error page gets successfully
1879 // reloaded into a different SiteInstance.
1880 if (pending_entry_->site_instance() &&
1881 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491882 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061883 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521884 }
creis77c9aa32015-09-25 19:59:421885
Nasko Oskovaee2f862018-06-15 00:05:521886 if (pending_entry_index_ == -1) {
1887 // In this case, we have a pending entry for a load of a new URL but Blink
1888 // didn't do a new navigation (params.did_create_new_entry). First check
1889 // to make sure Blink didn't treat a new cross-process navigation as
1890 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161891 // we must treat it as NEW rather than the converted reload case below,
1892 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451893 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161894 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061895 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521896 }
1897
1898 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161899 // We will create a pending entry, but NavigateWithoutEntry will convert
1900 // it to a reload since it's the same page and not create a new entry for
1901 // it. (The user doesn't want to have a new back/forward entry when they
1902 // do this.) Therefore we want to just ignore the pending entry and go
1903 // back to where we were (the "existing entry").
1904 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061905 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521906 }
avi7c6f35e2015-05-08 17:52:381907 }
1908
Rakina Zata Amni153d5702021-09-13 22:48:001909 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381910 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491911 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1912 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161913 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061914 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381915 }
1916
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121917 if (navigation_request->DidEncounterError() &&
1918 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101919 nav_entry_id == failed_pending_entry_id_) {
Charlie Reisb5f39cf2024-11-12 16:55:011920 // If the renderer was going to a pending entry that got cleared because of
1921 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511922 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491923 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061924 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381925 }
1926
Charlie Reisc0f17d2d2021-01-12 18:52:491927 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101928 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511929 trace_return.traced_value()->SetInteger("existing_entry_index",
1930 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381931 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441932 // The renderer has committed a navigation to an entry that no longer
1933 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491934 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061935 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381936 }
1937
avi7c6f35e2015-05-08 17:52:381938 // Since we weeded out "new" navigations above, we know this is an existing
1939 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491940 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061941 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381942}
1943
Rakina Zata Amni3460d382021-10-29 00:43:371944void NavigationControllerImpl::UpdateNavigationEntryDetails(
1945 NavigationEntryImpl* entry,
1946 RenderFrameHostImpl* rfh,
1947 const mojom::DidCommitProvisionalLoadParams& params,
1948 NavigationRequest* request,
1949 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001950 bool is_new_entry,
1951 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371952 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171953 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371954 entry->AddOrUpdateFrameEntry(
1955 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571956 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371957 rfh->GetSiteInstance(), nullptr, params.url,
1958 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171959 Referrer(*params.referrer),
1960 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371961 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171962 request ? request->GetRedirectChain() : redirects, params.page_state,
1963 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371964 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171965 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211966 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171967 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371968
1969 if (rfh->GetParent()) {
1970 // Only modify the NavigationEntry for main frame navigations.
1971 return;
1972 }
1973 if (entry->update_virtual_url_with_url())
1974 UpdateVirtualURLToURL(entry, params.url);
1975 // Don't use the page type from the pending entry. Some interstitial page
1976 // may have set the type to interstitial. Once we commit, however, the page
1977 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171978 entry->set_page_type((request && request->DidEncounterError())
1979 ? PAGE_TYPE_ERROR
1980 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431981 if (commit_details && commit_details->should_stay_as_initial_entry) {
1982 // Retain the "initial NavigationEntry" status.
1983 if (request->IsSameDocument()) {
1984 // If this is for a same-document navigation, the NavigationEntry must be
1985 // reused and should already be marked as the initial NavigationEntry.
1986 DCHECK(entry->IsInitialEntry());
1987 } else {
1988 // If this is for a cross-document navigation, it can be caused by a
1989 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1990 // "for synchronous about:blank" in the latter case, and also when it is
1991 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1992 // is not for a synchronous about:blank commit.
1993 NavigationEntryImpl::InitialNavigationEntryState new_state =
1994 NavigationEntryImpl::InitialNavigationEntryState::
1995 kInitialNotForSynchronousAboutBlank;
1996 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1997 request->is_synchronous_renderer_commit()) {
1998 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1999 kInitialForSynchronousAboutBlank;
2000 }
2001 entry->set_initial_navigation_entry_state(new_state);
2002 }
2003 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
2004 // Remove the "initial NavigationEntry" status.
2005 entry->set_initial_navigation_entry_state(
2006 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:002007 }
Rakina Zata Amniddf10502022-01-15 02:56:552008
Rakina Zata Amni3460d382021-10-29 00:43:372009 if (is_new_entry) {
2010 // Some properties of the NavigationEntry are only set when the entry is
2011 // new (we aren't reusing it).
2012 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:172013 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:402014 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:012015 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
2016 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:372017 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
2018 } else {
2019 // We are reusing the NavigationEntry. The site instance will normally be
2020 // the same except for a few cases:
2021 // 1) session restore, when no site instance will be assigned or
2022 // 2) redirect, when the site instance is reset.
2023 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
2024 entry->site_instance() == rfh->GetSiteInstance());
2025 }
2026}
2027
Rakina Zata Amniafd3c6582021-11-30 06:19:172028void NavigationControllerImpl::CreateInitialEntry() {
2029 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:032030 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:172031 auto params = mojom::DidCommitProvisionalLoadParams::New();
2032 // The initial NavigationEntry's URL is the empty URL. This preserves the old
2033 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
2034 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:402035 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:172036 params->http_status_code = 0;
2037 params->url_is_unreachable = false;
2038 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:172039 params->post_id = -1;
2040 params->embedding_token = base::UnguessableToken::Create();
2041 params->navigation_token = base::UnguessableToken::Create();
2042 params->did_create_new_entry = true;
2043 params->origin = rfh->GetLastCommittedOrigin();
2044 params->should_update_history = true;
2045 params->item_sequence_number = 0;
2046 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:152047 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:172048 params->transition = is_in_fenced_frame_tree
2049 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
2050 : ui::PAGE_TRANSITION_LINK;
2051 params->referrer = blink::mojom::Referrer::New();
2052
Rakina Zata Amniafd3c6582021-11-30 06:19:172053 auto new_entry = std::make_unique<NavigationEntryImpl>(
2054 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:382055 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:212056 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
2057 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
2058 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172059 UpdateNavigationEntryDetails(
2060 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:002061 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
2062 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172063
2064 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
2065 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:002066 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172067}
2068
Charlie Reisc0f17d2d2021-01-12 18:52:492069void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:322070 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072071 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362072 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442073 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562074 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002075 NavigationRequest* request,
2076 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572077 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372078 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452079 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372080 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522081 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2082 initiator_base_url = request->common_params().initiator_base_url;
2083 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062084
creisf49dfc92016-07-26 17:05:182085 // First check if this is an in-page navigation. If so, clone the current
2086 // entry instead of looking at the pending entry, because the pending entry
2087 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452088 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302089 FrameNavigationEntry* previous_frame_entry =
2090 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452091 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482092 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572093 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082094 rfh->GetSiteInstance(), nullptr, params.url,
2095 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212096 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092097 request->GetRedirectChain(), params.page_state, params.method,
2098 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392099 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302100 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572101 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302102 // FrameNavigationEntry.
2103 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572104 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032105
creisf49dfc92016-07-26 17:05:182106 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032107 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522108 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2109 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572110 // TODO(jam): we had one report of this with a URL that was redirecting to
2111 // only tildes. Until we understand that better, don't copy the cert in
2112 // this case.
2113 new_entry->GetSSL() = SSLStatus();
2114 }
creisf49dfc92016-07-26 17:05:182115
Patrick Monette50e8bd82019-06-13 22:40:452116 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2117 // that |frame_entry| should now have a reference count of exactly 2: one
2118 // due to the local variable |frame_entry|, and another due to |new_entry|
2119 // also retaining one. This should never fail, because it's the main frame.
2120 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182121 }
2122
Harkiran Bolaria59290d62021-03-17 01:53:012123 // If this is an activation navigation from a prerendered page, transfer the
2124 // new entry from an entry already created and stored in the
2125 // NavigationRequest. |new_entry| will not have been set prior to this as
2126 // |is_same_document| is mutually exclusive with
2127 // |IsPrerenderedPageActivation|.
2128 if (request->IsPrerenderedPageActivation()) {
2129 DCHECK(!is_same_document);
2130 DCHECK(!new_entry);
2131 new_entry = request->TakePrerenderNavigationEntry();
2132 DCHECK(new_entry);
2133 }
2134
Charlie Reisc0f17d2d2021-01-12 18:52:492135 // Only make a copy of the pending entry if it is appropriate for the new
2136 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452137 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042138 // 1. The SiteInstance hasn't been assigned to something else.
2139 // 2. The pending entry was intended as a new entry, rather than being a
2140 // history navigation that was interrupted by an unrelated,
2141 // renderer-initiated navigation.
2142 // TODO(csharrison): Investigate whether we can remove some of the coarser
2143 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452144 if (!new_entry && PendingEntryMatchesRequest(request) &&
2145 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342146 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432147 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352148 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432149
Camille Lamy62b826012019-02-26 09:15:472150 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452151 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182152 }
2153
Charlie Reisc0f17d2d2021-01-12 18:52:492154 // For cross-document commits with no matching pending entry, create a new
2155 // entry.
creisf49dfc92016-07-26 17:05:182156 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062157 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072158 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212159 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582160 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452161 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172162 nullptr, // blob_url_loader_factory
2163 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242164
2165 // Find out whether the new entry needs to update its virtual URL on URL
2166 // change and set up the entry accordingly. This is needed to correctly
2167 // update the virtual URL when replaceState is called after a pushState.
2168 GURL url = params.url;
2169 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492170 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412171 // update the virtual URL based on the new URL. For example, this is needed
2172 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2173 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372174 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2175 &url, browser_context_, &needs_update);
2176 new_entry->set_update_virtual_url_with_url(needs_update);
2177
Camille Lamy62b826012019-02-26 09:15:472178 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452179 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432180 }
2181
Alison Gale770f3fc2024-04-27 00:39:582182 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2183 // set for prerendered contents, if any. This is because
2184 // prerendering/activation technically won't be creating a new document.
2185 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2186 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012187 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372188 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2189 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002190 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082191
Harkiran Bolaria59290d62021-03-17 01:53:012192 // history.pushState() is classified as a navigation to a new page, but sets
2193 // is_same_document to true. In this case, we already have the title and
2194 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452195 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012196 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2197 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2198 }
[email protected]3a868f212014-08-09 10:41:192199 }
[email protected]ff64b3e2014-05-31 04:07:332200
[email protected]60d6cca2013-04-30 08:47:132201 DCHECK(!params.history_list_was_cleared || !replace_entry);
2202 // The browser requested to clear the session history when it initiated the
2203 // navigation. Now we know that the renderer has updated its state accordingly
2204 // and it is safe to also clear the browser side history.
2205 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552206 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132207 entries_.clear();
2208 last_committed_entry_index_ = -1;
2209 }
2210
Nasko Oskovaee2f862018-06-15 00:05:522211 // If this is a new navigation with replacement and there is a
2212 // pending_entry_ which matches the navigation reported by the renderer
2213 // process, then it should be the one replaced, so update the
2214 // last_committed_entry_index_ to use it.
2215 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092216 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522217 last_committed_entry_index_ = pending_entry_index_;
2218 }
2219
Alexander Timine3ec4192020-04-20 16:39:402220 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562221 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402222 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052223
Yuzu Saijoa725585f2022-11-28 04:14:032224 // If this is a history navigation and the old entry has an existing
2225 // back/forward cache metrics object, keep using the old one so that the
2226 // reasons logged from the last time the page navigated gets preserved.
2227 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2228 request)) {
2229 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2230 // because some tests do not have a pending entry.
2231 NavigationEntryImpl* entry =
2232 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2233 if (entry && entry->back_forward_cache_metrics()) {
2234 scoped_refptr<BackForwardCacheMetrics> metrics =
2235 entry->TakeBackForwardCacheMetrics();
2236 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2237 }
2238 }
2239
Andrew Verge754c70a2025-04-17 17:19:192240 bool was_post_commit_error =
2241 request->browser_initiated_error_navigation_type() ==
2242 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit;
2243
Carlos IL42b416592019-10-07 23:10:362244 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Andrew Verge754c70a2025-04-17 17:19:192245 was_post_commit_error, rfh->IsNestedWithinFencedFrame(),
2246 commit_details);
[email protected]e9ba4472008-09-14 15:42:432247}
2248
Charlie Reisc0f17d2d2021-01-12 18:52:492249void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322250 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072251 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362252 bool is_same_document,
jam48cea9082017-02-15 06:13:292253 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452254 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002255 bool keep_pending_entry,
2256 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562257 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2258 << "that a last committed entry exists.";
2259
[email protected]e9ba4472008-09-14 15:42:432260 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002261 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432262
Charlie Reis7e2cb6d2021-01-26 01:27:162263 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002264 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162265 // We're guaranteed to have a last committed entry if intended_as_new_entry
2266 // is true.
avicbdc4c12015-07-01 16:07:112267 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162268
2269 // If the NavigationRequest matches a new pending entry and is classified as
2270 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2271 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092272 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162273 // Note: The pending entry will usually have a real ReloadType here, but
2274 // it can still be ReloadType::NONE in cases that
2275 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2276
2277 // If we classified this correctly, the SiteInstance should not have
2278 // changed.
2279 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2280
2281 // For converted reloads, we assign the entry's unique ID to be that of
2282 // the new one. Since this is always the result of a user action, we want
2283 // to dismiss infobars, etc. like a regular user-initiated navigation.
2284 entry->set_unique_id(pending_entry_->GetUniqueID());
2285
2286 // The extra headers may have changed due to reloading with different
2287 // headers.
2288 entry->set_extra_headers(pending_entry_->extra_headers());
2289 }
2290 // Otherwise, this was intended as a new entry but the pending entry was
2291 // lost in the meantime and no new entry was created. We are stuck at the
2292 // last committed entry.
2293
2294 // Even if this is a converted reload from pressing enter in the omnibox,
2295 // the server could redirect, requiring an update to the SSL status. If this
2296 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452297 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162298 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472299 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452300 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162301 }
Rakina Zata Amnif6950d552020-11-24 03:26:102302 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112303 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102304 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162305
eugenebut604866f2017-05-10 21:35:362306 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452307 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362308 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2309 // this was a restored same document navigation entry, then it won't have
2310 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2311 // navigated it.
jam48cea9082017-02-15 06:13:292312 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522313 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2314 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292315 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2316 was_restored) {
2317 entry->GetSSL() = last_entry->GetSSL();
2318 }
2319 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452320 // In rapid back/forward navigations |request| sometimes won't have a cert
2321 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192322 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452323 if (request->GetSSLInfo().has_value() &&
2324 request->GetSSLInfo()->is_valid()) {
2325 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522326 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2327 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192328 entry->GetSSL() = SSLStatus();
2329 }
jam48cea9082017-02-15 06:13:292330 }
avicbdc4c12015-07-01 16:07:112331 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272332 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572333 // navigations that are EXISTING_ENTRY are same-document navigations that
2334 // result in replacement (e.g. history.replaceState(), location.replace(),
2335 // forced replacements for trivial session history contexts). For these
2336 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112337 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102338
Alison Gale81f4f2c72024-04-22 19:33:312339 // TODO(crbug.com/40532777): Set page transition type to
2340 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2341 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2342 // well as to fix the inconsistency with what we report to observers
2343 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102344
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572345 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102346
eugenebut604866f2017-05-10 21:35:362347 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452348 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362349 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472350 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452351 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112352 }
2353 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432354
Rakina Zata Amni3460d382021-10-29 00:43:372355 UpdateNavigationEntryDetails(entry, rfh, params, request,
2356 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002357 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302358
[email protected]5ccd4dc2012-10-24 02:28:142359 // The redirected to page should not inherit the favicon from the previous
2360 // page.
eugenebut604866f2017-05-10 21:35:362361 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482362 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142363
Charlie Reis951f43372023-05-05 00:30:072364 // Update the last committed index to reflect the committed entry. Do this
2365 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2366 // delegate sees the correct committed index when notified of navigation
2367 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2368 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212369 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072370
Peter Boströmd7592132019-01-30 04:50:312371 // We should also usually discard the pending entry if it corresponds to a
2372 // different navigation, since that one is now likely canceled. In rare
2373 // cases, we leave the pending entry for another navigation in place when we
2374 // know it is still ongoing, to avoid a flicker in the omnibox (see
2375 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432376 //
2377 // Note that we need to use the "internal" version since we don't want to
2378 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312379 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002380 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432381}
2382
[email protected]d202a7c2012-01-04 07:53:472383void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322384 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072385 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362386 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472387 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562388 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002389 NavigationRequest* request,
2390 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262391 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2392 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552393 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2394 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112395
[email protected]e9ba4472008-09-14 15:42:432396 // Manual subframe navigations just get the current entry cloned so the user
2397 // can go back or forward to it. The actual subframe information will be
2398 // stored in the page state for each of those entries. This happens out of
2399 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092400 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2401 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382402
Mikel Astizba9cf2fd2017-12-17 10:38:102403 // The DCHECK below documents the fact that we don't know of any situation
2404 // where |replace_entry| is true for subframe navigations. This simplifies
2405 // reasoning about the replacement struct for subframes (see
2406 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2407 DCHECK(!replace_entry);
2408
Patrick Monette50e8bd82019-06-13 22:40:452409 // This FrameNavigationEntry might not end up being used in the
2410 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372411 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452412 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372413 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522414 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2415 initiator_base_url = request->common_params().initiator_base_url;
2416 }
Nate Chapin63db0d12022-01-20 22:03:302417 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2418 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212419 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302420 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572421 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302422 if (is_same_document) {
2423 FrameNavigationEntry* previous_frame_entry =
2424 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572425 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302426 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572427 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302428 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572429 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302430 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572431 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302432 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572433 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302434 policy_container_policies->referrer_policy);
2435 }
2436
Patrick Monette50e8bd82019-06-13 22:40:452437 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482438 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572439 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082440 rfh->GetSiteInstance(), nullptr, params.url,
2441 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212442 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2443 request->GetRedirectChain(), params.page_state, params.method,
2444 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572445 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032446
creisce0ef3572017-01-26 17:53:082447 std::unique_ptr<NavigationEntryImpl> new_entry =
2448 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452449 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032450 frame_tree_->root());
creise062d542015-08-25 02:01:552451
Alexander Timine3ec4192020-04-20 16:39:402452 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562453 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402454 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472455
creisce0ef3572017-01-26 17:53:082456 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452457 // to replace, which can happen due to a unique name change. See
2458 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2459 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382460
Dave Tapuska87696ae2021-11-18 18:48:312461 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152462 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432463}
2464
[email protected]d202a7c2012-01-04 07:53:472465bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322466 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072467 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392468 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252469 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002470 NavigationRequest* request,
2471 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292472 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2473 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2474
[email protected]e9ba4472008-09-14 15:42:432475 // We're guaranteed to have a previously committed entry, and we now need to
2476 // handle navigation inside of a subframe in it without creating a new entry.
2477 DCHECK(GetLastCommittedEntry());
2478
creis913c63ce2016-07-16 19:52:522479 // For newly created subframes, we don't need to send a commit notification.
2480 // This is only necessary for history navigations in subframes.
2481 bool send_commit_notification = false;
2482
Rakina Zata Amnif6950d552020-11-24 03:26:102483 // If |nav_entry_id| is non-zero and matches an existing entry, this
2484 // is a history navigation. Update the last committed index accordingly. If
2485 // we don't recognize the |nav_entry_id|, it might be a recently
2486 // pruned entry. We'll handle it below.
2487 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2488 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472489 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062490 // Make sure that a subframe commit isn't changing the main frame's
2491 // origin. Otherwise the renderer process may be confused, leading to a
2492 // URL spoof. We can't check the path since that may change
2493 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572494 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2495 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242496 // We should use checks similar to RenderFrameHostImpl's
2497 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2498 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572499 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2500 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2501 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2502 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522503 current_top_url.DeprecatedGetOriginAsURL() !=
2504 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442505 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512506 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062507 }
creis3cdc3b02015-05-29 23:00:472508
creis913c63ce2016-07-16 19:52:522509 // We only need to discard the pending entry in this history navigation
2510 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062511 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002512 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522513
2514 // History navigations should send a commit notification.
2515 send_commit_notification = true;
avi98405c22015-05-21 20:47:062516 }
[email protected]e9ba4472008-09-14 15:42:432517 }
[email protected]f233e4232013-02-23 00:55:142518
creisce0ef3572017-01-26 17:53:082519 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2520 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372521 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2522 // exists), or we may want to clobber it and create a new one. We update in
2523 // cases where the corresponding FrameNavigationEntry is conceptually similar
2524 // to the document described by the commit params: same-document
2525 // navigations, history traversal to an existing entry, and reloads (including
2526 // a "soft reload" where we navigate to the same url without flagging it as a
2527 // reload). But in the case of a different document that is not logically
2528 // related to the committed FrameNavigationEntry's document (cross-document,
2529 // not same url, not a reload, not a history traversal), we replace rather
2530 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252531 //
Nate Chapin9f169072021-06-09 19:32:372532 // In the case where we update, the FrameNavigationEntry will potentially be
2533 // shared across multiple NavigationEntries, and any updates will be reflected
2534 // in all of those NavigationEntries. In the replace case, any existing
2535 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252536 //
2537 // When navigating away from the initial empty document, we also update rather
2538 // than replace. Either update or replace will overwrite the initial empty
2539 // document state for |last_committed|, but if the FrameNavigationEntry for
2540 // the initial empty document is shared across multiple NavigationEntries (due
2541 // to a navigation in another frame), we want to make sure we overwrite the
2542 // initial empty document state everywhere this FrameNavigationEntry is used,
2543 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452544 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372545 FrameNavigationEntry* last_committed_frame_entry =
2546 last_committed->GetFrameEntry(rfh->frame_tree_node());
2547 NavigationEntryImpl::UpdatePolicy update_policy =
2548 NavigationEntryImpl::UpdatePolicy::kUpdate;
2549 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312550 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372551 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252552 last_committed_frame_entry->url() != params.url &&
2553 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372554 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2555 }
2556
Rakina Zata Amni3460d382021-10-29 00:43:372557 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002558 update_policy, false /* is_new_entry */,
2559 commit_details);
creis625a0c7d2015-03-24 23:17:122560
creis913c63ce2016-07-16 19:52:522561 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432562}
2563
[email protected]d202a7c2012-01-04 07:53:472564int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232565 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032566 for (size_t i = 0; i < entries_.size(); ++i) {
2567 if (entries_[i].get() == entry)
2568 return i;
2569 }
2570 return -1;
[email protected]765b35502008-08-21 00:51:202571}
2572
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572573void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242574 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572575 NavigationControllerImpl* source =
2576 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572577 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382578 DCHECK_EQ(1, GetEntryCount());
2579 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472580 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172581 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572582
Francois Dorayeaace782017-06-21 16:37:242583 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442584 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572585 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572586
Fergal Dalya1d569972021-03-16 03:24:532587 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302588 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532589 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2590 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302591 }
[email protected]4e6419c2010-01-15 04:50:342592
Lukasz Anforowicz0de0f452020-12-02 19:57:152593 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572594}
2595
[email protected]79368982013-11-13 01:11:012596bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022597 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162598 if (last_committed_entry_index_ == -1)
2599 return false;
[email protected]9350602e2013-02-26 23:27:442600
[email protected]474f8512013-05-31 22:31:162601 // We cannot prune if there is a pending entry at an existing entry index.
2602 // It may not commit, so we have to keep the last committed entry, and thus
2603 // there is no sensible place to keep the pending entry. It is ok to have
2604 // a new pending entry, which can optionally commit as a new navigation.
2605 if (pending_entry_index_ != -1)
2606 return false;
2607
[email protected]474f8512013-05-31 22:31:162608 return true;
2609}
2610
[email protected]79368982013-11-13 01:11:012611void NavigationControllerImpl::PruneAllButLastCommitted() {
2612 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162613
avi2b177592014-12-10 02:08:022614 DCHECK_EQ(0, last_committed_entry_index_);
2615 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442616
Charlie Reis99b2eba22025-01-31 19:18:572617 BroadcastHistoryIndexAndLength();
[email protected]9350602e2013-02-26 23:27:442618}
2619
[email protected]79368982013-11-13 01:11:012620void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162621 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012622 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262623
Nate Chapin9eb16be72022-09-23 22:54:312624 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2625
[email protected]474f8512013-05-31 22:31:162626 // Erase all entries but the last committed entry. There may still be a
2627 // new pending entry after this.
2628 entries_.erase(entries_.begin(),
2629 entries_.begin() + last_committed_entry_index_);
2630 entries_.erase(entries_.begin() + 1, entries_.end());
2631 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262632}
2633
Christian Dullweber1af31e62018-02-22 11:49:482634void NavigationControllerImpl::DeleteNavigationEntries(
2635 const DeletionPredicate& deletionPredicate) {
2636 // It is up to callers to check the invariants before calling this.
2637 CHECK(CanPruneAllButLastCommitted());
2638 std::vector<int> delete_indices;
2639 for (size_t i = 0; i < entries_.size(); i++) {
2640 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572641 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482642 delete_indices.push_back(i);
2643 }
2644 }
2645 if (delete_indices.empty())
2646 return;
2647
2648 if (delete_indices.size() == GetEntryCount() - 1U) {
2649 PruneAllButLastCommitted();
2650 } else {
2651 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382652 for (const auto& index : base::Reversed(delete_indices)) {
2653 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482654 }
Charlie Reis99b2eba22025-01-31 19:18:572655 BroadcastHistoryIndexAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482656 }
2657 delegate()->NotifyNavigationEntriesDeleted();
2658}
2659
Carlos Caballero35ce710c2019-09-19 10:59:452660BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2661 return back_forward_cache_;
2662}
2663
William Liu055a3542023-04-02 17:21:192664NavigationEntryScreenshotCache*
2665NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212666 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262667 if (!nav_entry_screenshot_cache_ &&
2668 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192669 nav_entry_screenshot_cache_ =
2670 std::make_unique<NavigationEntryScreenshotCache>(
2671 BrowserContextImpl::From(browser_context_)
2672 ->GetNavigationEntryScreenshotManager()
2673 ->GetSafeRef(),
2674 this);
2675 }
2676 return nav_entry_screenshot_cache_.get();
2677}
2678
clamy987a3752018-05-03 17:36:262679void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2680 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2681 // progress, since this will cause a use-after-free. (We only allow this
2682 // when the tab is being destroyed for shutdown, since it won't return to
2683 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032684 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
Minoru Chikamune13ab4de2025-05-14 21:54:072685 // If `was_failure` is true, it means that the pending entry was discarded by
2686 // a `PendingEntryRefDeleted` call within `OnRequestFailedInternal`, in
2687 // response to a navigation request failure. This case is not at risk for
2688 // re-entrancy when `can_be_in_navigate_to_pending_entry_` is true, because
2689 // that code also creates another `PendingEntryRef` that would prevent the
2690 // `DiscardPendingEntry` call if the PostTask were skipped. See
2691 // https://crbug.com/411855273.
2692 if (!was_failure && can_be_in_navigate_to_pending_entry_ &&
Minoru Chikamune646eba42025-04-14 01:25:032693 !frame_tree_->IsBeingDestroyed()) {
2694 CheckPotentialNavigationReentrancy();
2695 }
clamy987a3752018-05-03 17:36:262696
2697 if (was_failure && pending_entry_) {
2698 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2699 } else {
2700 failed_pending_entry_id_ = 0;
2701 }
2702
2703 if (pending_entry_) {
2704 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332705 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262706 pending_entry_index_ = -1;
2707 pending_entry_ = nullptr;
2708 }
arthursonzogni66f711c2019-10-08 14:40:362709
2710 // Ensure any refs to the current pending entry are ignored if they get
2711 // deleted, by clearing the set of known refs. All future pending entries will
2712 // only be affected by new refs.
2713 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262714}
2715
2716void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2717 if (pending_entry_)
2718 pending_entry_->set_ssl_error(error);
2719}
2720
Xiaohan Wang7f8052e02022-01-14 18:44:282721#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422722// static
2723bool NavigationControllerImpl::ValidateDataURLAsString(
2724 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2725 if (!data_url_as_string)
2726 return false;
2727
2728 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2729 return false;
2730
2731 // The number of characters that is enough for validating a data: URI.
2732 // From the GURL's POV, the only important part here is scheme, it doesn't
2733 // check the actual content. Thus we can take only the prefix of the url, to
2734 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562735 constexpr size_t kDataUriPrefixMaxLen = 64;
2736 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2737 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422738 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2739 return false;
2740
2741 return true;
2742}
2743#endif
2744
Shivani Sharma194877032019-03-07 17:52:472745void NavigationControllerImpl::NotifyUserActivation() {
2746 // When a user activation occurs, ensure that all adjacent entries for the
2747 // same document clear their skippable bit, so that the history manipulation
2748 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012749 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172750 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012751 // If the value of CanGoBack changes as a result of making some entries
2752 // non-skippable, then we must let the delegate know to update its UI state.
2753 // See https://crbug.com/1477784.
2754 if (!can_go_back && CanGoBack()) {
2755 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2756 }
Shivani Sharma194877032019-03-07 17:52:472757}
2758
clamy987a3752018-05-03 17:36:262759bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2760 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332761 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2762 blink::LocalFrameToken initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492763 int initiator_process_id,
2764 base::TimeTicks actual_navigation_start) {
clamy987a3752018-05-03 17:36:262765 NavigationEntryImpl* entry =
2766 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2767 if (!entry)
2768 return false;
2769
2770 FrameNavigationEntry* frame_entry =
2771 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2772 if (!frame_entry)
2773 return false;
2774
Camille Lamy5193caa2018-10-12 11:59:422775 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572776 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232777 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332778 true /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:492779 initiator_process_id, actual_navigation_start);
clamyea99ea12018-05-28 13:54:232780
2781 if (!request)
2782 return false;
2783
arthursonzognif046d4a2019-12-12 19:08:102784 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412785
Rakina Zata Amni1c83b082023-02-08 01:09:002786 SCOPED_CRASH_KEY_STRING256(
2787 "Bug1400009", "req_url",
2788 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2789 SCOPED_CRASH_KEY_NUMBER(
2790 "Bug1400009", "nav_entry_si",
2791 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2792 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2793 frame_entry->site_instance()
2794 ? ((int)frame_entry->site_instance()->GetId())
2795 : -1);
2796 bool has_sig =
2797 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2798 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2799 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2800 has_sig ? (!!frame_tree_->GetRenderViewHost(
2801 frame_entry->site_instance()->group()))
2802 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052803 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2804 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232805
2806 return true;
clamy987a3752018-05-03 17:36:262807}
2808
Tsuyoshi Horo52fd08e2020-07-07 07:03:452809bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
Charlie Reisf4d51f402025-05-23 18:00:492810 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Tsuyoshi Horo52fd08e2020-07-07 07:03:452811 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2812 if (!entry)
2813 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432814
2815 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2816 // We should never navigate to an existing initial NavigationEntry that is
2817 // the initial NavigationEntry for the initial empty document that hasn't
2818 // been overridden by the synchronous about:blank commit, to preserve
2819 // legacy behavior where trying to reload when the main frame is on the
2820 // initial empty document won't result in a navigation. See also
2821 // https://crbug.com/1277414.
2822 return false;
2823 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452824 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2825 if (!frame_entry)
2826 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142827 ReloadType reload_type = ReloadType::NORMAL;
2828 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452829 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142830 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452831 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432832 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372833 std::nullopt /* initiator_frame_token */,
Charlie Reisf4d51f402025-05-23 18:00:492834 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
2835 actual_navigation_start);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452836 if (!request)
2837 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052838 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452839 return true;
2840}
2841
clamy987a3752018-05-03 17:36:262842void NavigationControllerImpl::NavigateFromFrameProxy(
2843 RenderFrameHostImpl* render_frame_host,
2844 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022845 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452846 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372847 const std::optional<url::Origin>& initiator_origin,
2848 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262849 bool is_renderer_initiated,
2850 SiteInstance* source_site_instance,
2851 const Referrer& referrer,
2852 ui::PageTransition page_transition,
2853 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252854 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262855 const std::string& method,
2856 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092857 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142858 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212859 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502860 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372861 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292862 blink::mojom::NavigationInitiatorActivationAndAdStatus
2863 initiator_activation_and_ad_status,
Charlie Reise1d9b8182025-04-02 04:32:122864 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:222865 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492866 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462867 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452868 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582869 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032870 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342871 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372872 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582873 if (is_renderer_initiated)
2874 DCHECK(initiator_origin.has_value());
2875
clamy987a3752018-05-03 17:36:262876 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582877
Rakina Zata Amni2322f4f82022-01-24 13:24:242878 // Don't allow an entry replacement if there is no entry to replace.
2879 // http://crbug.com/457149
2880 if (GetEntryCount() == 0)
2881 should_replace_current_entry = false;
2882
clamy987a3752018-05-03 17:36:262883 // Create a NavigationEntry for the transfer, without making it the pending
2884 // entry. Subframe transfers should have a clone of the last committed entry
2885 // with a FrameNavigationEntry for the target frame. Main frame transfers
2886 // should have a new NavigationEntry.
2887 // TODO(creis): Make this unnecessary by creating (and validating) the params
2888 // directly, passing them to the destination RenderFrameHost. See
2889 // https://crbug.com/536906.
2890 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262891 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262892 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452893 DCHECK(GetLastCommittedEntry());
2894 entry = GetLastCommittedEntry()->Clone();
2895 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172896 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2897 // Renderer-initiated navigation that target a remote frame are currently
2898 // classified as browser-initiated when this one has already navigated.
2899 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372900 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2901 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2902 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2903 // same-document navigation), they will still be present in the
2904 // committed NavigationEntry that will be referenced to construct the new
2905 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262906 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082907 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582908 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372909 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212910 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152911 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262912 } else {
2913 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172914 // If `node` is the outermost main frame, it rewrites a virtual url in order
2915 // to adjust the original input url if needed. For inner frames such as
2916 // fenced frames or subframes, they don't rewrite urls as the urls are not
2917 // input urls by users.
2918 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372919 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322920 if (source_site_instance && source_site_instance->HasProcess()) {
2921 source_process_site_url =
2922 source_site_instance->GetProcess()->GetProcessLock().site_url();
2923 }
clamy987a3752018-05-03 17:36:262924 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212925 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322926 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212927 extra_headers, browser_context_, blob_url_loader_factory,
2928 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262929 entry->root_node()->frame_entry->set_source_site_instance(
2930 static_cast<SiteInstanceImpl*>(source_site_instance));
2931 entry->root_node()->frame_entry->set_method(method);
2932 }
clamy987a3752018-05-03 17:36:262933
Camille Lamy5193caa2018-10-12 11:59:422934 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452935 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262936 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422937 override_user_agent = true;
clamy987a3752018-05-03 17:36:262938 }
2939 // TODO(creis): Set user gesture and intent received timestamp on Android.
2940
2941 // We may not have successfully added the FrameNavigationEntry to |entry|
2942 // above (per https://crbug.com/608402), in which case we create it from
2943 // scratch. This works because we do not depend on |frame_entry| being inside
2944 // |entry| during NavigateToEntry. This will go away when we shortcut this
2945 // further in https://crbug.com/536906.
2946 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2947 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452948 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082949 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582950 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372951 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212952 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152953 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572954 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262955 }
2956
Camille Lamy5193caa2018-10-12 11:59:422957 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022958 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452959 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292960 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212961 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422962 params.source_site_instance = source_site_instance;
2963 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2964 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032965 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422966 params.referrer = referrer;
2967 /* params.redirect_chain: skip */
2968 params.extra_headers = extra_headers;
2969 params.is_renderer_initiated = is_renderer_initiated;
2970 params.override_user_agent = UA_OVERRIDE_INHERIT;
2971 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542972 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422973 /* params.data_url_as_string: skip */
2974 params.post_data = post_body;
2975 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582976 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422977 /* params.frame_name: skip */
2978 // TODO(clamy): See if user gesture should be propagated to this function.
2979 params.has_user_gesture = false;
2980 params.should_clear_history_list = false;
2981 params.started_from_context_menu = false;
2982 /* params.navigation_ui_data: skip */
2983 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222984 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542985 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212986 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412987 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502988 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292989 params.initiator_activation_and_ad_status =
2990 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032991 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422992
2993 std::unique_ptr<NavigationRequest> request =
2994 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032995 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142996 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392997 ReloadType::NONE, entry.get(), frame_entry.get(),
Charlie Reise1d9b8182025-04-02 04:32:122998 actual_navigation_start_time, navigation_start_time,
2999 is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583000 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343001 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:233002
3003 if (!request)
3004 return;
3005
Garrett Tanzerbb8db412022-09-27 21:59:463006 // Force the navigation to take place in a new browsing instance.
3007 // This is used by _unfencedTop in fenced frames to ensure that navigations
3008 // leaving the fenced context create a new browsing instance.
3009 if (force_new_browsing_instance) {
3010 request->coop_status().ForceBrowsingInstanceSwap();
3011 }
3012
Arthur Hemery948742762019-09-18 10:06:243013 // At this stage we are proceeding with this navigation. If this was renderer
3014 // initiated with user gesture, we need to make sure we clear up potential
3015 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
3016 DiscardNonCommittedEntries();
3017
Lukasz Anforowicz9ee83c272020-12-01 20:14:053018 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:263019}
3020
[email protected]d1198fd2012-08-13 22:50:193021void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253022 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:213023 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:193024 if (!session_storage_namespace)
3025 return;
3026
3027 // We can't overwrite an existing SessionStorage without violating spec.
3028 // Attempts to do so may give a tab access to another tab's session storage
3029 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:153030 bool successful_insert =
3031 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:253032 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:053033 static_cast<SessionStorageNamespaceImpl*>(
3034 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:303035 .second;
3036 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:193037}
3038
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573039bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:453040 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:033041 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:463042}
3043
Aran Gilman37d11632019-10-08 23:07:153044SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:253045 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:303046 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:253047 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:033048 DOMStorageContextWrapper* context_wrapper =
3049 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
3050
3051 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:253052 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:033053 if (it != session_storage_namespace_map_.end()) {
3054 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:153055 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
3056 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:473057
michaelnbacbcbd2016-02-09 00:32:033058 return it->second.get();
3059 }
3060
3061 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:103062 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
3063 SessionStorageNamespaceImpl::Create(context_wrapper);
3064 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
3065 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:253066 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:103067 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:303068
Daniel Murphy31bbb8b12018-02-07 21:44:103069 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:303070}
3071
3072SessionStorageNamespace*
3073NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:253074 return GetSessionStorageNamespace(
3075 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:303076}
3077
3078const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573079NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303080 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553081}
[email protected]d202a7c2012-01-04 07:53:473082
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573083bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563084 return needs_reload_;
3085}
[email protected]a26023822011-12-29 00:23:553086
[email protected]46bb5e9c2013-10-03 22:16:473087void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413088 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3089}
3090
3091void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473092 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413093 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543094
3095 if (last_committed_entry_index_ != -1) {
3096 entries_[last_committed_entry_index_]->SetTransitionType(
3097 ui::PAGE_TRANSITION_RELOAD);
3098 }
[email protected]46bb5e9c2013-10-03 22:16:473099}
3100
[email protected]d202a7c2012-01-04 07:53:473101void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573102 DCHECK_LT(index, GetEntryCount());
3103 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313104 DiscardNonCommittedEntries();
3105
Nate Chapin9eb16be72022-09-23 22:54:313106 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313107 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123108 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313109 last_committed_entry_index_--;
3110}
3111
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573112NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273113 // If there is no pending_entry_, there should be no pending_entry_index_.
3114 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3115
3116 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363117 // at that index. An exception is while a reload of a post commit error page
3118 // is ongoing; in that case pending entry will point to the entry replaced
3119 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273120 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363121 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3122 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273123
[email protected]022af742011-12-28 18:37:253124 return pending_entry_;
3125}
3126
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573127int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273128 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273129 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553130 return pending_entry_index_;
3131}
3132
avi25764702015-06-23 15:43:373133void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573134 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363135 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313136 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003137 bool in_fenced_frame_tree,
3138 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313139 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3140 // set because:
3141 // 1) They don't influence the history of the outer page.
3142 // 2) They are always replace only navigation (there is always only one entry
3143 // in their history stack).
3144 // 3) Are not top level navigations and appear similar to iframes.
3145 // Navigations of the fenced frame might create a new NavigationEntry, which
3146 // will call this function. Non fenced frame navigations will never have
3147 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3148 // InsertOrReplaceEntry.
3149 DCHECK_EQ(in_fenced_frame_tree,
3150 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3151 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203152
avi5cad4912015-06-19 05:25:443153 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3154 // need to keep continuity with the pending entry, so copy the pending entry's
3155 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3156 // then the renderer navigated on its own, independent of the pending entry,
3157 // so don't copy anything.
3158 if (pending_entry_ && pending_entry_index_ == -1)
3159 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203160
Rakina Zata Amnia4e27222021-12-22 01:05:003161 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203162
creisee17e932015-07-17 17:56:223163 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453164 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103165 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573166 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363167 // If the new entry is a post-commit error page, we store the current last
3168 // committed entry to the side so that we can put it back when navigating
3169 // away from the error.
3170 if (was_post_commit_error) {
3171 DCHECK(!entry_replaced_by_post_commit_error_);
3172 entry_replaced_by_post_commit_error_ =
3173 std::move(entries_[last_committed_entry_index_]);
3174 }
dcheng36b6aec92015-12-26 06:16:363175 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223176 return;
3177 }
[email protected]765b35502008-08-21 00:51:203178
creis37979a62015-08-04 19:48:183179 // We shouldn't see replace == true when there's no committed entries.
3180 DCHECK(!replace);
3181
Michael Thiessen9b14d512019-09-23 21:19:473182 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203183
Shivani Sharmad8c8d652019-02-13 17:27:573184 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203185
dcheng36b6aec92015-12-26 06:16:363186 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203187 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293188}
3189
Shivani Sharmad8c8d652019-02-13 17:27:573190void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163191 if (entries_.size() < max_entry_count())
3192 return;
3193
3194 DCHECK_EQ(max_entry_count(), entries_.size());
3195 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573196 CHECK_EQ(pending_entry_index_, -1);
3197
3198 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423199 // Retrieve the oldest skippable entry.
3200 for (; index < GetEntryCount(); index++) {
3201 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3202 break;
Shivani Sharmad8c8d652019-02-13 17:27:573203 }
3204
3205 // If there is no skippable entry or if it is the last committed entry then
3206 // fall back to pruning the oldest entry. It is not safe to prune the last
3207 // committed entry.
3208 if (index == GetEntryCount() || index == last_committed_entry_index_)
3209 index = 0;
3210
3211 bool should_succeed = RemoveEntryAtIndex(index);
3212 DCHECK_EQ(true, should_succeed);
3213
3214 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253215}
3216
William Liu62ae26c2024-08-08 14:28:163217std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273218NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163219 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203220 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373221 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133222 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493223 const std::string* navigation_api_key,
3224 base::TimeTicks actual_navigation_start) {
Alexander Timin3a92df72019-09-20 11:59:503225 TRACE_EVENT0("navigation",
3226 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273227 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023228 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363229 if (pending_entry_index_ != -1) {
3230 // The pending entry may not be in entries_ if a post-commit error page is
3231 // showing.
3232 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3233 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3234 }
Gyuyoung Kim107c2a02021-04-13 01:49:303235 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573236 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013237 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033238 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573239 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133240 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3241 // the same as the top level frame being navigated.
3242 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373243 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133244 }
Arthur Sonzogni620cec62018-12-13 13:08:573245
[email protected]83c2e232011-10-07 21:36:463246 // If we were navigating to a slow-to-commit page, and the user performs
3247 // a session history navigation to the last committed page, RenderViewHost
3248 // will force the throbber to start, but WebKit will essentially ignore the
3249 // navigation, and won't send a message to stop the throbber. To prevent this
3250 // from happening, we drop the navigation here and stop the slow-to-commit
3251 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023252 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083253 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273254 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033255 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123256
[email protected]83c2e232011-10-07 21:36:463257 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163258 return {};
[email protected]83c2e232011-10-07 21:36:463259 }
3260
Arthur Sonzognic686e8f2024-01-11 08:36:373261 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333262 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3263 if (initiator_rfh) {
3264 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543265 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333266 DCHECK(initiator_frame_token);
3267 }
3268
creisce0ef3572017-01-26 17:53:083269 // Compare FrameNavigationEntries to see which frames in the tree need to be
3270 // navigated.
clamy3cb9bea92018-07-10 12:42:023271 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3272 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333273 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3274 initiator_process_id, soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493275 actual_navigation_start, &same_document_loads,
3276 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303277
3278 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573279 // We were unable to match any frames to navigate. This can happen if a
3280 // history navigation targets a subframe that no longer exists
3281 // (https://crbug.com/705550). In this case, we need to update the current
3282 // history entry to the pending one but keep the main document loaded. We
3283 // also need to ensure that observers are informed about the updated
3284 // current history entry (e.g., for greying out back/forward buttons), and
Charlie Reis99b2eba22025-01-31 19:18:573285 // that renderer processes update their history indices. The easiest way
Alex Moshchuk3a4e77a2020-05-29 21:32:573286 // to do all that is to schedule a "redundant" same-document navigation in
3287 // the main frame.
3288 //
3289 // Note that we don't want to remove this history entry, as it might still
3290 // be valid later, since a frame that it's targeting may be recreated.
3291 //
3292 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3293 // need to repeat history navigations until finding the one that works.
3294 // Consider changing this behavior to keep looking for the first valid
3295 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023296 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423297 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573298 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573299 ReloadType::NONE /* reload_type */,
3300 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433301 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493302 initiator_frame_token, initiator_process_id,
3303 actual_navigation_start);
clamy3cb9bea92018-07-10 12:42:023304 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573305 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023306 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163307 return {};
clamy3cb9bea92018-07-10 12:42:023308 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573309 same_document_loads.push_back(std::move(navigation_request));
3310
3311 // Sanity check that we never take this branch for any kinds of reloads,
3312 // as those should've queued a different-document load in the main frame.
3313 DCHECK(!is_forced_reload);
3314 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303315 }
3316
Nate Chapinbf682fa32022-09-26 22:41:203317 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163318 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203319 if (initiator_rfh && initiator_rfh->IsSandboxed(
3320 network::mojom::WebSandboxFlags::kTopNavigation)) {
3321 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3322 initiator_rfh, same_document_loads) &&
3323 DoesSandboxNavigationStayWithinSubtree(
3324 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503325 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163326 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203327 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3328 initiator_rfh,
3329 navigates_inside_tree
3330 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3331 : blink::mojom::WebFeature::
3332 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523333
3334 // If the navigation occurred outside the tree discard it because
3335 // the sandboxed frame didn't have permission to navigate outside
3336 // its tree. If it is possible that the navigation is both inside and
3337 // outside the frame tree and we discard it entirely because we don't
3338 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143339 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203340 // If a |navigation_api_key| was provided, this navigation originated from
3341 // the navigation API. Notify the renderer that the navigation was
3342 // cancelled so the navigation API can fire an error event and reject the
3343 // relevant promise.
3344 if (navigation_api_key) {
3345 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3346 *navigation_api_key,
3347 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3348 }
Dave Tapuska855c1e12019-08-23 20:45:523349 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133350
3351 for (auto& unused_request : same_document_loads) {
3352 unused_request->set_navigation_discard_reason(
3353 NavigationDiscardReason::kNeverStarted);
3354 }
3355 for (auto& unused_request : different_document_loads) {
3356 unused_request->set_navigation_discard_reason(
3357 NavigationDiscardReason::kNeverStarted);
3358 }
William Liu62ae26c2024-08-08 14:28:163359 return {};
Dave Tapuska855c1e12019-08-23 20:45:523360 }
Dave Tapuska8bfd84c2019-03-26 20:47:163361 }
3362
Nate Chapin6c43c022023-02-13 23:32:423363 // If it is possible that this traverse may involve a same-document navigation
3364 // in the initiator and there is a Navigation API key involved, then we may
3365 // need to notify the initiator if it fails. (The early returns above either
3366 // do not involve these cases or already notify the initiator.)
3367 // The event only needs to fire for the initiator, and only if the initiator
3368 // itself is performing a same-document navigation (because the event will not
3369 // fire if it navigates cross-document).
3370 if (navigation_api_key) {
3371 for (auto& item : same_document_loads) {
3372 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3373 item->set_pending_navigation_api_key(*navigation_api_key);
3374 break;
3375 }
3376 }
3377 }
3378
Carlos Caballero539a421c2020-07-06 10:25:573379 // BackForwardCache:
3380 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563381 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573382 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
Charlie Reis655c8f02025-05-15 01:16:173383 CHECK_EQ(reload_type, ReloadType::NONE);
3384 base::WeakPtr<NavigationRequest> request;
Rakina Zata Amni58681c62024-06-25 06:32:133385
Charlie Reis655c8f02025-05-15 01:16:173386 // Skip a redundant NavigationRequest creation, per
3387 // https://crbug.com/417251428.
3388 if (base::FeatureList::IsEnabled(kSkipExtraBfcacheNavigationRequest)) {
3389 // If the BackForwardCache can handle this request, it must be for a main
3390 // frame, cross-document, non-reload request. This means there is only one
3391 // item in `different_document_loads` and no `same_document_loads`.
3392 CHECK_EQ(different_document_loads.size(), 1u);
3393 CHECK(same_document_loads.empty());
3394 request = different_document_loads.at(0)->GetWeakPtr();
Charlie Reisd3e4fef2025-05-20 02:04:173395
3396 // Ensure that no re-entrant calls or discards of the pending entry occur
3397 // while calling `Navigator::Navigate` for a pending entry.
3398 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3399 weak_factory_.GetSafeRef());
3400
Charlie Reis655c8f02025-05-15 01:16:173401 root->navigator().Navigate(std::move(different_document_loads.at(0)),
3402 ReloadType::NONE);
Charlie Reisd3e4fef2025-05-20 02:04:173403
3404 // `reentrancy_guard` deleted here.
Charlie Reis655c8f02025-05-15 01:16:173405 } else {
3406 // The legacy approach creates a new NavigationRequest for the entry and
3407 // discards any previously created NavigationRequests, even though the new
3408 // request is identical to the sole existing request.
3409 // TODO(crbug.com/417251428): Remove this path once we measure the impact.
3410 auto navigation_request = CreateNavigationRequestFromEntry(
3411 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3412 ReloadType::NONE, false /* is_same_document_history_load */,
3413 false /* is_history_navigation_in_new_child */, initiator_frame_token,
Charlie Reisf4d51f402025-05-23 18:00:493414 initiator_process_id, actual_navigation_start);
Charlie Reis655c8f02025-05-15 01:16:173415 request = navigation_request->GetWeakPtr();
3416 root->navigator().Navigate(std::move(navigation_request),
3417 ReloadType::NONE);
3418
3419 for (auto& unused_request : same_document_loads) {
3420 unused_request->set_navigation_discard_reason(
3421 NavigationDiscardReason::kNeverStarted);
3422 }
3423 for (auto& unused_request : different_document_loads) {
3424 unused_request->set_navigation_discard_reason(
3425 NavigationDiscardReason::kNeverStarted);
3426 }
Rakina Zata Amni58681c62024-06-25 06:32:133427 }
3428
Charlie Reis655c8f02025-05-15 01:16:173429 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_requests;
William Liu62ae26c2024-08-08 14:28:163430 if (request) {
Charlie Reis655c8f02025-05-15 01:16:173431 bf_cache_requests.push_back(std::move(request));
William Liu62ae26c2024-08-08 14:28:163432 }
Charlie Reis655c8f02025-05-15 01:16:173433 return bf_cache_requests;
Carlos Caballero539a421c2020-07-06 10:25:573434 }
3435
3436 // History navigation might try to reuse a specific BrowsingInstance, already
3437 // used by a page in the cache. To avoid having two different main frames that
3438 // live in the same BrowsingInstance, evict the all pages with this
3439 // BrowsingInstance from the cache.
3440 //
3441 // For example, take the following scenario:
3442 //
3443 // A1 = Some page on a.com
3444 // A2 = Some other page on a.com
3445 // B3 = An uncacheable page on b.com
3446 //
3447 // Then the following navigations occur:
3448 // A1->A2->B3->A1
3449 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3450 // take its place) and A1 will be created in the same BrowsingInstance (and
3451 // SiteInstance), as A2.
3452 //
3453 // If we didn't do anything, both A1 and A2 would remain alive in the same
3454 // BrowsingInstance/SiteInstance, which is unsupported by
3455 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3456 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483457 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3458 pending_entry_->site_instance()
3459 ? pending_entry_->site_instance()->GetId().value()
3460 : -1);
3461 SCOPED_CRASH_KEY_NUMBER(
3462 "rvh_double", "pending_entry_bi",
3463 pending_entry_->site_instance()
3464 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3465 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573466 if (pending_entry_->site_instance()) {
3467 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3468 pending_entry_->site_instance());
3469 }
3470
Rakina Zata Amnid605d462022-06-01 10:17:033471 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3472 pending_entry_ && pending_entry_->IsRestored());
3473 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3474 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3475 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3476 pending_entry_index_);
3477 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3478 last_committed_entry_index_);
3479 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3480 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3481 pending_entry_ && pending_entry_->IsInitialEntry());
3482 SCOPED_CRASH_KEY_BOOL(
3483 "nav_reentrancy", "pending_entry_initial2",
3484 pending_entry_ &&
3485 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3486 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3487 IsInitialNavigation());
3488 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3489 IsInitialBlankNavigation());
3490 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3491 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3492 (int)pending_reload_);
3493
Charlie Reisd3e4fef2025-05-20 02:04:173494 // Ensure that no re-entrant calls or discards of the pending entry occur
3495 // while calling `Navigator::Navigate` for a pending entry.
3496 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3497 weak_factory_.GetSafeRef());
creis4e2ecb72015-06-20 00:46:303498
Rakina Zata Amnid605d462022-06-01 10:17:033499 // If the navigation-reentrancy is caused by calling
3500 // NavigateToExistingPendingEntry twice, this will note the previous call's
3501 // pending entry's ID.
3502 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3503 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3504
Nate Chapin154b14b2023-02-17 18:28:163505 // If there is a main-frame same-document history navigation, we may defer
3506 // the subframe history navigations in order to give JS in the main frame the
3507 // opportunity to cancel the entire traverse via the navigate event. In that
3508 // case, we need to stash the main frame request's navigation token on the
3509 // subframes, so they can look up the main frame request and defer themselves
3510 // until it completes.
3511 if (!same_document_loads.empty() &&
3512 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3513 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3514 // The token will only be returned in cases where deferring the navigation
3515 // is necessary.
3516 if (auto main_frame_same_document_token =
3517 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3518 for (auto& item : same_document_loads) {
3519 if (item.get() != main_frame_request) {
3520 item->set_main_frame_same_document_history_token(
3521 main_frame_same_document_token);
3522 }
3523 }
3524 for (auto& item : different_document_loads) {
3525 item->set_main_frame_same_document_history_token(
3526 main_frame_same_document_token);
3527 }
3528 }
3529 }
3530
William Liu122754942024-01-18 22:34:393531 if (!initiator_rfh) {
3532 // A browser-initiated navigation won't have a `initiator_rfh`.
3533 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3534 different_document_loads, same_document_loads);
3535 }
3536
William Liu62ae26c2024-08-08 14:28:163537 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3538 all_requests.reserve(same_document_loads.size() +
3539 different_document_loads.size());
3540 bool seen_primary_main_frame_request = false;
3541
creis4e2ecb72015-06-20 00:46:303542 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023543 for (auto& item : same_document_loads) {
3544 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273545 // The request could be destroyed before `navigator().Navigate()` returns.
3546 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053547 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163548 if (request) {
3549 // Can only have one primary main frame request.
3550 CHECK(!seen_primary_main_frame_request ||
3551 !request->IsInPrimaryMainFrame());
3552 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3553 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273554 }
creis4e2ecb72015-06-20 00:46:303555 }
clamy3cb9bea92018-07-10 12:42:023556 for (auto& item : different_document_loads) {
3557 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273558 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053559 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163560 if (request) {
3561 // Can only have one primary main frame request.
3562 CHECK(!seen_primary_main_frame_request ||
3563 !request->IsInPrimaryMainFrame());
3564 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3565 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273566 }
creis4e2ecb72015-06-20 00:46:303567 }
clamy3cb9bea92018-07-10 12:42:023568
William Liu62ae26c2024-08-08 14:28:163569 return all_requests;
Charlie Reisd3e4fef2025-05-20 02:04:173570 // `reentrancy_guard` deleted here.
creis4e2ecb72015-06-20 00:46:303571}
3572
Alex Moshchuk3a4e77a2020-05-29 21:32:573573NavigationControllerImpl::HistoryNavigationAction
3574NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303575 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573576 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423577 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583578 // Only active and prerendered documents are allowed to navigate in their
3579 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423580 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013581 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583582 // - If the document is in pending deletion, the browser already committed
3583 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3584 // - If the document is in back-forward cache, it's not allowed to navigate
3585 // as it should remain frozen. Ignore the request and evict the document
3586 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423587 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583588 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423589 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113590 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3591 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423592 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113593 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423594 }
arthursonzogni03f76152019-02-12 10:35:203595
Alex Moshchuk3a4e77a2020-05-29 21:32:573596 // Reloads should result in a different-document load. Note that reloads may
3597 // also happen via the |needs_reload_| mechanism where the reload_type is
3598 // NONE, so detect this by comparing whether we're going to the same
3599 // entry that we're currently on. Similarly to above, only main frames
3600 // should reach this. Note that subframes support reloads, but that's done
3601 // via a different path that doesn't involve FindFramesToNavigate (see
3602 // RenderFrameHost::Reload()).
3603 if (reload_type != ReloadType::NONE ||
3604 pending_entry_index_ == last_committed_entry_index_) {
3605 DCHECK(frame->IsMainFrame());
3606 return HistoryNavigationAction::kDifferentDocument;
3607 }
3608
Alex Moshchuk47d1a4bd2020-06-01 22:15:343609 // If there is no new FrameNavigationEntry for the frame, ignore the
3610 // load. For example, this may happen when going back to an entry before a
3611 // frame was created. Suppose we commit a same-document navigation that also
3612 // results in adding a new subframe somewhere in the tree. If we go back,
3613 // the new subframe will be missing a FrameNavigationEntry in the previous
3614 // NavigationEntry, but we shouldn't delete or change what's loaded in
3615 // it.
3616 //
Alex Moshchuke65c39272020-06-03 17:55:373617 // Note that in this case, there is no need to keep looking for navigations
3618 // in subframes, which would be missing FrameNavigationEntries as well.
3619 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343620 // It's important to check this before checking |old_item| below, since both
3621 // might be null, and in that case we still shouldn't change what's loaded in
3622 // this frame. Note that scheduling any loads assumes that |new_item| is
3623 // non-null. See https://crbug.com/1088354.
3624 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3625 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373626 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343627
Charlie Reisa474fb62022-03-17 02:31:363628 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3629 // which history item it is currently on, since this may be different than the
3630 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3631 // (e.g., if a history navigation is targeting multiple frames and only some
3632 // have committed so far).
creis4e2ecb72015-06-20 00:46:303633 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363634 frame->current_frame_host()->last_committed_frame_entry();
3635 if (!old_item) {
3636 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3637 // fall back to the last committed NavigationEntry's record for this frame.
3638 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583639 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363640 // accurate FrameNavigationEntry and eliminate this case.
3641 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3642 }
3643 // If neither approach finds a FrameNavigationEntry, schedule a
3644 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583645 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573646 if (!old_item)
3647 return HistoryNavigationAction::kDifferentDocument;
3648
Alex Moshchuk3a4e77a2020-05-29 21:32:573649 // If the new item is not in the same SiteInstance, schedule a
3650 // different-document load. Newly restored items may not have a SiteInstance
3651 // yet, in which case it will be assigned on first commit.
3652 if (new_item->site_instance() &&
3653 new_item->site_instance() != old_item->site_instance())
3654 return HistoryNavigationAction::kDifferentDocument;
3655
Charlie Reis71e4ae32025-01-29 21:37:573656 // If the origins of the new and old items are both present but don't match,
3657 // schedule a different document load even if the document sequence numbers
3658 // somehow match.
3659 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3660 // committed origin on `new_item`, and update the Blink DSN computation to
3661 // avoid a cross-origin DSN match when possible.
3662 if (new_item->committed_origin().has_value() &&
3663 old_item->committed_origin().has_value() &&
3664 !new_item->committed_origin()->IsSameOriginWith(
3665 old_item->committed_origin().value())) {
3666 return HistoryNavigationAction::kDifferentDocument;
3667 }
3668
Alex Moshchuk3a4e77a2020-05-29 21:32:573669 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313670 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3671 // that we do this even if the history navigation would not be modifying this
3672 // frame were it live.
3673 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573674 return HistoryNavigationAction::kDifferentDocument;
3675
3676 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313677 // Starting a navigation after a crash early-promotes the speculative
3678 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3679 // committed yet, so we can not possibly perform a same-document history
3680 // navigation. The frame would need to be reloaded with a cross-document
3681 // navigation.
3682 if (!frame->current_frame_host()->has_committed_any_navigation())
3683 return HistoryNavigationAction::kDifferentDocument;
3684
creis54131692016-08-12 18:32:253685 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493686 // sequence number but different item sequence number.
3687 if (new_item->document_sequence_number() ==
3688 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573689 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493690 }
avib48cb312016-05-05 21:35:003691
Alex Moshchuk3a4e77a2020-05-29 21:32:573692 // Otherwise, if both item and document sequence numbers differ, this
3693 // should be a different document load.
3694 return HistoryNavigationAction::kDifferentDocument;
3695 }
3696
3697 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373698 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573699 DCHECK_EQ(new_item->document_sequence_number(),
3700 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373701 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573702}
3703
3704void NavigationControllerImpl::FindFramesToNavigate(
3705 FrameTreeNode* frame,
3706 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373707 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333708 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373709 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133710 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:493711 base::TimeTicks actual_navigation_start,
Alex Moshchuk3a4e77a2020-05-29 21:32:573712 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3713 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3714 DCHECK(pending_entry_);
3715 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3716
3717 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3718
3719 if (action == HistoryNavigationAction::kSameDocument) {
3720 std::unique_ptr<NavigationRequest> navigation_request =
3721 CreateNavigationRequestFromEntry(
3722 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133723 /*is_same_document_history_load=*/true,
3724 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333725 initiator_frame_token, initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:493726 actual_navigation_start, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573727 if (navigation_request) {
3728 // Only add the request if was properly created. It's possible for the
3729 // creation to fail in certain cases, e.g. when the URL is invalid.
3730 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303731 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573732 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473733 std::unique_ptr<NavigationRequest> navigation_request =
3734 CreateNavigationRequestFromEntry(
3735 frame, pending_entry_, new_item, reload_type,
3736 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433737 false /* is_history_navigation_in_new_child */,
Charlie Reisf4d51f402025-05-23 18:00:493738 initiator_frame_token, initiator_process_id,
3739 actual_navigation_start);
Lei Zhang96031532019-10-10 19:05:473740 if (navigation_request) {
3741 // Only add the request if was properly created. It's possible for the
3742 // creation to fail in certain cases, e.g. when the URL is invalid.
3743 different_document_loads->push_back(std::move(navigation_request));
3744 }
3745 // For a different document, the subframes will be destroyed, so there's
3746 // no need to consider them.
3747 return;
Alex Moshchuke65c39272020-06-03 17:55:373748 } else if (action == HistoryNavigationAction::kStopLooking) {
3749 return;
creis4e2ecb72015-06-20 00:46:303750 }
3751
Yoav Weiss8c573952022-11-17 17:35:133752 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3753 // we currently only support soft navigation heuristics for the top level
3754 // frame.
creis4e2ecb72015-06-20 00:46:303755 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333756 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3757 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373758 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:493759 actual_navigation_start, same_document_loads,
3760 different_document_loads);
creis4e2ecb72015-06-20 00:46:303761 }
3762}
3763
Harkiran Bolariaba823e42021-05-21 18:30:363764base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
Charlie Reisf4d51f402025-05-23 18:00:493765 const LoadURLParams& params,
3766 base::TimeTicks actual_navigation_start) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553767 FrameTreeNode* node = GetTargetFrameTreeNodeForNavigation(params);
clamy21718cc22018-06-13 13:34:243768
Camille Lamy5193caa2018-10-12 11:59:423769 // Compute overrides to the LoadURLParams for |override_user_agent|,
3770 // |should_replace_current_entry| and |has_user_gesture| that will be used
3771 // both in the creation of the NavigationEntry and the NavigationRequest.
3772 // Ideally, the LoadURLParams themselves would be updated, but since they are
3773 // passed as a const reference, this is not possible.
3774 // TODO(clamy): When we only create a NavigationRequest, move this to
3775 // CreateNavigationRequestFromLoadURLParams.
3776 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3777 GetLastCommittedEntry());
3778
Rakina Zata Amnie2d31312022-11-18 03:38:453779 // An entry replacement must happen if the current browsing context should
3780 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333781 bool should_replace_current_entry =
3782 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453783 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423784
clamy21718cc22018-06-13 13:34:243785 // Javascript URLs should not create NavigationEntries. All other navigations
3786 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243787 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373788 std::unique_ptr<NavigationEntryImpl> entry =
3789 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3790 should_replace_current_entry,
3791 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243792 DiscardPendingEntry(false);
3793 SetPendingEntry(std::move(entry));
3794 }
3795
Tim Judkins59548192023-05-17 17:51:203796 // Renderer-debug URLs are sent to the current renderer process immediately
3797 // for processing and don't need to create a NavigationRequest. Note: this
3798 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243799 // renderer-debug URLs.
3800 // Note: we intentionally leave the pending entry in place for renderer debug
3801 // URLs, unlike the cases below where we clear it if the navigation doesn't
3802 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303803 if (blink::IsRendererDebugURL(params.url)) {
Emmanuel Arias Soto9e159652025-05-16 07:53:553804 // Renderer-debug URLs won't go through NavigationThrottles so we have to
3805 // check them explicitly. See crbug.com/40605746.
Aaron Colwelle1908d982020-06-26 22:08:153806 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203807 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483808 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363809 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483810 }
3811
clamy21718cc22018-06-13 13:34:243812 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363813 return nullptr;
clamy21718cc22018-06-13 13:34:243814 }
3815
Antonio Sartori78a749f2020-11-30 12:03:393816 DCHECK(pending_entry_);
3817
clamy21718cc22018-06-13 13:34:243818 // Convert navigations to the current URL to a reload.
3819 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3820 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3821 // DevTools sometimes issues navigations to main frames that they do not
3822 // expect to see treated as reload, and it only works because they pass a
3823 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3824 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543825 ReloadType reload_type = params.reload_type;
3826 if (reload_type == ReloadType::NONE &&
3827 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043828 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243829 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243830 params.load_type ==
3831 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543832 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243833 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473834 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393835
3836 // If this is a reload of an existing FrameNavigationEntry and we had a
3837 // policy container for it, then we should copy it into the pending entry,
3838 // so that it is copied to the navigation request in
3839 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453840 FrameNavigationEntry* previous_frame_entry =
3841 GetLastCommittedEntry()->GetFrameEntry(node);
3842 if (previous_frame_entry &&
3843 previous_frame_entry->policy_container_policies()) {
3844 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3845 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393846 }
3847 }
3848
3849 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173850 // document, then we should copy the document polices from RenderFrameHost's
3851 // PolicyContainerHost. The NavigationRequest will create a new
3852 // PolicyContainerHost with the document policies from the |pending_entry_|,
3853 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3854 // the navigation. This way, we ensure that we keep enforcing the right
3855 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453856 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393857 if (node->current_frame_host() &&
3858 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193859 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163860 node->current_frame_host()
3861 ->policy_container_host()
3862 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233863 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393864 }
clamy21718cc22018-06-13 13:34:243865 }
3866
3867 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263868 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243869
Tsuyoshi Horo167ca6432022-03-09 05:16:393870 // This will be used to set the Navigation Timing API navigationStart
3871 // parameter for browser navigations in new tabs (intents, tabs opened through
3872 // "Open link in new tab"). If the navigation must wait on the current
3873 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3874 // will be updated when the BeforeUnload ack is received.
3875 const auto navigation_start_time = base::TimeTicks::Now();
Tsuyoshi Horo167ca6432022-03-09 05:16:393876
Camille Lamy5193caa2018-10-12 11:59:423877 std::unique_ptr<NavigationRequest> request =
3878 CreateNavigationRequestFromLoadParams(
3879 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143880 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393881 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
Charlie Reisf4d51f402025-05-23 18:00:493882 actual_navigation_start, navigation_start_time);
clamy21718cc22018-06-13 13:34:243883
3884 // If the navigation couldn't start, return immediately and discard the
3885 // pending NavigationEntry.
3886 if (!request) {
3887 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363888 return nullptr;
clamy21718cc22018-06-13 13:34:243889 }
3890
Camille Lamy5193caa2018-10-12 11:59:423891#if DCHECK_IS_ON()
3892 // Safety check that NavigationRequest and NavigationEntry match.
3893 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3894#endif
3895
Charlie Reisd3e4fef2025-05-20 02:04:173896 // Ensure that no re-entrant calls or discards of the pending entry occur
3897 // while calling `Navigator::Navigate` for a pending entry.
3898 ScopedPendingEntryReentrancyGuard reentrancy_guard(
3899 weak_factory_.GetSafeRef());
arthursonzogni66f711c2019-10-08 14:40:363900
Harkiran Bolariaba823e42021-05-21 18:30:363901 base::WeakPtr<NavigationHandle> created_navigation_handle(
3902 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053903 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243904
Harkiran Bolariaba823e42021-05-21 18:30:363905 return created_navigation_handle;
Charlie Reisd3e4fef2025-05-20 02:04:173906 // `reentrancy_guard` deleted here.
clamy21718cc22018-06-13 13:34:243907}
3908
Emmanuel Arias Soto9e159652025-05-16 07:53:553909FrameTreeNode* NavigationControllerImpl::GetTargetFrameTreeNodeForNavigation(
3910 const LoadURLParams& params) {
3911 FrameTreeNode* node = nullptr;
3912 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3913 node = params.frame_tree_node_id
3914 ? frame_tree_->FindByID(params.frame_tree_node_id)
3915 : frame_tree_->FindByName(params.frame_name);
3916 DCHECK(!node || &node->frame_tree() == &frame_tree());
3917 if (!node && params.frame_tree_node_id) {
3918 // If the specified FrameTreeNode exists in another FrameTree, the caller
3919 // is using the wrong NavigationController.
3920 CHECK(!FrameTreeNode::GloballyFindByID(params.frame_tree_node_id),
3921 base::NotFatalUntil::M140);
3922 }
3923 }
3924
3925 // If no FrameTreeNode was specified, navigate the main frame.
3926 if (!node) {
3927 node = frame_tree_->root();
3928 }
3929 return node;
3930}
3931
clamyea99ea12018-05-28 13:54:233932void NavigationControllerImpl::HandleRendererDebugURL(
3933 FrameTreeNode* frame_tree_node,
3934 const GURL& url) {
3935 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243936 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3937 // the renderer process is not live, unless it is the initial navigation
3938 // of the tab.
clamyea99ea12018-05-28 13:54:233939 if (!IsInitialNavigation()) {
3940 DiscardNonCommittedEntries();
3941 return;
3942 }
Fergal Dalyecd3b0202020-06-25 01:57:373943 // The current frame is always a main frame. If IsInitialNavigation() is
3944 // true then there have been no navigations and any frames of this tab must
3945 // be in the same renderer process. If that has crashed then the only frame
3946 // that can be revived is the main frame.
3947 frame_tree_node->render_manager()
3948 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233949 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223950
3951 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3952 // notification, so set is loading to true here to properly surface it when
3953 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313954 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223955 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223956 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223957 }
clamyea99ea12018-05-28 13:54:233958 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3959}
3960
clamy21718cc22018-06-13 13:34:243961std::unique_ptr<NavigationEntryImpl>
3962NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3963 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423964 const LoadURLParams& params,
3965 bool override_user_agent,
3966 bool should_replace_current_entry,
3967 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393968 // Browser initiated navigations might not have a blob_url_loader_factory set
3969 // in params even if the navigation is to a blob URL. If that happens, lookup
3970 // the correct url loader factory to use here.
3971 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483972 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473973 // Resolve the blob URL in the storage partition associated with the target
3974 // frame. This is the storage partition the URL will be loaded in, and only
3975 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393976 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473977 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393978 }
3979
clamy21718cc22018-06-13 13:34:243980 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443981 // extra_headers in params are \n separated; navigation entries want \r\n.
3982 std::string extra_headers_crlf;
3983 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243984
3985 // For subframes, create a pending entry with a corresponding frame entry.
3986 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453987 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243988 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083989 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243990 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373991 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213992 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3993 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393994 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163995 // a conversion of a new navigation into a reload, we will set the right
3996 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193997 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243998 } else {
3999 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:174000 // If `node` is the outermost main frame, it rewrites a virtual url in order
4001 // to adjust the original input url if needed. For inner frames such as
4002 // fenced frames or subframes, they don't rewrite urls as the urls are not
4003 // input urls by users.
4004 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:324005 scoped_refptr<SiteInstance> source_site_instance =
4006 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:374007 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:324008 if (source_site_instance && source_site_instance->HasProcess()) {
4009 source_process_site_url =
4010 source_site_instance->GetProcess()->GetProcessLock().site_url();
4011 }
clamy21718cc22018-06-13 13:34:244012 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:064013 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:324014 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:214015 params.transition_type, params.is_renderer_initiated,
4016 extra_headers_crlf, browser_context_, blob_url_loader_factory,
4017 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:244018 entry->set_source_site_instance(
4019 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
4020 entry->SetRedirectChain(params.redirect_chain);
4021 }
4022
4023 // Set the FTN ID (only used in non-site-per-process, for tests).
4024 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:244025 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:424026 entry->SetIsOverridingUserAgent(override_user_agent);
4027 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:544028 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:244029
clamy21718cc22018-06-13 13:34:244030 switch (params.load_type) {
4031 case LOAD_TYPE_DEFAULT:
4032 break;
4033 case LOAD_TYPE_HTTP_POST:
4034 entry->SetHasPostData(true);
4035 entry->SetPostData(params.post_data);
4036 break;
4037 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:544038 // LoadDataWithBaseURL is a special case that needs to assign both a base
4039 // URL and a virtual URL, while loading the actual content from a data
4040 // URL.
clamy21718cc22018-06-13 13:34:244041 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:544042 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:284043#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:244044 entry->SetDataURLAsString(params.data_url_as_string);
4045#endif
4046 entry->SetCanLoadLocalResources(params.can_load_local_resources);
4047 break;
Shu Yang112ad492024-07-25 17:11:544048#if BUILDFLAG(IS_ANDROID)
4049 case LOAD_TYPE_PDF_ANDROID:
4050 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
4051 // internal URL is used for the navigation URL.
4052 entry->SetVirtualURL(params.virtual_url_for_special_cases);
4053 break;
4054#endif
clamy21718cc22018-06-13 13:34:244055 }
4056
4057 // TODO(clamy): NavigationEntry is meant for information that will be kept
4058 // after the navigation ended and therefore is not appropriate for
4059 // started_from_context_menu. Move started_from_context_menu to
4060 // NavigationUIData.
4061 entry->set_started_from_context_menu(params.started_from_context_menu);
4062
4063 return entry;
4064}
4065
clamyea99ea12018-05-28 13:54:234066std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:424067NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
4068 FrameTreeNode* node,
4069 const LoadURLParams& params,
4070 bool override_user_agent,
4071 bool should_replace_current_entry,
4072 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:144073 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:424074 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574075 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:394076 FrameNavigationEntry* frame_entry,
Charlie Reise1d9b8182025-04-02 04:32:124077 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:224078 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:494079 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:454080 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584081 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:344082 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:374083 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574084 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:524085
4086 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
4087 // subframes have FrameNavigationEntries associated with them. Until then,
4088 // there may be cases where a subframe navigation is missing `frame_entry`
4089 // (e.g., see https://crbug.com/358084015).
4090
Nasko Oskov3c2f9e252019-01-10 17:45:534091 // All renderer-initiated navigations must have an initiator_origin.
4092 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:514093
Camille Lamy5193caa2018-10-12 11:59:424094 GURL url_to_load;
4095 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:324096
Camille Lamy2baa8022018-10-19 16:43:174097 // For main frames, rewrite the URL if necessary and compute the virtual URL
4098 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:264099 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424100 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:174101 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424102 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:424103
Shu Yang112ad492024-07-25 17:11:544104 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
4105 // that need to define a virtual URL to display, which differs from the
4106 // navigation URL.
4107 if (params.load_type == LOAD_TYPE_DATA) {
4108 virtual_url = params.virtual_url_for_special_cases;
4109 }
4110#if BUILDFLAG(IS_ANDROID)
4111 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
4112 virtual_url = params.virtual_url_for_special_cases;
4113 }
4114#endif
Camille Lamy5193caa2018-10-12 11:59:424115
Camille Lamy2baa8022018-10-19 16:43:174116 if (virtual_url.is_empty())
4117 virtual_url = url_to_load;
4118
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574119 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:284120
Aran Gilman249eb122019-12-02 23:32:464121 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
4122 // behavior: it is possible for two calls to RewriteUrlForNavigation to
4123 // return different results, leading to a different URL in the
4124 // NavigationRequest and FrameEntry. This will be fixed once we remove the
4125 // pending NavigationEntry, as we'll only make one call to
4126 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:524127 if (frame_entry) {
4128 VLOG_IF(1, (url_to_load != frame_entry->url()))
4129 << "NavigationRequest and FrameEntry have different URLs: "
4130 << url_to_load << " vs " << frame_entry->url();
4131 }
Camille Lamyb9ed3c52018-11-19 15:34:284132
Camille Lamy2baa8022018-10-19 16:43:174133 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424134 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174135 // NavigationRequest.
4136 } else {
4137 url_to_load = params.url;
4138 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244139 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174140 }
Camille Lamy5193caa2018-10-12 11:59:424141
Ehsan Karamad44fc72112019-02-26 18:15:474142 if (node->render_manager()->is_attaching_inner_delegate()) {
4143 // Avoid starting any new navigations since this node is now preparing for
4144 // attaching an inner delegate.
4145 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204146 }
Camille Lamy5193caa2018-10-12 11:59:424147
Alex Moshchuk99242832023-05-22 17:21:444148 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424149 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444150 }
Camille Lamy5193caa2018-10-12 11:59:424151
danakjd83d706d2020-11-25 22:11:124152 // Look for a pending commit that is to another document in this
4153 // FrameTreeNode. If one exists, then the last committed URL will not be the
4154 // current URL by the time this navigation commits.
4155 bool has_pending_cross_document_commit =
4156 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214157 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124158
Minggang Wangb9f3fa92021-07-01 15:30:314159 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494160 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524161 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494162 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134163 /*is_same_document_history_load=*/false,
4164 is_embedder_initiated_fenced_frame_navigation,
4165 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424166
4167 // Create the NavigationParams based on |params|.
4168
Hiroki Nakagawa4ed61282021-06-18 05:37:234169 bool is_view_source_mode = entry->IsViewSourceMode();
4170 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294171
Antonio Sartori6984c742021-08-26 08:03:414172 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294173
Hiroki Nakagawa4ed61282021-06-18 05:37:234174 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294175 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254176 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294177
Charlie Reisf21cd182024-08-09 21:44:524178 std::string page_state_data =
4179 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4180
Minggang Wangb9f3fa92021-07-01 15:30:314181 blink::mojom::CommonNavigationParamsPtr common_params =
4182 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214183 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514184 blink::mojom::Referrer::New(params.referrer.url,
4185 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214186 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514187 should_replace_current_entry, params.base_url_for_data_url,
Charlie Reise1d9b8182025-04-02 04:32:124188 actual_navigation_start_time, navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514189 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144190 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414191 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274192 false /* has_text_fragment_token */,
4193 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4194 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514195 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054196 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424197
Minggang Wangb9f3fa92021-07-01 15:30:314198 blink::mojom::CommitNavigationParamsPtr commit_params =
4199 blink::mojom::CommitNavigationParams::New(
Diana Quae845bf2025-04-03 20:12:374200 url::Origin(),
Ari Chivukulac7533522024-05-14 21:52:344201 // The correct storage key will be computed before committing the
4202 // navigation.
4203 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324204 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504205 std::vector<net::RedirectInfo>(), params.post_content_type,
4206 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524207 params.can_load_local_resources, page_state_data,
4208 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134209 /*intended_as_new_entry=*/true,
Charlie Reis99b2eba22025-01-31 19:18:574210 /*pending_history_list_index=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144211 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4212 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134213 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314214 params.should_clear_history_list,
4215 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224216 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134217 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514218 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284219#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134220 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144221#endif
Yoav Weiss8c573952022-11-17 17:35:134222 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154223 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134224 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074225 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134226 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4227 /*origin_agent_cluster=*/false,
4228 /*origin_agent_cluster_left_as_default=*/true,
4229 /*enabled_client_hints=*/
4230 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264231 /*is_cross_site_cross_browsing_context_group=*/false,
4232 /*should_have_sticky_user_activation=*/false,
4233 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134234 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014235 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134236 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584237 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134238 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134239 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284240 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134241 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444242 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424243 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374244 /*view_transition_state=*/std::nullopt,
4245 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054246 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464247 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374248 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054249 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094250 /*load_with_storage_access=*/
4251 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374252 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374253 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484254 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314255 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164256 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174257 node->current_frame_host()->GetCachedPermissionStatuses(),
Charlie Reiscdb798342025-02-14 22:04:464258 /*should_skip_screentshot=*/false,
Alex Moshchukd0d759c22025-05-09 18:18:354259 /*force_new_document_sequence_number=*/false,
4260 /*navigation_metrics_token=*/base::UnguessableToken::Create());
Xiaohan Wang7f8052e02022-01-14 18:44:284261#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424262 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564263 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424264 }
4265#endif
4266
Lucas Furukawa Gadania9c45682019-07-31 22:05:144267 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074268 commit_params->navigation_timing->system_entropy_at_navigation_start =
4269 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4270 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424271
Camille Lamy5193caa2018-10-12 11:59:424272 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4273 std::string extra_headers_crlf;
4274 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094275
Alex Moshchuk9321e6a2022-12-07 21:58:314276 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144277 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084278 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094279 params.initiator_frame_token, params.initiator_process_id,
4280 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214281 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294282 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454283 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344284 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034285 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134286
4287 if (!navigation_request) {
4288 return nullptr;
4289 }
4290
Yao Xiaodc5ed102019-06-04 19:19:094291 navigation_request->set_from_download_cross_origin_redirect(
4292 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554293 navigation_request->set_force_new_browsing_instance(
4294 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514295 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434296 if (params.force_no_https_upgrade) {
4297 navigation_request->set_force_no_https_upgrade();
4298 }
Yao Xiaodc5ed102019-06-04 19:19:094299 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424300}
4301
4302std::unique_ptr<NavigationRequest>
4303NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234304 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574305 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234306 FrameNavigationEntry* frame_entry,
4307 ReloadType reload_type,
4308 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434309 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374310 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334311 int initiator_process_id,
Charlie Reisf4d51f402025-05-23 18:00:494312 base::TimeTicks actual_navigation_start,
Arthur Sonzognic686e8f2024-01-11 08:36:374313 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134314 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344315 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234316 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434317 // We should never navigate to an existing initial NavigationEntry that is the
4318 // initial NavigationEntry for the initial empty document that hasn't been
4319 // overridden by the synchronous about:blank commit, to preserve previous
4320 // behavior where trying to reload when the main frame is on the initial empty
4321 // document won't result in a navigation.
4322 // See also https://crbug.com/1277414.
4323 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324324
clamyea99ea12018-05-28 13:54:234325 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234326
Ehsan Karamad44fc72112019-02-26 18:15:474327 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4328 // Avoid starting any new navigations since this node is now preparing for
4329 // attaching an inner delegate.
4330 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204331 }
4332
Alex Moshchuk99242832023-05-22 17:21:444333 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4334 dest_url)) {
clamyea99ea12018-05-28 13:54:234335 return nullptr;
4336 }
4337
clamyea99ea12018-05-28 13:54:234338 // This will be used to set the Navigation Timing API navigationStart
4339 // parameter for browser navigations in new tabs (intents, tabs opened through
4340 // "Open link in new tab"). If the navigation must wait on the current
4341 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4342 // will be updated when the BeforeUnload ack is received.
clamyea99ea12018-05-28 13:54:234343 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074344 const auto navigation_start_system_entropy =
4345 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4346 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234347
danakjd83d706d2020-11-25 22:11:124348 // Look for a pending commit that is to another document in this
4349 // FrameTreeNode. If one exists, then the last committed URL will not be the
4350 // current URL by the time this navigation commits.
4351 bool has_pending_cross_document_commit =
4352 frame_tree_node->render_manager()
4353 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494354 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214355 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124356
Minggang Wangb9f3fa92021-07-01 15:30:314357 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124358 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524359 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494360 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494361 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134362 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494363 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424364
4365 // A form submission may happen here if the navigation is a
4366 // back/forward/reload navigation that does a form resubmission.
4367 scoped_refptr<network::ResourceRequestBody> request_body;
4368 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394369 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504370 // entry. This way, it could be directly retrieved here. Right now, it is only
4371 // partially recovered when request.method == "POST" and request.body exists.
4372 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424373 if (frame_entry->method() == "POST") {
4374 request_body = frame_entry->GetPostData(&post_content_type);
4375 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304376 post_content_type = std::string(
4377 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504378 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424379 }
4380
4381 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314382 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514383 entry->ConstructCommonNavigationParams(
4384 *frame_entry, request_body, dest_url,
4385 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Charlie Reisf4d51f402025-05-23 18:00:494386 navigation_type, actual_navigation_start, navigation_start,
Charlie Reise1d9b8182025-04-02 04:32:124387 /*input_start=*/base::TimeTicks());
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514388 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554389 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424390
4391 // TODO(clamy): |intended_as_new_entry| below should always be false once
4392 // Reload no longer leads to this being called for a pending NavigationEntry
4393 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314394 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144395 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404396 *frame_entry, common_params->url, common_params->method,
4397 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144398 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534399 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484400 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134401 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074402 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144403 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074404 commit_params->navigation_timing->system_entropy_at_navigation_start =
4405 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4406 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164407 commit_params->initial_permission_statuses =
4408 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424409
W. James MacLeanb7d6092682022-10-05 15:23:264410 if (common_params->url.IsAboutSrcdoc()) {
4411 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4412 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594413 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264414 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334415 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314416 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144417 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434418 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334419 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4420 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374421 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294422 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4423 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474424 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234425}
4426
[email protected]d202a7c2012-01-04 07:53:474427void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214428 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274429 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404430
Takashi Toyoshimaea534ef22021-07-21 03:27:594431 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404432 // location bar will have up-to-date information about the security style
4433 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134434 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404435
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374436 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574437 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294438}
4439
initial.commit09911bf2008-07-26 23:55:294440// static
[email protected]d202a7c2012-01-04 07:53:474441size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234442 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154443 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214444 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234445}
4446
[email protected]d202a7c2012-01-04 07:53:474447void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224448 if (is_active && needs_reload_)
4449 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214450
4451 if (frame_tree_->is_primary();
4452 auto* cache = GetNavigationEntryScreenshotCache()) {
4453 cache->SetVisible(is_active);
4454 }
initial.commit09911bf2008-07-26 23:55:294455}
4456
[email protected]d202a7c2012-01-04 07:53:474457void NavigationControllerImpl::LoadIfNecessary() {
Charlie Reisf4d51f402025-05-23 18:00:494458 base::TimeTicks actual_navigation_start = base::TimeTicks::Now();
Rakina Zata Amnid605d462022-06-01 10:17:034459 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4460 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294461 if (!needs_reload_)
4462 return;
4463
Bo Liucdfa4b12018-11-06 00:21:444464 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4465 needs_reload_type_);
4466
initial.commit09911bf2008-07-26 23:55:294467 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004468 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294469 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004470 if (entry_replaced_by_post_commit_error_) {
4471 // If the current entry is a post commit error, we reload the entry it
4472 // replaced instead. We leave the error entry in place until a commit
4473 // replaces it, but the pending entry points to the original entry in the
4474 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4475 // case that pending_entry_ != entries_[pending_entry_index_].
4476 // Note that this handling is similar to
4477 // `NavigationControllerImpl::Reload()`.
4478 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4479 pending_entry_index_ = GetCurrentEntryIndex();
4480 NavigateToExistingPendingEntry(
4481 ReloadType::NONE,
4482 /*initiator_rfh=*/nullptr,
4483 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494484 /*navigation_api_key=*/nullptr, actual_navigation_start);
Xinghui Lue4e50be2024-05-15 21:46:004485 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134486 NavigateToExistingPendingEntry(
4487 ReloadType::NONE,
4488 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374489 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494490 /*navigation_api_key=*/nullptr, actual_navigation_start);
Rakina Zata Amnie2d31312022-11-18 03:38:454491 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434492 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274493 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344494 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134495 NavigateToExistingPendingEntry(
4496 ReloadType::NONE,
4497 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374498 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Charlie Reisf4d51f402025-05-23 18:00:494499 /*navigation_api_key=*/nullptr, actual_navigation_start);
avicc872d7242015-08-19 21:26:344500 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434501 // We should never navigate to an existing initial NavigationEntry that is
4502 // the initial NavigationEntry for the initial empty document that hasn't
4503 // been overridden by the synchronous about:blank commit, to preserve
4504 // legacy behavior where trying to reload when the main frame is on the
4505 // initial empty document won't result in a navigation. See also
4506 // https://crbug.com/1277414. If there is something to reload, the
4507 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4508 // it here.
avicc872d7242015-08-19 21:26:344509 needs_reload_ = false;
4510 }
initial.commit09911bf2008-07-26 23:55:294511}
4512
Kevin McNeeccca6172021-10-19 17:11:144513base::WeakPtr<NavigationHandle>
4514NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364515 RenderFrameHost* render_frame_host,
4516 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364517 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134518 RenderFrameHostImpl* rfhi =
4519 static_cast<RenderFrameHostImpl*>(render_frame_host);
Andrew Verge754c70a2025-04-17 17:19:194520 std::unique_ptr<NavigationRequest> navigation_request =
4521 CreateNavigationRequestForErrorPage(rfhi, url, error_page_html,
4522 /*is_post_commit_error_page=*/true);
4523 if (!navigation_request) {
Kevin McNeeccca6172021-10-19 17:11:144524 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114525 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584526
Rakina Zata Amni919b7922020-12-11 09:03:134527 FrameTreeNode* node = rfhi->frame_tree_node();
Charlie Reis09952ee2022-12-08 16:35:074528 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414529 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144530
Andrew Verge754c70a2025-04-17 17:19:194531 // TODO(crbug.com/406729265): LoadPostCommitErrorPage() does not initiate a
4532 // navigation via Navigator::Navigate(). We should fix that, so that
4533 // post-commit error page navigations don't bypass other important checks in
4534 // this function.
Kevin McNeeccca6172021-10-19 17:11:144535 // Calling BeginNavigation may destroy the NavigationRequest.
4536 base::WeakPtr<NavigationRequest> created_navigation_request(
4537 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414538 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144539 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414540}
4541
Andrew Verge754c70a2025-04-17 17:19:194542void NavigationControllerImpl::NavigateFrameToErrorPage(
4543 RenderFrameHostImpl* render_frame_host_impl,
4544 const GURL& url,
4545 const std::string& error_page_html) {
4546 // For now, this function can only be used for fenced frame roots. In the
4547 // future, it will be updated to work for any frame.
4548 // TODO(crbug.com/406729265): Implement this method for all types of frames,
4549 // including main frames and other subframe types.
4550 CHECK(render_frame_host_impl->IsFencedFrameRoot());
4551
4552 std::unique_ptr<NavigationRequest> navigation_request =
4553 CreateNavigationRequestForErrorPage(render_frame_host_impl, url,
4554 error_page_html,
4555 /*is_post_commit_error_page=*/false);
4556 if (!navigation_request) {
4557 return;
4558 }
4559
4560 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
4561 node->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
4562}
4563
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574564void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214565 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094566 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154567 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144568 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294569}
4570
[email protected]d202a7c2012-01-04 07:53:474571void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364572 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584573 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474574 // represent a no-committed-entry state.
4575 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364576 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584577 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474578 // if `entries_` contains pre-existing entries from the NavigationController
4579 // before restore, which would not be removed and will be at the front of the
4580 // entries list, causing the index to be off by the amount of pre-existing
4581 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294582 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294583}
[email protected]765b35502008-08-21 00:51:204584
arthursonzogni69a6a1b2019-09-17 09:23:004585void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004586 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4587}
4588
4589void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4590 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474591 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104592 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4593 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294594 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474595 return;
Michael Thiessenc5676d22019-09-25 22:32:104596 }
avi45a72532015-04-07 21:01:454597 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314598
4599 if (!delegate_)
4600 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374601 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484602}
4603
avi7c6f35e2015-05-08 17:52:384604int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4605 int nav_entry_id) const {
4606 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4607 if (entries_[i]->GetUniqueID() == nav_entry_id)
4608 return i;
4609 }
4610 return -1;
4611}
4612
[email protected]d202a7c2012-01-04 07:53:474613void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574614 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254615 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574616 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594617 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254618 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374619 // Normally, cloning a NavigationEntryImpl results in sharing
4620 // FrameNavigationEntries between the original and the clone. However, when
4621 // cloning from a different NavigationControllerImpl, we want to fork the
4622 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374623 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594624 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254625 }
Rakina Zata Amnie2d31312022-11-18 03:38:454626 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274627 DCHECK(pending_entry_index_ == -1 ||
4628 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254629}
[email protected]c5b88d82012-10-06 17:03:334630
4631void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184632 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334633 get_timestamp_callback_ = get_timestamp_callback;
4634}
[email protected]8ff00d72012-10-23 19:12:214635
Shivani Sharmaffb32b82019-04-09 16:58:474636// History manipulation intervention:
4637void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474638 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564639 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404640 bool is_renderer_initiated,
4641 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564642 // Note that for a subframe,
4643 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454644 // gesture happened in any subframe (propagated to main frame) or in the main
4645 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564646 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274647 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474648 return;
4649 }
4650 if (last_committed_entry_index_ == -1)
4651 return;
4652
Shivani Sharmac4cc8922019-04-18 03:11:174653 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474654
Alexander Timine3ec4192020-04-20 16:39:404655 // Log UKM with the URL we are navigating away from.
4656 ukm::builders::HistoryManipulationIntervention(
4657 previous_page_load_ukm_source_id)
4658 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474659}
4660
Shivani Sharmac4cc8922019-04-18 03:11:174661void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4662 int reference_index,
4663 bool skippable) {
4664 auto* reference_entry = GetEntryAtIndex(reference_index);
4665 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4666
4667 int64_t document_sequence_number =
4668 reference_entry->root_node()->frame_entry->document_sequence_number();
4669 for (int index = 0; index < GetEntryCount(); index++) {
4670 auto* entry = GetEntryAtIndex(index);
4671 if (entry->root_node()->frame_entry->document_sequence_number() ==
4672 document_sequence_number) {
4673 entry->set_should_skip_on_back_forward_ui(skippable);
4674 }
4675 }
4676}
4677
arthursonzogni66f711c2019-10-08 14:40:364678std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4679NavigationControllerImpl::ReferencePendingEntry() {
4680 DCHECK(pending_entry_);
4681 auto pending_entry_ref =
4682 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4683 pending_entry_refs_.insert(pending_entry_ref.get());
4684 return pending_entry_ref;
4685}
4686
4687void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4688 // Ignore refs that don't correspond to the current pending entry.
4689 auto it = pending_entry_refs_.find(ref);
4690 if (it == pending_entry_refs_.end())
4691 return;
4692 pending_entry_refs_.erase(it);
4693
4694 if (!pending_entry_refs_.empty())
4695 return;
4696
4697 // The pending entry may be deleted before the last PendingEntryRef.
4698 if (!pending_entry_)
4699 return;
4700
4701 // We usually clear the pending entry when the matching NavigationRequest
4702 // fails, so that an arbitrary URL isn't left visible above a committed page.
4703 //
4704 // However, we do preserve the pending entry in some cases, such as on the
4705 // initial navigation of an unmodified blank tab. We also allow the delegate
4706 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4707 // user edit the URL and try again. This may be useful in cases that the
4708 // committed page cannot be attacker-controlled. In these cases, we still
4709 // allow the view to clear the pending entry and typed URL if the user
4710 // requests (e.g., hitting Escape with focus in the address bar).
4711 //
4712 // Do not leave the pending entry visible if it has an invalid URL, since this
4713 // might be formatted in an unexpected or unsafe way.
4714 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364715 bool should_preserve_entry =
4716 (pending_entry_ == GetVisibleEntry()) &&
4717 pending_entry_->GetURL().is_valid() &&
4718 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4719 if (should_preserve_entry)
4720 return;
4721
4722 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374723 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364724}
4725
Titouan Rigoudy6ec70402021-02-02 15:42:194726std::unique_ptr<PolicyContainerPolicies>
4727NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394728 RenderFrameHostImpl* rfh,
4729 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214730 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174731 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214732 if (navigation_encountered_error) {
4733 // We should never reload the policy container of an error page from
4734 // history, see https://crbug.com/364773822.
4735 return nullptr;
4736 }
4737
Antonio Sartori78a749f2020-11-30 12:03:394738 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454739 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394740 FrameNavigationEntry* previous_frame_entry =
4741 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4742
Alison Gale770f3fc2024-04-27 00:39:584743 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394744 // ensure we always have a FrameNavigationEntry here.
4745 if (!previous_frame_entry)
4746 return nullptr;
4747
Titouan Rigoudy6ec70402021-02-02 15:42:194748 const PolicyContainerPolicies* previous_policies =
4749 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394750
Titouan Rigoudy6ec70402021-02-02 15:42:194751 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394752 return nullptr;
4753
4754 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234755 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394756 }
4757
Titouan Rigoudy72f892d2022-05-02 18:21:234758 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394759}
4760
Charlie Reis99b2eba22025-01-31 19:18:574761void NavigationControllerImpl::BroadcastHistoryIndexAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504762 OPTIONAL_TRACE_EVENT2(
Charlie Reis99b2eba22025-01-31 19:18:574763 "content", "NavigationControllerImpl::BroadcastHistoryIndexAndLength",
4764 "history_index", GetLastCommittedEntryIndex(), "history_length",
Hayato Ito2c8c08d02021-06-23 03:38:434765 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504766
Charlie Reis99b2eba22025-01-31 19:18:574767 int history_index = GetLastCommittedEntryIndex();
Kevin McNee7705fe82024-11-07 18:56:314768 int history_length = GetEntryCount();
Charlie Reis99b2eba22025-01-31 19:18:574769 auto callback = [history_index, history_length](RenderViewHostImpl* rvh) {
Kevin McNee7705fe82024-11-07 18:56:314770 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
Charlie Reis99b2eba22025-01-31 19:18:574771 broadcast->SetHistoryIndexAndLength(history_index, history_length);
Kevin McNee7705fe82024-11-07 18:56:314772 }
4773 };
Ali Hijazid87307d2022-11-07 20:15:034774 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504775}
4776
4777void NavigationControllerImpl::DidAccessInitialMainDocument() {
4778 // We may have left a failed browser-initiated navigation in the address bar
4779 // to let the user edit it and try again. Clear it now that content might
4780 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034781 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504782 DiscardPendingEntry(false);
4783
4784 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374785 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504786}
4787
4788void NavigationControllerImpl::UpdateStateForFrame(
4789 RenderFrameHostImpl* rfhi,
4790 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564791 OPTIONAL_TRACE_EVENT1("content",
4792 "NavigationControllerImpl::UpdateStateForFrame",
4793 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504794 // The state update affects the last NavigationEntry associated with the given
4795 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4796 // in the case of an UpdateState from a frame being swapped out). We track
4797 // which entry this is in the RenderFrameHost's nav_entry_id.
4798 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4799 if (!entry)
4800 return;
4801
4802 FrameNavigationEntry* frame_entry =
4803 entry->GetFrameEntry(rfhi->frame_tree_node());
4804 if (!frame_entry)
4805 return;
4806
4807 // The SiteInstance might not match if we do a cross-process navigation with
4808 // replacement (e.g., auto-subframe), in which case the swap out of the old
4809 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4810 // has already been replaced and destroyed.
4811 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4812 return;
4813
4814 if (page_state == frame_entry->page_state())
4815 return; // Nothing to update.
4816
4817 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4818
4819 // The document_sequence_number and item_sequence_number recorded in the
4820 // FrameNavigationEntry should not differ from the one coming with the update,
4821 // since it must come from the same document. Do not update it if a difference
4822 // is detected, as this indicates that |frame_entry| is not the correct one.
4823 blink::ExplodedPageState exploded_state;
4824 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4825 return;
4826
4827 if (exploded_state.top.document_sequence_number !=
4828 frame_entry->document_sequence_number() ||
4829 exploded_state.top.item_sequence_number !=
4830 frame_entry->item_sequence_number()) {
4831 return;
4832 }
4833
4834 frame_entry->SetPageState(page_state);
4835 NotifyEntryChanged(entry);
4836}
4837
Nate Chapina2c881f52023-11-07 17:02:094838namespace {
4839
4840// The caller is responsible for ensuring the entry is same-origin to the
4841// origin to be committed.
4842blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4843 FrameNavigationEntry* frame_entry,
4844 int64_t pending_document_sequence_number) {
4845 blink::ExplodedPageState exploded_state;
4846 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4847 &exploded_state)) {
4848 return nullptr;
4849 }
4850 blink::ExplodedFrameState frame_state = exploded_state.top;
4851
4852 // If the document represented by this FNE hid its full url from appearing in
4853 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4854 // in the navigation API as well (unless we're navigating to that document).
4855 std::u16string url;
4856 if (pending_document_sequence_number ==
4857 frame_entry->document_sequence_number() ||
4858 !frame_entry->protect_url_in_navigation_api()) {
4859 url = frame_state.url_string.value_or(std::u16string());
4860 }
4861
4862 return blink::mojom::NavigationApiHistoryEntry::New(
4863 frame_state.navigation_api_key.value_or(std::u16string()),
4864 frame_state.navigation_api_id.value_or(std::u16string()), url,
4865 frame_state.item_sequence_number, frame_state.document_sequence_number,
4866 frame_state.navigation_api_state);
4867}
4868
4869} // namespace
4870
Domenic Denicolacd30f5f82022-03-16 21:48:014871std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4872NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574873 Direction direction,
4874 int entry_index,
4875 const url::Origin& pending_origin,
4876 FrameTreeNode* node,
4877 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304878 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094879 int64_t pending_document_sequence_number,
4880 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014881 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454882 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174883 // Don't process the initial entry.
4884 DCHECK_EQ(GetEntryCount(), 1);
4885 return entries;
4886 }
Nate Chapind1fe3612021-04-16 20:45:574887 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304888 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574889 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4890 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094891 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574892 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414893 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574894 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014895 // An entry should only appear in the navigation API entries if it is for
4896 // the same origin as the document being committed. Check the committed
4897 // origin, or if that is not available (during restore), check against the
4898 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584899 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094900 // once we can be sure that entries with the same ISN will never be
4901 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414902 url::Origin frame_entry_origin =
4903 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4904 frame_entry->url(),
4905 frame_entry->initiator_origin().value_or(url::Origin())));
4906 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574907 break;
4908 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4909 continue;
Nate Chapina2c881f52023-11-07 17:02:094910 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4911 ToNavigationApiHistoryEntry(frame_entry,
4912 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304913 DCHECK(entry->url.empty() ||
4914 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574915 entries.push_back(std::move(entry));
4916 previous_item_sequence_number = frame_entry->item_sequence_number();
4917 }
4918 }
4919 // If |entries| was constructed by iterating backwards from
4920 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4921 // earliest-at-the-front. Reverse it.
4922 if (direction == Direction::kBack)
4923 std::reverse(entries.begin(), entries.end());
4924 return entries;
4925}
4926
Domenic Denicolacd30f5f82022-03-16 21:48:014927blink::mojom::NavigationApiHistoryEntryArraysPtr
4928NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554929 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574930 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404931 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444932 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404933 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574934
Nate Chapind1fe3612021-04-16 20:45:574935 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554936 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574937
Nate Chapine82339d02022-05-03 23:48:254938 // NOTE: |entry_index| is the index where this entry will commit if no
4939 // modifications are made between now and DidCommitNavigation. This is used to
4940 // walk |entries_| and determine which entries should be exposed by the
4941 // navigation API. It is important to calculate this correctly, because blink
4942 // will cancel a same-document history commit if it's not present in the
4943 // entries blink knows about.
4944 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574945 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304946 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254947 bool will_create_new_entry = false;
4948 if (GetPendingEntryIndex() != -1) {
4949 entry_index = GetPendingEntryIndex();
4950 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4951 pending_item_sequence_number = frame_entry->item_sequence_number();
4952 pending_document_sequence_number =
4953 frame_entry->document_sequence_number();
4954 }
4955 } else if (request &&
4956 !NavigationTypeUtils::IsReload(
4957 request->common_params().navigation_type) &&
4958 !NavigationTypeUtils::IsHistory(
4959 request->common_params().navigation_type) &&
4960 !request->common_params().should_replace_current_entry &&
4961 !request->common_params()
4962 .is_history_navigation_in_new_child_frame) {
4963 will_create_new_entry = true;
4964 entry_index = GetLastCommittedEntryIndex() + 1;
4965 // Don't set pending_item_sequence_number or
4966 // pending_document_sequence_number in this case - a new unique isn/dsn will
4967 // be calculated in the renderer later.
4968 } else if (GetLastCommittedEntryIndex() != -1) {
4969 entry_index = GetLastCommittedEntryIndex();
4970 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574971 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304972 pending_document_sequence_number =
4973 frame_entry->document_sequence_number();
4974 }
Nate Chapind1fe3612021-04-16 20:45:574975 }
4976
Domenic Denicolacd30f5f82022-03-16 21:48:014977 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254978 if (entry_index == -1) {
4979 // TODO(rakina): Exit early when there is no last committed entry.
4980 // Remove when InitialNavigationEntry ships.
4981 return entry_arrays;
4982 }
4983
Nate Chapina2c881f52023-11-07 17:02:094984 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014985 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574986 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094987 pending_item_sequence_number, pending_document_sequence_number,
4988 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574989
4990 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094991 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574992 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014993 entry_arrays->forward_entries =
4994 PopulateSingleNavigationApiHistoryEntryVector(
4995 Direction::kForward, entry_index, pending_origin, node,
4996 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094997 pending_document_sequence_number, forwardmost_index);
4998 }
4999
5000 // If the previous entry is within the block of contiguous entries being
5001 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:255002 FrameNavigationEntry* previous_entry = nullptr;
5003 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:055004 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
5005 .initiator_frame_tree_node_id();
5006 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:255007 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
5008 previous_entry = initiator_node->frame_tree()
5009 .controller()
5010 .GetLastCommittedEntry()
5011 ->GetFrameEntry(initiator_node);
5012 }
5013 } else if (GetLastCommittedEntryIndex() != -1 &&
5014 GetLastCommittedEntryIndex() >= backmost_index &&
5015 GetLastCommittedEntryIndex() <= forwardmost_index) {
5016 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
5017 }
5018 if (previous_entry) {
5019 url::Origin previous_entry_origin =
5020 previous_entry->committed_origin().value_or(url::Origin::Resolve(
5021 previous_entry->url(),
5022 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:585023 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:255024 // once we can be sure that entries with the same ISN will never be
5025 // cross-origin.
5026 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
5027 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
5028 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:095029 }
Nate Chapind1fe3612021-04-16 20:45:575030 }
Nate Chapinc06cf80a2023-11-18 01:12:255031
Nate Chapin4e657a472022-02-06 03:38:375032 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:575033}
5034
Nate Chapinfbfe5af2021-06-10 17:22:085035NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:575036NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085037 FrameNavigationEntry* current_entry,
5038 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:575039 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:085040 if (!target_entry || !target_entry->committed_origin())
5041 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:085042 if (!current_entry->committed_origin()->IsSameOriginWith(
5043 *target_entry->committed_origin())) {
5044 return HistoryNavigationAction::kStopLooking;
5045 }
5046
5047 // NOTE: We don't actually care between kSameDocument and
5048 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:575049 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:085050 return HistoryNavigationAction::kDifferentDocument;
5051 return HistoryNavigationAction::kKeepLooking;
5052}
5053
Domenic Denicolacc094fb2022-03-16 23:40:575054void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:205055 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:375056 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:145057 soft_navigation_heuristics_task_id,
Charlie Reisf4d51f402025-05-23 18:00:495058 const std::string& key,
5059 base::TimeTicks actual_navigation_start) {
Nate Chapinbf682fa32022-09-26 22:41:205060 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:085061 FrameNavigationEntry* current_entry =
5062 GetLastCommittedEntry()->GetFrameEntry(node);
Nate Chapin0dbc93af2025-03-28 17:02:525063 if (!current_entry || !current_entry->committed_origin()) {
Nate Chapinfbfe5af2021-06-10 17:22:085064 return;
Nate Chapin0dbc93af2025-03-28 17:02:525065 }
Nate Chapinfbfe5af2021-06-10 17:22:085066
Alison Gale47d1537d2024-04-19 21:31:465067 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:135068 // when `navigation.traverseTo()` is called.
5069
Nate Chapinfbfe5af2021-06-10 17:22:085070 // We want to find the nearest matching entry that is contiguously
5071 // same-instance and same-origin. Check back first, then forward.
5072 // TODO(japhet): Link spec here once it exists.
5073 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:575074 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085075 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5076 if (result == HistoryNavigationAction::kStopLooking)
5077 break;
5078 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495079 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5080 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085081 return;
5082 }
5083 }
5084 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:575085 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:085086 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
5087 if (result == HistoryNavigationAction::kStopLooking)
5088 break;
5089 if (result != HistoryNavigationAction::kKeepLooking) {
Charlie Reisf4d51f402025-05-23 18:00:495090 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key,
5091 actual_navigation_start);
Nate Chapinfbfe5af2021-06-10 17:22:085092 return;
5093 }
5094 }
Nate Chapinbf682fa32022-09-26 22:41:205095
5096 // If we fall through to here, a matching NavigationEntry couldn't be found.
5097 // Notify the renderer that the navigation was cancelled.
5098 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
5099 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:085100}
5101
Domenic Denicolacc094fb2022-03-16 23:40:575102bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:305103 network::mojom::ReferrerPolicy referrer_policy) {
5104 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
5105 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
5106}
5107
shivanigithubf405bf0d2021-11-05 17:58:335108bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
5109 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:315110 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:335111 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:545112 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:465113 // The preview mode appears as prerendered page in renderers, and
5114 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:035115 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:515116 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:335117 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:545118}
5119
Julie Jeongeun Kim0e242242022-11-30 10:45:095120void NavigationControllerImpl::DidChangeReferrerPolicy(
5121 FrameTreeNode* node,
5122 network::mojom::ReferrerPolicy referrer_policy) {
5123 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
5124 if (!entry)
5125 return;
5126
5127 // The FrameNavigationEntry may want to change whether to protect its url
5128 // in the navigation API when the referrer policy changes.
5129 entry->set_protect_url_in_navigation_api(
5130 ShouldProtectUrlInNavigationApi(referrer_policy));
5131}
5132
Minoru Chikamune646eba42025-04-14 01:25:035133void NavigationControllerImpl::CheckPotentialNavigationReentrancy() {
Minoru Chikamune13ab4de2025-05-14 21:54:075134 if (can_be_in_navigate_to_pending_entry_) {
Minoru Chikamune646eba42025-04-14 01:25:035135 // This DumpWithoutCrashing is an investigation code for
5136 // https://crbug.com/396998476.
5137 base::debug::DumpWithoutCrashing();
5138 }
5139}
5140
Andrew Verge754c70a2025-04-17 17:19:195141std::unique_ptr<NavigationRequest>
5142NavigationControllerImpl::CreateNavigationRequestForErrorPage(
5143 RenderFrameHostImpl* render_frame_host_impl,
5144 const GURL& url,
5145 const std::string& error_page_html,
5146 bool is_post_commit_error_page) {
5147 // Only active documents can load error pages:
5148 // - If the document is in pending deletion, the browser already committed to
5149 // destroying this RenderFrameHost so ignore loading the error page.
5150 // - If the document is in back-forward cache, it's not allowed to navigate as
5151 // it should remain frozen. Ignore the request and evict the document from
5152 // back-forward cache.
5153 // - If the document is prerendering, it can navigate but when loading error
5154 // pages, cancel prerendering.
5155 if (render_frame_host_impl->IsInactiveAndDisallowActivation(
5156 is_post_commit_error_page
5157 ? DisallowActivationReasonId::kLoadPostCommitErrorPage
5158 : DisallowActivationReasonId::kBrowserInitiatedErrorPage)) {
5159 return nullptr;
5160 }
5161
5162 FrameTreeNode* node = render_frame_host_impl->frame_tree_node();
5163
5164 blink::mojom::CommonNavigationParamsPtr common_params =
5165 blink::CreateCommonNavigationParams();
5166 // |url| might be empty, such as when this method is called before
5167 // the frame actually committed (e.g. iframe with "src" set to a
5168 // slow-responding URL). We should rewrite the URL to about:blank in this
5169 // case, as the renderer will only think a page is an error page if it has a
5170 // non-empty unreachable URL.
5171 common_params->url = url.is_empty() ? GURL("about:blank") : url;
5172
5173 // Loading an error page via LoadPostCommitErrorPage() performs a temporary
5174 // replacement of the entire NavigationEntry and swaps it back in later.
5175 // All other error page types should permanently replace the current entry.
5176 if (!is_post_commit_error_page) {
5177 common_params->should_replace_current_entry = true;
5178 }
5179
5180 blink::mojom::CommitNavigationParamsPtr commit_params =
5181 blink::CreateCommitNavigationParams();
5182 commit_params->original_url = common_params->url;
5183
5184 commit_params->navigation_timing->system_entropy_at_navigation_start =
5185 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
5186 node, blink::mojom::SystemEntropy::kNormal);
5187
5188 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
5189 // error pages.
5190 commit_params->frame_policy = node->pending_frame_policy();
5191
5192 std::unique_ptr<NavigationRequest> navigation_request =
5193 NavigationRequest::CreateBrowserInitiated(
5194 node, std::move(common_params), std::move(commit_params),
5195 false /* was_opener_suppressed */, "" /* extra_headers */,
5196 nullptr /* frame_entry */, nullptr /* entry */,
5197 false /* is_form_submission */, nullptr /* navigation_ui_data */,
5198 std::nullopt /* impression */, false /* is_pdf */);
5199 if (is_post_commit_error_page) {
5200 navigation_request->set_browser_initiated_error_navigation_type(
5201 NavigationRequest::BrowserInitiatedErrorNavigationType::kPostCommit);
5202 } else {
5203 navigation_request->set_browser_initiated_error_navigation_type(
5204 NavigationRequest::BrowserInitiatedErrorNavigationType::kRegular);
5205 }
5206 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
5207 navigation_request->set_error_page_html(error_page_html);
5208 return navigation_request;
5209}
5210
[email protected]8ff00d72012-10-23 19:12:215211} // namespace content