blob: 924d7433684d78aeaa5c77be37fcf079309bca98 [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"
Charlie Reis23c26da2022-01-29 00:57:4747#include "base/numerics/safe_conversions.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3948#include "base/strings/escape.h"
[email protected]348fbaac2013-06-11 06:31:5149#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0050#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3751#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0052#include "base/trace_event/optional_trace_event.h"
ssid3e765612015-01-28 04:03:4253#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0854#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5955#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2856#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1857#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3958#include "content/browser/blob_storage/chrome_blob_storage_context.h"
William Liu055a3542023-04-02 17:21:1959#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3160#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4161#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0462#include "content/browser/dom_storage/session_storage_namespace_impl.h"
Nate Chapinc06cf80a2023-11-18 01:12:2563#include "content/browser/preloading/prerender/prerender_host.h"
Sharon Yang242ef822023-05-15 21:07:3264#include "content/browser/process_lock.h"
Mingyu Lei68f34412023-08-21 07:31:3765#include "content/browser/renderer_host/back_forward_cache_impl.h"
danakjc492bf82020-09-09 20:02:4466#include "content/browser/renderer_host/debug_urls.h"
67#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0068#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3369#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4470#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5771#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4472#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1973#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
74#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
Khushal Sagar94ea2dc2024-08-06 17:15:2675#include "content/browser/renderer_host/navigation_transitions/navigation_transition_config.h"
danakjc492bf82020-09-09 20:02:4476#include "content/browser/renderer_host/navigator.h"
Takashi Toyoshima4dad2c12023-11-13 10:04:4677#include "content/browser/renderer_host/page_delegate.h"
danakjc492bf82020-09-09 20:02:4478#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0079#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0780#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3281#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3382#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4283#include "content/common/content_constants_internal.h"
Rakina Zata Amni84a859df2024-06-07 15:56:3284#include "content/common/content_navigation_policy.h"
Nate Chapind1fe3612021-04-16 20:45:5785#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5186#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1187#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1988#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1189#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4690#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0091#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4792#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5893#include "content/public/browser/render_widget_host.h"
94#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1095#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3496#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1997#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3898#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1099#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47100#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43101#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59102#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36103#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57104#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18105#include "services/metrics/public/cpp/ukm_builders.h"
106#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17107#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37108#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44109#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58110#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39111#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30112#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21113#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06114#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43115#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50116#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31117#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51118#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46119#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26120#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29121
[email protected]8ff00d72012-10-23 19:12:21122namespace content {
[email protected]e9ba4472008-09-14 15:42:43123namespace {
124
125// Invoked when entries have been pruned, or removed. For example, if the
126// current entries are [google, digg, yahoo], with the current entry google,
127// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47128void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50129 int index,
[email protected]c12bf1a12008-09-17 16:28:49130 int count) {
[email protected]8ff00d72012-10-23 19:12:21131 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50132 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49133 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14134 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43135}
136
[email protected]e9ba4472008-09-14 15:42:43137// Configure all the NavigationEntries in entries for restore. This resets
138// the transition type to reload and makes sure the content state isn't empty.
139void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57140 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48141 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47142 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43143 // Use a transition type of reload so that we don't incorrectly increase
144 // the typed count.
Lei Zhang96031532019-10-10 19:05:47145 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
146 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43147 }
148}
149
[email protected]bf70edce2012-06-20 22:32:22150// Determines whether or not we should be carrying over a user agent override
151// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57152bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22153 return last_entry && last_entry->GetIsOverridingUserAgent();
154}
155
Camille Lamy5193caa2018-10-12 11:59:42156// Determines whether to override user agent for a navigation.
157bool ShouldOverrideUserAgent(
158 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57159 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42160 switch (override_user_agent) {
161 case NavigationController::UA_OVERRIDE_INHERIT:
162 return ShouldKeepOverride(last_committed_entry);
163 case NavigationController::UA_OVERRIDE_TRUE:
164 return true;
165 case NavigationController::UA_OVERRIDE_FALSE:
166 return false;
Camille Lamy5193caa2018-10-12 11:59:42167 }
Peter Boströmfc7ddc182024-10-31 19:37:21168 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42169}
170
Rakina Zata Amni312822d72021-06-04 16:13:37171// Returns true if this navigation should be treated as a reload. For e.g.
Liang Zhao0351d762024-11-13 00:10:07172// clicking on a link which results in a navigation to the last committed URL
173// (but wasn't converted to do a replacement navigation in the renderer), etc.
174// This intentionally excludes navigating to the last committed URL via the
175// address bar, so that the current scroll position is not restored.
Fergal Daly766177d2020-07-07 07:54:04176// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
177// |base_url_for_data_url|, |transition_type| correspond to the new navigation
178// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
179// navigation that committed.
180bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
181 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57182 const GURL& virtual_url,
183 const GURL& base_url_for_data_url,
184 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57185 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37186 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57187 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37188 // Navigations intended to do a replacement shouldn't be converted to do a
189 // reload.
190 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28191 return false;
clamy0a656e42018-02-06 18:18:28192 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45193 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55194 return false;
195
arthursonzogni7a8243682017-12-14 16:41:42196 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28197 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42198 return false;
199
Liang Zhao0351d762024-11-13 00:10:07200 // Same URL navigations from the address bar should only be treated as reloads
201 // if PAGE_TRANSITION_RELOAD is set (not for PAGE_TRANSITION_TYPED or
202 // PAGE_TRANSITION_LINK). In non-address-bar cases, PAGE_TRANSITION_TYPED
203 // and PAGE_TRANSITION_LINK can be treated as reloads.
clamy0a656e42018-02-06 18:18:28204 bool transition_type_can_be_converted = false;
Liang Zhao0351d762024-11-13 00:10:07205 if (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
206 if (ui::PageTransitionCoreTypeIs(transition_type,
207 ui::PAGE_TRANSITION_RELOAD)) {
208 transition_type_can_be_converted = true;
209 }
210 } else {
211 if (ui::PageTransitionCoreTypeIs(transition_type,
212 ui::PAGE_TRANSITION_TYPED) ||
213 ui::PageTransitionCoreTypeIs(transition_type,
214 ui::PAGE_TRANSITION_LINK)) {
215 transition_type_can_be_converted = true;
216 }
ananta3bdd8ae2016-12-22 17:11:55217 }
clamy0a656e42018-02-06 18:18:28218 if (!transition_type_can_be_converted)
219 return false;
220
221 // This check is required for cases like view-source:, etc. Here the URL of
222 // the navigation entry would contain the url of the page, while the virtual
223 // URL contains the full URL including the view-source prefix.
224 if (virtual_url != last_committed_entry->GetVirtualURL())
225 return false;
226
Fergal Daly766177d2020-07-07 07:54:04227 // Check that the URLs match.
228 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
229 // If there's no frame entry then by definition the URLs don't match.
230 if (!frame_entry)
231 return false;
232
233 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28234 return false;
235
236 // This check is required for Android WebView loadDataWithBaseURL. Apps
237 // can pass in anything in the base URL and we need to ensure that these
238 // match before classifying it as a reload.
239 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
240 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
241 return false;
ananta3bdd8ae2016-12-22 17:11:55242 }
243
clamy0a656e42018-02-06 18:18:28244 // Skip entries with SSL errors.
245 if (last_committed_entry->ssl_error())
246 return false;
247
248 // Don't convert to a reload when the last navigation was a POST or the new
249 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04250 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28251 return false;
252
253 return true;
ananta3bdd8ae2016-12-22 17:11:55254}
255
Arthur Sonzognic686e8f2024-01-11 08:36:37256std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12257 const mojom::DidCommitProvisionalLoadParams& params,
258 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32259 // Error pages commit in an opaque origin, yet have the real URL that resulted
260 // in an error as the |params.url|. Since successful reload of an error page
261 // should commit in the correct origin, setting the opaque origin on the
262 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17263 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37264 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32265
Arthur Sonzognic686e8f2024-01-11 08:36:37266 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32267}
268
Alex Moshchuk99242832023-05-22 17:21:44269bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42270 const GURL& virtual_url,
271 const GURL& dest_url) {
272 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44273 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
274 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42275 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
276 << virtual_url.possibly_invalid_spec();
277 return false;
278 }
279
280 // Don't attempt to navigate to non-empty invalid URLs.
281 if (!dest_url.is_valid() && !dest_url.is_empty()) {
282 LOG(WARNING) << "Refusing to load invalid URL: "
283 << dest_url.possibly_invalid_spec();
284 return false;
285 }
286
287 // The renderer will reject IPC messages with URLs longer than
288 // this limit, so don't attempt to navigate with a longer URL.
289 if (dest_url.spec().size() > url::kMaxURLChars) {
290 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
291 << " characters.";
292 return false;
293 }
294
Aaron Colwell33109c592020-04-21 21:31:19295 // Reject renderer debug URLs because they should have been handled before
296 // we get to this point. This check handles renderer debug URLs
297 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
298 // provides defense-in-depth if a renderer debug URL manages to get here via
299 // some other path. We want to reject the navigation here so it doesn't
300 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30301 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19302 LOG(WARNING) << "Refusing to load renderer debug URL: "
303 << dest_url.possibly_invalid_spec();
304 return false;
305 }
306
Alex Moshchuk99242832023-05-22 17:21:44307 // Guests only support navigations to known-safe schemes. This check already
308 // exists in the extensions layer, where it also dispatches proper events to
309 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
310 // for defense-in-depth to ensure that no other places in the codebase
311 // accidentally navigate guests to schemes such as WebUI, which is not
312 // supported. See https://crbug.com/1444221.
313 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
314 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
315 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
316 !dest_url.SchemeIs(url::kAboutScheme)) {
317 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
318 << dest_url.possibly_invalid_spec();
319 return false;
320 }
321 }
322
Camille Lamy5193caa2018-10-12 11:59:42323 return true;
324}
325
Mikel Astizba9cf2fd2017-12-17 10:38:10326// See replaced_navigation_entry_data.h for details: this information is meant
327// to ensure |*output_entry| keeps track of its original URL (landing page in
328// case of server redirects) as it gets replaced (e.g. history.replaceState()),
329// without overwriting it later, for main frames.
330void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57331 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10332 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17333 if (output_entry->GetReplacedEntryData().has_value() ||
334 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10335 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17336 }
Mikel Astizba9cf2fd2017-12-17 10:38:10337
338 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57339 data.first_committed_url = replaced_entry->GetURL();
340 data.first_timestamp = replaced_entry->GetTimestamp();
341 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29342 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10343}
344
Minggang Wangb9f3fa92021-07-01 15:30:31345blink::mojom::NavigationType GetNavigationType(
346 const GURL& old_url,
347 const GURL& new_url,
348 ReloadType reload_type,
349 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52350 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31351 bool has_pending_cross_document_commit,
352 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49353 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13354 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49355 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23356 // Reload navigations
357 switch (reload_type) {
358 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31359 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23360 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31361 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23362 case ReloadType::NONE:
363 break; // Fall through to rest of function.
364 }
365
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08366 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31367 return entry->GetHasPostData()
368 ? blink::mojom::NavigationType::RESTORE_WITH_POST
369 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23370 }
371
danakjb952ef12021-01-14 19:58:49372 const bool can_be_same_document =
373 // A pending cross-document commit means this navigation will not occur in
374 // the current document, as that document would end up being replaced in
375 // the meantime.
376 !has_pending_cross_document_commit &&
377 // If the current document is an error page, we should always treat it as
378 // a different-document navigation so that we'll attempt to load the
379 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49380 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13381 // If the navigation is an embedder-initiated navigation of a fenced
382 // frame root (i.e. enters a fenced frame tree from outside),
383 // same-document navigations should be disabled because we don't want to
384 // allow information to be joined across multiple embedder-initiated
385 // fenced frame navigations (which may contain separate cross-site data).
386 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49387 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
388 // same-document navigations should be disabled because we want to force
389 // the creation of a new browsing context group.
390 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12391
clamyea99ea12018-05-28 13:54:23392 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52393 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12394 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31395 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
396 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23397 }
398 DCHECK(!is_same_document_history_load);
399
400 // A same-document fragment-navigation happens when the only part of the url
401 // that is modified is after the '#' character.
402 //
403 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12404 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23405 //
406 // Note: this check is only valid for navigations that are not history
407 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
408 // history navigation from 'A#foo' to 'A#bar' is not a same-document
409 // navigation, but a different-document one. This is why history navigation
410 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47411 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52412 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12413
414 // The one case where we do the wrong thing here and incorrectly choose
415 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
416 // the renderer is a frameset. All frameset navigations should be
417 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
418 // navigation would do the right thing, as it would send it to the browser and
419 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
420 // into this method). But since we can't tell that case here for browser-
421 // initiated navigations, we have to get the renderer involved. In that case
422 // the navigation would be restarted due to the renderer spending a reply of
423 // mojom::CommitResult::RestartCrossDocument.
424
425 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31426 ? blink::mojom::NavigationType::SAME_DOCUMENT
427 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23428}
429
Camille Lamy5193caa2018-10-12 11:59:42430// Adjusts the original input URL if needed, to get the URL to actually load and
431// the virtual URL, which may differ.
432void RewriteUrlForNavigation(const GURL& original_url,
433 BrowserContext* browser_context,
434 GURL* url_to_load,
435 GURL* virtual_url,
436 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42437 // Allow the browser URL handler to rewrite the URL. This will, for example,
438 // remove "view-source:" from the beginning of the URL to get the URL that
439 // will actually be loaded. This real URL won't be shown to the user, just
440 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31441 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42442 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
443 url_to_load, browser_context, reverse_on_redirect);
444}
445
446#if DCHECK_IS_ON()
447// Helper sanity check function used in debug mode.
448void ValidateRequestMatchesEntry(NavigationRequest* request,
449 NavigationEntryImpl* entry) {
450 if (request->frame_tree_node()->IsMainFrame()) {
451 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
452 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31453 ui::PageTransitionFromInt(request->common_params().transition),
454 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42455 }
Nasko Oskovc36327d2019-01-03 23:23:04456 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42457 entry->should_clear_history_list());
458 DCHECK_EQ(request->common_params().has_user_gesture,
459 entry->has_user_gesture());
460 DCHECK_EQ(request->common_params().base_url_for_data_url,
461 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04462 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42463 entry->GetCanLoadLocalResources());
464 DCHECK_EQ(request->common_params().started_from_context_menu,
465 entry->has_started_from_context_menu());
466
467 FrameNavigationEntry* frame_entry =
468 entry->GetFrameEntry(request->frame_tree_node());
469 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52470 // TODO(https://crbug.com/40467594): This case should be unreachable once
471 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42472 return;
473 }
474
Camille Lamy5193caa2018-10-12 11:59:42475 DCHECK_EQ(request->common_params().method, frame_entry->method());
476
Nasko Oskovc36327d2019-01-03 23:23:04477 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42478 if (redirect_size == frame_entry->redirect_chain().size()) {
479 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04480 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42481 frame_entry->redirect_chain()[i]);
482 }
483 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21484 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42485 }
486}
487#endif // DCHECK_IS_ON()
488
Dave Tapuska8bfd84c2019-03-26 20:47:16489// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20490// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16491bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20492 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16493 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20494 DCHECK(sandboxed_initiator_rfh);
495 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
496 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16497 for (auto& item : navigations) {
498 bool within_subtree = false;
499 // Check whether this NavigationRequest affects a frame within the
500 // sandboxed frame's subtree by walking up the tree looking for the
501 // sandboxed frame.
502 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03503 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20504 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16505 within_subtree = true;
506 break;
507 }
508 }
509 if (!within_subtree)
510 return false;
511 }
512 return true;
513}
514
William Liu122754942024-01-18 22:34:39515// Used for "Navigation.SessionHistoryCount" histogram.
516enum class HistoryNavTypeForHistogram {
517 // A same-doc or cross-doc navigation of the main frame. We can only have one
518 // main frame request per `NavigationController::GoToIndex()`.
519 kMainFrame = 0,
520 // `NavigationController::GoToIndex()` creates one main frame request and
521 // one or more subframe requests.
522 kMainFrameAndSubframe,
523 // `NavigationController::GoToIndex()` creates one or more subframe requests.
524 kSubframe,
525 // Used for histogram boundary.
526 kCount
527};
528
529void CountRequests(
530 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
531 int& mutable_main_frame_cnt,
532 int& mutable_subframe_cnt) {
533 for (const auto& req : requests) {
534 if (req->IsInPrimaryMainFrame()) {
535 // We can only have one main frame navigation at a time.
536 CHECK_EQ(mutable_main_frame_cnt, 0);
537 ++mutable_main_frame_cnt;
538 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
539 ++mutable_subframe_cnt;
540 }
541 }
542}
543
544// Record the number of different types of navigations as histograms. See
545// `HistoryNavTypeForHistogram` for the types.
546void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
547 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
548 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
549 // We must have one request.
550 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
551
552 int main_frame_cnt = 0;
553 int subframe_cnt = 0;
554 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
555 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
556
557 std::optional<HistoryNavTypeForHistogram> history_nav_type;
558 if (main_frame_cnt > 0) {
559 if (subframe_cnt == 0) {
560 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
561 } else {
562 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
563 }
564 } else if (subframe_cnt > 0) {
565 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
566 }
567 if (history_nav_type.has_value()) {
568 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
569 history_nav_type.value(),
570 HistoryNavTypeForHistogram::kCount);
571 }
572}
573
[email protected]e9ba4472008-09-14 15:42:43574} // namespace
575
arthursonzogni66f711c2019-10-08 14:40:36576// NavigationControllerImpl::PendingEntryRef------------------------------------
577
578NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
579 base::WeakPtr<NavigationControllerImpl> controller)
580 : controller_(controller) {}
581
582NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
583 if (!controller_) // Can be null with interstitials.
584 return;
585
586 controller_->PendingEntryRefDeleted(this);
587}
588
[email protected]d202a7c2012-01-04 07:53:47589// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29590
[email protected]23a918b2014-07-15 09:51:36591const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23592
[email protected]765b35502008-08-21 00:51:20593// static
[email protected]d202a7c2012-01-04 07:53:47594size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23595 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20596
[email protected]e6fec472013-05-14 05:29:02597// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20598// when testing.
599static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29600
[email protected]71fde352011-12-29 03:29:56601// static
dcheng9bfa5162016-04-09 01:00:57602std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
603 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10604 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37605 std::optional<url::Origin> initiator_origin,
606 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10607 ui::PageTransition transition,
608 bool is_renderer_initiated,
609 const std::string& extra_headers,
610 BrowserContext* browser_context,
611 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
612 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21613 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37614 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32615 is_renderer_initiated, extra_headers, browser_context,
616 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10617}
618
619// static
620std::unique_ptr<NavigationEntryImpl>
621NavigationControllerImpl::CreateNavigationEntry(
622 const GURL& url,
623 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37624 std::optional<url::Origin> initiator_origin,
625 std::optional<GURL> initiator_base_url,
626 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57627 ui::PageTransition transition,
628 bool is_renderer_initiated,
629 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09630 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17631 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
632 bool rewrite_virtual_urls) {
633 GURL url_to_load = url;
634 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56635 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17636 if (rewrite_virtual_urls) {
637 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
638 &reverse_on_redirect);
639 }
Lukasz Anforowicz641234d52019-11-07 21:07:10640 // Let the NTP override the navigation params and pretend that this is a
641 // browser-initiated, bookmark-like navigation.
642 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32643 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21644 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10645
Patrick Monettef507e982019-06-19 20:18:06646 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28647 nullptr, // The site instance for tabs is sent on navigation
648 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21649 url_to_load, referrer, initiator_origin, initiator_base_url,
650 std::u16string(), transition, is_renderer_initiated,
651 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17652 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42653 entry->SetVirtualURL(virtual_url);
654 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56655 entry->set_update_virtual_url_with_url(reverse_on_redirect);
656 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06657 return entry;
[email protected]71fde352011-12-29 03:29:56658}
659
[email protected]cdcb1dee2012-01-04 00:46:20660// static
661void NavigationController::DisablePromptOnRepost() {
662 g_check_for_repost = false;
663}
664
[email protected]c5b88d82012-10-06 17:03:33665base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
666 base::Time t) {
667 // If |t| is between the water marks, we're in a run of duplicates
668 // or just getting out of it, so increase the high-water mark to get
669 // a time that probably hasn't been used before and return it.
670 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35671 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33672 return high_water_mark_;
673 }
674
675 // Otherwise, we're clear of the last duplicate run, so reset the
676 // water marks.
677 low_water_mark_ = high_water_mark_ = t;
678 return t;
679}
680
ckitagawa0faa5e42020-06-17 17:30:54681NavigationControllerImpl::ScopedShowRepostDialogForTesting::
682 ScopedShowRepostDialogForTesting()
683 : was_disallowed_(g_check_for_repost) {
684 g_check_for_repost = true;
685}
686
687NavigationControllerImpl::ScopedShowRepostDialogForTesting::
688 ~ScopedShowRepostDialogForTesting() {
689 g_check_for_repost = was_disallowed_;
690}
691
Nate Chapin9eb16be72022-09-23 22:54:31692NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
693 base::SafeRef<NavigationControllerImpl> controller)
694 : controller_(controller) {
695 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
696 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
697 frame_tree_node_id_to_keys_.insert(
698 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
699 if (auto* frame_entry = frame_tree_node->current_frame_host()
700 ->last_committed_frame_entry()) {
701 frame_tree_node_id_to_doc_seq_nos_.insert(
702 {frame_tree_node->frame_tree_node_id(),
703 frame_entry->document_sequence_number()});
704 }
705 }
706 PopulateKeySet(Direction::kBack);
707 PopulateKeySet(Direction::kForward);
708}
709
710void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
711 Direction direction) {
712 // Keep track of which FrameTreeNodes may still have relevant API keys in
713 // additional FrameNavigationEntries.
714 std::set<FrameTreeNode*> nodes_to_process;
715 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
716 nodes_to_process.insert(node);
717 }
718
719 const int offset = direction == Direction::kForward ? 1 : -1;
720 const int start = direction == Direction::kForward
721 ? controller_->GetLastCommittedEntryIndex()
722 : controller_->GetLastCommittedEntryIndex() - 1;
723 for (int i = start;
724 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
725 i += offset) {
726 std::set<FrameTreeNode*> nodes_to_continue_processing;
727
728 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
729 entry->ForEachFrameEntry([this, &nodes_to_process,
730 &nodes_to_continue_processing,
731 &entry](FrameNavigationEntry* frame_entry) {
732 // Find the |node| that matches |frame_entry|, if any.
733 FrameTreeNode* node = nullptr;
734 if (frame_entry == entry->root_node()->frame_entry) {
735 node = controller_->frame_tree().root();
736 } else {
737 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
738 if (it == names_to_nodes_.end())
739 return;
740 node = it->second;
741 }
742
743 // Skip this node if a previous step determine there are no longer
744 // relevant navigation API keys in this direction.
745 if (nodes_to_process.find(node) == nodes_to_process.end())
746 return;
747
748 // Stop processing |node| if we reach a point where it's cross-origin.
749 // See also PopulateSingleNavigationApiHistoryEntryVector().
750 url::Origin frame_entry_origin =
751 frame_entry->committed_origin().value_or(url::Origin::Resolve(
752 frame_entry->url(),
753 frame_entry->initiator_origin().value_or(url::Origin())));
754 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
755 return;
756
757 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
758 frame_entry->navigation_api_key());
759 // Mark |node| as needing more processing for the next entry.
760 nodes_to_continue_processing.insert(node);
761
762 // Check whether |node| went cross-document. If so, its children are
763 // no longer the same conceptual iframe as the current one, and
764 // should no longer be processed. This check is intentionally done
765 // after processing the current |node|, which may still have relevant
766 // discarded API keys.
767 if (frame_entry->document_sequence_number() !=
768 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50769 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31770 nodes_to_process.erase(descendant);
771 }
772 });
773
774 nodes_to_process.swap(nodes_to_continue_processing);
775 }
776}
777
778NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
779 std::set<std::string> all_keys;
780 // Find all remaining navigation API keys after some entries have been
781 // removed.
782 for (auto& entry : controller_->entries_) {
783 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
784 all_keys.insert(frame_entry->navigation_api_key());
785 });
786 }
787
788 // Notify each frame in the renderer of any disposed navigation API keys.
789 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
790 std::vector<std::string> disposed_keys;
791 for (const auto& key : id_to_keys.second) {
792 if (all_keys.find(key) == all_keys.end())
793 disposed_keys.push_back(key);
794 }
795 if (disposed_keys.empty())
796 continue;
797
798 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
799 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
800 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
801 }
802}
803
[email protected]d202a7c2012-01-04 07:53:47804NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00805 BrowserContext* browser_context,
806 FrameTree& frame_tree,
807 NavigationControllerDelegate* delegate)
808 : frame_tree_(frame_tree),
809 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57810 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22811 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37812 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
813 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37814 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29815}
816
[email protected]d202a7c2012-01-04 07:53:47817NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00818 // The NavigationControllerImpl might be called inside its delegate
819 // destructor. Calling it is not valid anymore.
820 delegate_ = nullptr;
821 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29822}
823
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57824BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55825 return browser_context_;
826}
827
[email protected]d202a7c2012-01-04 07:53:47828void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30829 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36830 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57831 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47832 // Note that it's possible for `entries_` to contain multiple entries at this
833 // point, as Restore() might be called on a NavigationController that is
834 // already used (e.g. due to WebView's restoreState() API), not only for fresh
835 // NavigationControllers. These entries are not cleared to preserve legacy
836 // behavior and also because `pending_entry_` might point to one of the
837 // pre-existing entries. An exception for this is when `entries_` contains
838 // only the initial NavigationEntry, which must be removed.
839
840 // Do not proceed if selected_navigation will be out of bounds for the updated
841 // entries_ list, since it will be assigned to last_committed_entry_index_ and
842 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58843 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47844 // is empty, since there should be no work to do (rather than marking the
845 // existing entries as needing reload). Also consider returning early if the
846 // selected index is -1, which represents a no-committed-entry state.
847 if (selected_navigation < -1 ||
848 selected_navigation >=
849 base::checked_cast<int>(entries->size() + entries_.size())) {
850 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24851 }
Charlie Reis23c26da2022-01-29 00:57:47852
Rakina Zata Amni46087a12022-11-11 08:28:38853 // There will always be at least one entry (new NavigationControllers will
854 // have the initial NavigationEntry).
855 if (selected_navigation == -1)
856 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47857
Rakina Zata Amni46087a12022-11-11 08:28:38858 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
859 // If we are on the initial NavigationEntry, it must be the only entry in
860 // the list. Since it's impossible to do a history navigation to the
861 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
862 // `pending_entry` might be set for a new non-history navigation).
863 // Note that we should not clear `entries_` if `entries` is empty (when
864 // InitialNavigationEntry mode is enabled), since that would leave us
865 // without any NavigationEntry.
866 CHECK_EQ(1, GetEntryCount());
867 CHECK_EQ(-1, pending_entry_index_);
868 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47869 }
[email protected]ce3fa3c2009-04-20 19:55:57870
[email protected]ce3fa3c2009-04-20 19:55:57871 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44872 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03873 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47874 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43875 if (entry->GetURL().is_empty()) {
876 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01877 // persisting the initial NavigationEntry [which is no longer possible but
878 // some old persisted sessions might still contain it] or when the
879 // serializer failed to write the URL because it's too long). Trying to
880 // restore and navigate to an entry with an empty URL will result in
881 // crashes, so change the URL to about:blank. See also
882 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43883 entry->SetURL(GURL(url::kAboutBlankURL));
884 }
dcheng36b6aec92015-12-26 06:16:36885 entries_.push_back(
886 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47887 }
avif16f85a72015-11-13 18:25:03888
889 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
890 // cleared out safely.
891 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57892
893 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36894 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57895}
896
toyoshim6142d96f2016-12-19 09:07:25897void NavigationControllerImpl::Reload(ReloadType reload_type,
898 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03899 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
900 (int)reload_type);
901 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
902 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28903 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28904 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32905 int current_index = -1;
906
Carlos IL42b416592019-10-07 23:10:36907 if (entry_replaced_by_post_commit_error_) {
908 // If there is an entry that was replaced by a currently active post-commit
909 // error navigation, this can't be the initial navigation.
910 DCHECK(!IsInitialNavigation());
911 // If the current entry is a post commit error, we reload the entry it
912 // replaced instead. We leave the error entry in place until a commit
913 // replaces it, but the pending entry points to the original entry in the
914 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
915 // case that pending_entry_ != entries_[pending_entry_index_].
916 entry = entry_replaced_by_post_commit_error_.get();
917 current_index = GetCurrentEntryIndex();
918 } else if (IsInitialNavigation() && pending_entry_) {
919 // If we are reloading the initial navigation, just use the current
920 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32921 entry = pending_entry_;
922 // The pending entry might be in entries_ (e.g., after a Clone), so we
923 // should also update the current_index.
924 current_index = pending_entry_index_;
925 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00926 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32927 current_index = GetCurrentEntryIndex();
928 if (current_index != -1) {
creis3da03872015-02-20 21:12:32929 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32930 }
[email protected]979a4bc2013-04-24 01:27:15931 }
[email protected]241db352013-04-22 18:04:05932
[email protected]59167c22013-06-03 18:07:32933 // If we are no where, then we can't reload. TODO(darin): We should add a
934 // CanReload method.
935 if (!entry)
936 return;
937
Rakina Zata Amnif297a802022-01-18 03:53:43938 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
939 // We should never navigate to an existing initial NavigationEntry that is
940 // the initial NavigationEntry for the initial empty document that hasn't
941 // been overridden by the synchronous about:blank commit, to preserve
942 // legacy behavior where trying to reload when the main frame is on the
943 // initial empty document won't result in a navigation. See also
944 // https://crbug.com/1277414.
945 return;
946 }
947
Aran Gilman37d11632019-10-08 23:07:15948 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30949 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07950 // they really want to do this. If they do, the dialog will call us back
951 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57952 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02953
[email protected]106a0812010-03-18 00:15:12954 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57955 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47956 return;
initial.commit09911bf2008-07-26 23:55:29957 }
Lei Zhang96031532019-10-10 19:05:47958
Wang Huia25efabc2022-09-24 17:27:22959 // Set ReloadType for |entry|.
960 entry->set_reload_type(reload_type);
961
Lei Zhang96031532019-10-10 19:05:47962 if (!IsInitialNavigation())
963 DiscardNonCommittedEntries();
964
965 pending_entry_ = entry;
966 pending_entry_index_ = current_index;
967 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
968
Nate Chapin45f620582021-09-30 17:45:43969 // location.reload() goes through BeginNavigation, so all reloads triggered
970 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13971 NavigateToExistingPendingEntry(
972 reload_type,
973 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:37974 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:13975 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29976}
977
[email protected]d202a7c2012-01-04 07:53:47978void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48979 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12980}
981
[email protected]d202a7c2012-01-04 07:53:47982void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49983 // If the pending reload type has been cleared by another navigation
984 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48985 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49986 return;
[email protected]106a0812010-03-18 00:15:12987 }
Wang Hui96ab1012022-10-11 02:05:49988 Reload(pending_reload_, false);
989 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12990}
991
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57992bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09993 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11994}
995
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57996bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38997 // Check that we're on the initial NavigationEntry and that this is not a
998 // cloned tab.
999 return IsInitialNavigation() && GetEntryCount() == 1 &&
1000 GetLastCommittedEntry()->IsInitialEntry() &&
1001 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401002}
1003
Aran Gilman37d11632019-10-08 23:07:151004NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1005 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581006 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031007 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581008}
1009
Adithya Srinivasan9b0c99c2021-08-10 15:19:451010NavigationEntryImpl*
1011NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1012 int nav_entry_id) const {
1013 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1014 if (entry)
1015 return entry;
1016 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521017 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451018 : nullptr;
1019}
1020
W. James MacLeanc07dc41b2022-07-25 18:52:161021void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571022 const url::Origin& origin) {
1023 for (int i = 0; i < GetEntryCount(); i++) {
1024 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161025 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571026 }
1027 if (entry_replaced_by_post_commit_error_) {
1028 // It's possible we could come back to this entry if the error
1029 // page/interstitial goes away.
1030 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161031 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571032 }
W. James MacLean1c40862c2020-04-27 21:05:571033}
1034
avi25764702015-06-23 15:43:371035void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571036 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001037 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371038 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271039 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201040}
1041
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571042NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471043 if (pending_entry_)
1044 return pending_entry_;
1045 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201046}
1047
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571048NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321049 // The pending entry is safe to return for new (non-history), browser-
1050 // initiated navigations. Most renderer-initiated navigations should not
1051 // show the pending entry, to prevent URL spoof attacks.
1052 //
1053 // We make an exception for renderer-initiated navigations in new tabs, as
1054 // long as no other page has tried to access the initial empty document in
1055 // the new tab. If another page modifies this blank page, a URL spoof is
1056 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321057 bool safe_to_show_pending =
1058 pending_entry_ &&
1059 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091060 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321061 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461062 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321063
1064 // Also allow showing the pending entry for history navigations in a new tab,
1065 // such as Ctrl+Back. In this case, no existing page is visible and no one
1066 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151067 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1068 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321069 safe_to_show_pending = true;
1070
1071 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191072 return pending_entry_;
1073 return GetLastCommittedEntry();
1074}
1075
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571076int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201077 if (pending_entry_index_ != -1)
1078 return pending_entry_index_;
1079 return last_committed_entry_index_;
1080}
1081
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571082NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381083 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031084 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201085}
1086
Elad Alon32044f532025-03-04 22:16:031087const NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry()
1088 const {
1089 CHECK_NE(last_committed_entry_index_, -1);
1090 return entries_[last_committed_entry_index_].get();
1091}
1092
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571093bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351094 const std::string& mime_type = frame_tree_->root()
1095 ->current_frame_host()
1096 ->GetPage()
1097 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531098 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1099 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271100 NavigationEntry* visible_entry = GetVisibleEntry();
1101 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391102 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161103}
1104
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571105int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271106 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451107 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271108 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551109 return last_committed_entry_index_;
1110}
1111
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571112int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451113 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291114 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551115 return static_cast<int>(entries_.size());
1116}
1117
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571118NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371119 if (index < 0 || index >= GetEntryCount())
1120 return nullptr;
1121
avif16f85a72015-11-13 18:25:031122 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251123}
1124
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571125NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471126 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201127}
1128
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571129int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461130 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031131}
1132
Arthur Sonzognic686e8f2024-01-11 08:36:371133std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031134 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591135 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1136 return index;
1137 }
Shivani Sharma298d12852019-01-22 20:04:031138 }
Arthur Sonzognic686e8f2024-01-11 08:36:371139 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591140}
1141
1142bool NavigationControllerImpl::CanGoBack() {
1143 return GetIndexForGoBack().has_value();
1144}
1145
Arthur Sonzognic686e8f2024-01-11 08:36:371146std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591147 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1148 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1149 return index;
1150 }
1151 }
Arthur Sonzognic686e8f2024-01-11 08:36:371152 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201153}
1154
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571155bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591156 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201157}
1158
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571159bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031160 int index = GetIndexForOffset(offset);
1161 return index >= 0 && index < GetEntryCount();
1162}
1163
Xiaohan Wang7f8052e02022-01-14 18:44:281164#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151165bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151166 if (offset == 0)
1167 return true;
1168 int increment = offset > 0 ? 1 : -1;
1169 int non_skippable_entries = 0;
1170 for (int index = GetIndexForOffset(increment);
1171 index >= 0 && index < GetEntryCount(); index += increment) {
1172 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1173 non_skippable_entries++;
1174
1175 if (non_skippable_entries == std::abs(offset))
1176 return true;
1177 }
1178 return false;
1179}
1180#endif
1181
[email protected]d202a7c2012-01-04 07:53:471182void NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371183 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061184
Kevin McNeeedc481c2023-04-27 22:30:581185 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211186
Kevin McNee3b3a56192023-03-17 14:40:591187 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201188}
1189
[email protected]d202a7c2012-01-04 07:53:471190void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161191 // Note that at least one entry (the last one) will be non-skippable since
1192 // entries are marked skippable only when they add another entry because of
1193 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371194 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591195
Kevin McNeeedc481c2023-04-27 22:30:581196 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591197
1198 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201199}
1200
[email protected]d202a7c2012-01-04 07:53:471201void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131202 GoToIndex(index, /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371203 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:131204 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161205}
1206
William Liu62ae26c2024-08-08 14:28:161207std::vector<base::WeakPtr<NavigationRequest>>
1208NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201209 int index,
1210 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371211 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131212 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201213 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441214 TRACE_EVENT0("browser,navigation,benchmark",
1215 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501216 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1217 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1218 entries_.size());
1219 // Indices should have have been validated by the caller.
1220 CHECK_GE(index, 0);
1221 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201222
Rakina Zata Amnif297a802022-01-18 03:53:431223 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1224 // We should never navigate to an existing initial NavigationEntry that is
1225 // the initial NavigationEntry for the initial empty document that hasn't
1226 // been overridden by the synchronous about:blank commit, to preserve
1227 // legacy behavior where trying to reload when the main frame is on the
1228 // initial empty document won't result in a navigation. See also
1229 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161230 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431231 }
1232
[email protected]cbab76d2008-10-13 22:42:471233 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201234
arthursonzogni5c4c202d2017-04-25 23:41:271235 DCHECK_EQ(nullptr, pending_entry_);
1236 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431237
arthursonzogni5c4c202d2017-04-25 23:41:271238 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201239 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271240 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1241 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
William Liuec04e382024-05-23 18:03:271242 return NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
1243 soft_navigation_heuristics_task_id,
1244 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201245}
1246
[email protected]d202a7c2012-01-04 07:53:471247void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121248 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031249 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201250 return;
1251
[email protected]9ba14052012-06-22 23:50:031252 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201253}
1254
Nate Chapinbf682fa32022-09-26 22:41:201255void NavigationControllerImpl::GoToOffsetFromRenderer(
1256 int offset,
Yoav Weiss8c573952022-11-17 17:35:131257 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371258 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131259 soft_navigation_heuristics_task_id) {
Nate Chapinbb74c5a52023-07-21 23:13:351260 // Note: This is actually reached in unit tests.
1261 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431262 return;
1263
Nate Chapinbf682fa32022-09-26 22:41:201264 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131265 soft_navigation_heuristics_task_id,
1266 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431267}
1268
William Liu62ae26c2024-08-08 14:28:161269std::vector<base::WeakPtr<NavigationRequest>>
1270NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271271 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1272 /*soft_navigation_heuristics_task_id=*/std::nullopt,
1273 /*navigation_api_key=*/nullptr);
1274}
1275
Xiaohan Wang7f8052e02022-01-14 18:44:281276#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151277void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1278 // Note: This is actually reached in unit tests.
1279 if (!CanGoToOffsetWithSkipping(offset))
1280 return;
1281
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421282 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151283 GoToIndex(GetIndexForOffset(offset));
1284 return;
1285 }
1286 int increment = offset > 0 ? 1 : -1;
1287 // Find the offset without counting skippable entries.
1288 int target_index = GetIndexForOffset(increment);
1289 int non_skippable_entries = 0;
1290 for (int index = target_index; index >= 0 && index < GetEntryCount();
1291 index += increment) {
1292 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1293 non_skippable_entries++;
1294
1295 if (non_skippable_entries == std::abs(offset)) {
1296 target_index = index;
1297 break;
1298 }
1299 }
1300
1301 GoToIndex(target_index);
1302}
1303#endif
1304
[email protected]41374f12013-07-24 02:49:281305bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151306 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281307 return false;
[email protected]6a13a6c2011-12-20 21:47:121308
[email protected]43032342011-03-21 14:10:311309 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281310 return true;
[email protected]cbab76d2008-10-13 22:42:471311}
1312
Michael Thiessen9b14d512019-09-23 21:19:471313void NavigationControllerImpl::PruneForwardEntries() {
1314 DiscardNonCommittedEntries();
1315 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471316 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471317 if (num_removed <= 0)
1318 return;
Nate Chapin9eb16be72022-09-23 22:54:311319 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471320 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1321 NotifyPrunedEntries(this, remove_start_index /* start index */,
1322 num_removed /* count */);
1323}
1324
Aran Gilman37d11632019-10-08 23:07:151325void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1326 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321327 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311328 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511329 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1330 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321331 }
1332}
1333
Harkiran Bolariaba823e42021-05-21 18:30:361334base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1335 const GURL& url,
1336 const Referrer& referrer,
1337 ui::PageTransition transition,
1338 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471339 LoadURLParams params(url);
1340 params.referrer = referrer;
1341 params.transition_type = transition;
1342 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361343 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471344}
1345
Harkiran Bolariaba823e42021-05-21 18:30:361346base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1347 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061348 if (params.is_renderer_initiated)
1349 DCHECK(params.initiator_origin.has_value());
1350
naskob8744d22014-08-28 17:07:431351 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151352 "NavigationControllerImpl::LoadURLWithParams", "url",
1353 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291354 bool is_explicit_navigation =
1355 GetContentClient()->browser()->IsExplicitNavigation(
1356 params.transition_type);
1357 if (HandleDebugURL(params.url, params.transition_type,
1358 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431359 // If Telemetry is running, allow the URL load to proceed as if it's
1360 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491361 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181362 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361363 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181364 }
[email protected]47752982014-07-29 08:01:431365 }
[email protected]8bf1048012012-02-08 01:22:181366
[email protected]cf002332012-08-14 19:17:471367 // Checks based on params.load_type.
1368 switch (params.load_type) {
1369 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431370 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541371#if BUILDFLAG(IS_ANDROID)
1372 case LOAD_TYPE_PDF_ANDROID:
1373#endif
[email protected]cf002332012-08-14 19:17:471374 break;
1375 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261376 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211377 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471378 }
1379 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461380 }
[email protected]e47ae9472011-10-13 19:48:341381
[email protected]e47ae9472011-10-13 19:48:341382 // The user initiated a load, we don't need to reload anymore.
1383 needs_reload_ = false;
1384
Harkiran Bolariaba823e42021-05-21 18:30:361385 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441386}
1387
Charlie Reis4c53a962023-06-21 23:17:531388void NavigationControllerImpl::LoadOriginalRequestURL() {
1389 // If the original request URL is not valid, matches the current URL, or
1390 // involves POST data, then simply reload. The POST check avoids issues with
1391 // sending data to the wrong page.
1392 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1393 const GURL& original_request_url =
1394 GetLastCommittedEntry()->GetOriginalRequestURL();
1395 if (!original_request_url.is_valid() ||
1396 original_request_url == last_committed_url ||
1397 GetLastCommittedEntry()->GetHasPostData()) {
1398 Reload(ReloadType::NORMAL, true);
1399 return;
1400 }
1401
1402 // Otherwise, attempt to load the original request URL without any of the
1403 // other data from the current NavigationEntry, replacing the current entry.
1404 // Loading the original URL is useful in cases such as modifying the user
1405 // agent.
1406 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1407 std::make_unique<NavigationController::LoadURLParams>(
1408 original_request_url);
1409 load_params->should_replace_current_entry = true;
1410 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1411 LoadURLWithParams(*load_params.get());
1412}
1413
Mohamed Abdelhalim833de902019-09-16 17:41:451414bool NavigationControllerImpl::PendingEntryMatchesRequest(
1415 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191416 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451417 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191418}
1419
[email protected]d202a7c2012-01-04 07:53:471420bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321421 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071422 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331423 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441424 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251425 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561426 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131427 NavigationRequest* navigation_request) {
1428 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331429
1430 // Note: validation checks and renderer kills due to invalid commit messages
1431 // must happen before getting here, in
1432 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1433 // effects of the navigation have already occurred.
1434
[email protected]cd2e15742013-03-08 04:08:311435 is_initial_navigation_ = false;
1436
Wang Hui96ab1012022-10-11 02:05:491437 // Any pending request to repost a form submission is no longer valid, since a
1438 // different NavigationEntry is committing.
1439 pending_reload_ = ReloadType::NONE;
1440
[email protected]0e8db942008-09-24 21:21:481441 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431442 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451443 if (entry_replaced_by_post_commit_error_) {
1444 // Same document navigation events with a post-commit error should already
1445 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1446 // reaching here.
1447 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331448
Xinghui Lub9e86a352024-05-17 16:29:421449 if (pending_entry_) {
1450 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1451 // `pending_entry_` isn't pointing to the last committed entry.
1452 // Instead, all reload approaches (e.g., in `Reload` and
1453 // `LoadIfNecessary`) should attempt to load the
1454 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1455 // entry itself.
1456 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1457 << "Incorrectly reloading the post commit error page entry.";
1458 }
Xinghui Lue4e50be2024-05-15 21:46:001459
Rakina Zata Amnie2d31312022-11-18 03:38:451460 // Any commit while a post-commit error page is showing should put the
1461 // original entry back, replacing the error page's entry. This includes
1462 // reloads, where the original entry was used as the pending entry and
1463 // should now be at the correct index at commit time.
1464 entries_[last_committed_entry_index_] =
1465 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481466 }
Rakina Zata Amnie2d31312022-11-18 03:38:451467 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1468 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001469 // Must honor user agent overrides in the |navigation_request|, such as
1470 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1471 // result, besides comparing |pending_entry_|'s user agent against
1472 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1473 // agent against LastCommittedEntry's.
1474 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541475 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1476 (PendingEntryMatchesRequest(navigation_request) &&
1477 pending_entry_->GetIsOverridingUserAgent() !=
1478 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001479 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451480 }
[email protected]ecd9d8702008-08-28 22:10:171481
Dave Tapuskaa2ab4f252021-07-08 21:31:281482 bool is_main_frame_navigation = !rfh->GetParent();
1483
Alexander Timind2f2e4f22019-04-02 20:04:531484 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1485 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281486 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141487 // BackForwardCacheMetrics to be associated with the new navigation's
1488 // NavigationEntry, by either creating a new object or reusing the previous
1489 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281490 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211491 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141492 back_forward_cache_metrics = BackForwardCacheMetrics::
1493 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281494 GetLastCommittedEntry(), is_main_frame_navigation,
1495 params.document_sequence_number);
1496 }
Yuzu Saijo29f96ca92022-12-08 04:54:121497
Alexander Timind2f2e4f22019-04-02 20:04:531498 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281499 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451500 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1501 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531502 }
1503 }
1504
Rakina Zata Amnifd8370b2022-11-14 13:32:251505 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1506 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091507 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251508 details->did_replace_entry =
1509 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091510
fdegans9caf66a2015-07-30 21:10:421511 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111512 // except for restored entries. This should be true even if the current commit
1513 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291514 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481515 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081516 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111517
1518 // Only make changes based on the pending entry if the NavigationRequest
1519 // matches it. Otherwise, the pending entry may be for a different request
1520 // (e.g., if a slow history navigation is pending while an auto-subframe
1521 // commit occurs).
1522 if (PendingEntryMatchesRequest(navigation_request)) {
1523 // It is no longer necessary to consider the pending entry as restored.
1524 if (pending_entry_->IsRestored()) {
1525 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1526 was_restored = true;
1527 }
[email protected]e9ba4472008-09-14 15:42:431528
Charlie Reisf8cde712022-10-20 16:25:091529 // If the SiteInstance has changed from the matching pending entry, this
1530 // must be treated as a new navigation with replacement. Set the replacement
1531 // bit here and ClassifyNavigation will identify this case and return
1532 // NEW_ENTRY.
1533 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1534 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1535 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251536 // TODO(nasko,creis,rakina): Move this to happen before committing the
1537 // navigation. This is a bit complicated because we don't currently
1538 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091539 details->did_replace_entry = true;
1540 }
Nasko Oskovaee2f862018-06-15 00:05:521541 }
[email protected]bcd904482012-02-01 01:54:221542
[email protected]e9ba4472008-09-14 15:42:431543 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101544 NavigationType navigation_type =
1545 ClassifyNavigation(rfh, params, navigation_request);
1546 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451547
Rakina Zata Amnie2d31312022-11-18 03:38:451548 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451549 // Ensure that this navigation does not add a navigation entry, since
1550 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1551 // beyond the last committed one. Therefore, `should_replace_current_entry`
1552 // should be set, which replaces the current entry, or this should be a
1553 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251554 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331555 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451556 }
1557
Rakina Zata Amnie2d31312022-11-18 03:38:451558 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551559 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241560 // This is a subframe navigation on the initial empty document, which used
1561 // to not have a NavigationEntry to attach to. Now it can attach to the
1562 // initial NavigationEntry, and we must ensure that its NavigationEntry
1563 // will keep the "initial NavigationEntry" status and won't append a new
1564 // NavigationEntry (it should always do replacement instead).
1565 // See also https://crbug.com/1277414.
1566 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551567 // Subframe navigation on initial NavigationEntry must not append a new
1568 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1569 // means every subframe navigation that happens while we're on the initial
1570 // NavigationEntry will always reuse the existing NavigationEntry and
1571 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101572 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1573 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551574 // This is a navigation that modifies the initial NavigationEntry, either
1575 // for a replacement or a reload. The initial NavigationEntry should
1576 // retain its "initial NavigationEntry" status in this case.
1577 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241578 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251579 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1580 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241581 // This is a synchronous about:blank navigation on the main frame, which
1582 // used to not create a NavigationEntry when we have no NavigationEntry on
1583 // FrameTree creation. We now have the initial NavigationEntry and are on
1584 // the initial NavigationEntry. To preserve old behavior, we should still
1585 // keep the "initial" status for the new NavigationEntry that we will
1586 // create for this navigation, so that subframe navigations under the
1587 // synchronously committed about:blank document will never append new
1588 // NavigationEntry, and instead will just reuse the initial
1589 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1590 // See also https://crbug.com/1277414.
1591 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551592 }
1593 }
1594 DCHECK(!details->should_stay_as_initial_entry ||
1595 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201596
eugenebutee08663a2017-04-27 17:43:121597 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441598 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121599
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071600 details->is_prerender_activation =
1601 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241602 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1603 ->GetOutermostMainFrame()
1604 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071605
Peter Boströmd7592132019-01-30 04:50:311606 // Make sure we do not discard the pending entry for a different ongoing
1607 // navigation when a same document commit comes in unexpectedly from the
1608 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1609 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581610 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061611 bool keep_pending_entry =
1612 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101613 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061614 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311615
Miyoung Shin3299cbf2022-11-22 01:41:101616 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061617 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491618 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051619 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561620 previous_document_had_history_intervention_activation,
1621 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431622 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061623 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491624 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1625 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001626 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431627 break;
[email protected]8ff00d72012-10-23 19:12:211628 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471629 RendererDidNavigateNewSubframe(
1630 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561631 previous_document_had_history_intervention_activation,
1632 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431633 break;
[email protected]8ff00d72012-10-23 19:12:211634 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391635 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251636 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001637 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081638 // We don't send a notification about auto-subframe PageState during
1639 // UpdateStateForFrame, since it looks like nothing has changed. Send
1640 // it here at commit time instead.
1641 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431642 return false;
creis59d5a47cb2016-08-24 23:57:191643 }
[email protected]e9ba4472008-09-14 15:42:431644 break;
Aran Gilman37d11632019-10-08 23:07:151645 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211646 NOTREACHED();
[email protected]765b35502008-08-21 00:51:201647 }
1648
[email protected]688aa65c62012-09-28 04:32:221649 // At this point, we know that the navigation has just completed, so
1650 // record the time.
1651 //
1652 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261653 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331654 base::Time timestamp =
1655 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1656 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131657 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221658
Peter Boströmd7592132019-01-30 04:50:311659 // If we aren't keeping the pending entry, there shouldn't be one at this
1660 // point. Clear it again in case any error cases above forgot to do so.
1661 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1662 // been cleared instead of protecting against it.
1663 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551664 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141665
[email protected]e9ba4472008-09-14 15:42:431666 // All committed entries should have nonempty content state so WebKit doesn't
1667 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471668 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321669 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221670 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441671 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141672
Alexander Timind2f2e4f22019-04-02 20:04:531673 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1674 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281675 if (back_forward_cache_metrics &&
1676 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531677 active_entry->set_back_forward_cache_metrics(
1678 std::move(back_forward_cache_metrics));
1679 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281680
1681 // `back_forward_cache_metrics()` may return null as we do not record
1682 // back-forward cache metrics for navigations in non-primary frame trees.
1683 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581684 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141685 // These are both only available from details at this point, so we capture
1686 // them here.
1687 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101688 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141689 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1690 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281691 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1692 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321693 IsBackForwardCacheEnabled() &&
1694 rfh->delegate()->IsBackForwardCacheSupported() &&
1695 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281696 }
naskoc7533512016-05-06 17:01:121697
Charles Reisc0507202017-09-21 00:40:021698 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1699 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1700 // A mismatch can occur if the renderer lies or due to a unique name collision
1701 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121702 FrameNavigationEntry* frame_entry =
1703 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021704 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1705 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031706 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081707 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1708 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031709 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201710
1711 // Remember the bindings the renderer process has at this point, so that
1712 // we do not grant this entry additional bindings if we come back to it.
1713 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301714 }
[email protected]132e281a2012-07-31 18:32:441715
[email protected]97d8f0d2013-10-29 16:49:211716 // Once it is committed, we no longer need to track several pieces of state on
1717 // the entry.
naskoc7533512016-05-06 17:01:121718 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131719
[email protected]49bd30e62011-03-22 20:12:591720 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221721 // TODO(creis): This check won't pass for subframes until we create entries
1722 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001723 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421724 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591725
[email protected]e9ba4472008-09-14 15:42:431726 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001727 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001728 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311729 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531730
arthursonzogni7ddc6542021-04-09 09:16:501731 active_entry->SetIsOverridingUserAgent(
1732 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031733
[email protected]93f230e02011-06-01 14:40:001734 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291735
aelias100c9192017-01-13 00:01:431736 if (overriding_user_agent_changed)
1737 delegate_->UpdateOverridingUserAgent();
1738
creis03b48002015-11-04 00:54:561739 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1740 // one knows the latest NavigationEntry it is showing (whether it has
1741 // committed anything in this navigation or not). This allows things like
1742 // state and title updates from RenderFrames to apply to the latest relevant
1743 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381744 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031745 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381746 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431747
1748 if (navigation_request->IsPrerenderedPageActivation()) {
Charlie Reis99b2eba22025-01-31 19:18:571749 BroadcastHistoryIndexAndLength();
Alison Gale47d1537d2024-04-19 21:31:461750 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431751 // is activated. As a result, a "prerenderingchange" event listener sees the
1752 // history.length which is not updated yet. We should guarantee that
Charlie Reis99b2eba22025-01-31 19:18:571753 // history's length and index should be updated before a
Hayato Ito2c8c08d02021-06-23 03:38:431754 // "prerenderingchange" event listener runs. One possible approach is to use
1755 // the same IPC which "prerenderingchange" uses, and propagate history's
Charlie Reis99b2eba22025-01-31 19:18:571756 // length and index together with that.
Hayato Ito2c8c08d02021-06-23 03:38:431757 }
1758
[email protected]e9ba4472008-09-14 15:42:431759 return true;
initial.commit09911bf2008-07-26 23:55:291760}
1761
[email protected]8ff00d72012-10-23 19:12:211762NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321763 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101764 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241765 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591766 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511767 "ClassifyNavigation");
1768
avi7c6f35e2015-05-08 17:52:381769 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241770 // A new entry. We may or may not have a corresponding pending entry, and
1771 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001772 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491773 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061774 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381775 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241776 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511777 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381778 return NAVIGATION_TYPE_NEW_SUBFRAME;
1779 }
1780
Charlie Reisc0f17d2d2021-01-12 18:52:491781 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381782 DCHECK(!params.history_list_was_cleared);
1783
avi39c1edd32015-06-04 20:06:001784 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381785 // All manual subframes would be did_create_new_entry and handled above, so
1786 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081787 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1788 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381789 }
1790
Rakina Zata Amnif6950d552020-11-24 03:26:101791 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1792 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381793 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1794 // create a new page.
1795
Hayato Ito2ae49442021-07-02 02:59:251796 // This main frame navigation is not a history navigation (since
1797 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1798 // reload or a replacement navigation, which will modify the existing entry.
1799 //
Nasko Oskov332593c2018-08-16 17:21:341800 // TODO(nasko): With error page isolation, reloading an existing session
1801 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491802 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341803 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511804 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491805 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061806 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381807 }
1808
Charlie Reisf8cde712022-10-20 16:25:091809 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521810 // If the SiteInstance of the |pending_entry_| does not match the
1811 // SiteInstance that got committed, treat this as a new navigation with
1812 // replacement. This can happen if back/forward/reload encounters a server
1813 // redirect to a different site or an isolated error page gets successfully
1814 // reloaded into a different SiteInstance.
1815 if (pending_entry_->site_instance() &&
1816 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491817 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061818 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521819 }
creis77c9aa32015-09-25 19:59:421820
Nasko Oskovaee2f862018-06-15 00:05:521821 if (pending_entry_index_ == -1) {
1822 // In this case, we have a pending entry for a load of a new URL but Blink
1823 // didn't do a new navigation (params.did_create_new_entry). First check
1824 // to make sure Blink didn't treat a new cross-process navigation as
1825 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161826 // we must treat it as NEW rather than the converted reload case below,
1827 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451828 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161829 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061830 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521831 }
1832
1833 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161834 // We will create a pending entry, but NavigateWithoutEntry will convert
1835 // it to a reload since it's the same page and not create a new entry for
1836 // it. (The user doesn't want to have a new back/forward entry when they
1837 // do this.) Therefore we want to just ignore the pending entry and go
1838 // back to where we were (the "existing entry").
1839 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061840 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521841 }
avi7c6f35e2015-05-08 17:52:381842 }
1843
Rakina Zata Amni153d5702021-09-13 22:48:001844 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381845 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491846 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1847 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161848 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061849 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381850 }
1851
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121852 if (navigation_request->DidEncounterError() &&
1853 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101854 nav_entry_id == failed_pending_entry_id_) {
Charlie Reisb5f39cf2024-11-12 16:55:011855 // If the renderer was going to a pending entry that got cleared because of
1856 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511857 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491858 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061859 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381860 }
1861
Charlie Reisc0f17d2d2021-01-12 18:52:491862 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101863 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511864 trace_return.traced_value()->SetInteger("existing_entry_index",
1865 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381866 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441867 // The renderer has committed a navigation to an entry that no longer
1868 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491869 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061870 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381871 }
1872
avi7c6f35e2015-05-08 17:52:381873 // Since we weeded out "new" navigations above, we know this is an existing
1874 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491875 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061876 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381877}
1878
Rakina Zata Amni3460d382021-10-29 00:43:371879void NavigationControllerImpl::UpdateNavigationEntryDetails(
1880 NavigationEntryImpl* entry,
1881 RenderFrameHostImpl* rfh,
1882 const mojom::DidCommitProvisionalLoadParams& params,
1883 NavigationRequest* request,
1884 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001885 bool is_new_entry,
1886 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371887 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171888 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371889 entry->AddOrUpdateFrameEntry(
1890 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571891 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371892 rfh->GetSiteInstance(), nullptr, params.url,
1893 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171894 Referrer(*params.referrer),
1895 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371896 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171897 request ? request->GetRedirectChain() : redirects, params.page_state,
1898 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371899 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171900 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211901 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171902 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371903
1904 if (rfh->GetParent()) {
1905 // Only modify the NavigationEntry for main frame navigations.
1906 return;
1907 }
1908 if (entry->update_virtual_url_with_url())
1909 UpdateVirtualURLToURL(entry, params.url);
1910 // Don't use the page type from the pending entry. Some interstitial page
1911 // may have set the type to interstitial. Once we commit, however, the page
1912 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171913 entry->set_page_type((request && request->DidEncounterError())
1914 ? PAGE_TYPE_ERROR
1915 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431916 if (commit_details && commit_details->should_stay_as_initial_entry) {
1917 // Retain the "initial NavigationEntry" status.
1918 if (request->IsSameDocument()) {
1919 // If this is for a same-document navigation, the NavigationEntry must be
1920 // reused and should already be marked as the initial NavigationEntry.
1921 DCHECK(entry->IsInitialEntry());
1922 } else {
1923 // If this is for a cross-document navigation, it can be caused by a
1924 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1925 // "for synchronous about:blank" in the latter case, and also when it is
1926 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1927 // is not for a synchronous about:blank commit.
1928 NavigationEntryImpl::InitialNavigationEntryState new_state =
1929 NavigationEntryImpl::InitialNavigationEntryState::
1930 kInitialNotForSynchronousAboutBlank;
1931 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1932 request->is_synchronous_renderer_commit()) {
1933 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1934 kInitialForSynchronousAboutBlank;
1935 }
1936 entry->set_initial_navigation_entry_state(new_state);
1937 }
1938 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1939 // Remove the "initial NavigationEntry" status.
1940 entry->set_initial_navigation_entry_state(
1941 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001942 }
Rakina Zata Amniddf10502022-01-15 02:56:551943
Rakina Zata Amni3460d382021-10-29 00:43:371944 if (is_new_entry) {
1945 // Some properties of the NavigationEntry are only set when the entry is
1946 // new (we aren't reusing it).
1947 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171948 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:401949 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:011950 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
1951 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:371952 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1953 } else {
1954 // We are reusing the NavigationEntry. The site instance will normally be
1955 // the same except for a few cases:
1956 // 1) session restore, when no site instance will be assigned or
1957 // 2) redirect, when the site instance is reset.
1958 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1959 entry->site_instance() == rfh->GetSiteInstance());
1960 }
1961}
1962
Rakina Zata Amniafd3c6582021-11-30 06:19:171963void NavigationControllerImpl::CreateInitialEntry() {
1964 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031965 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171966 auto params = mojom::DidCommitProvisionalLoadParams::New();
1967 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1968 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1969 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:401970 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:171971 params->http_status_code = 0;
1972 params->url_is_unreachable = false;
1973 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171974 params->post_id = -1;
1975 params->embedding_token = base::UnguessableToken::Create();
1976 params->navigation_token = base::UnguessableToken::Create();
1977 params->did_create_new_entry = true;
1978 params->origin = rfh->GetLastCommittedOrigin();
1979 params->should_update_history = true;
1980 params->item_sequence_number = 0;
1981 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151982 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171983 params->transition = is_in_fenced_frame_tree
1984 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1985 : ui::PAGE_TRANSITION_LINK;
1986 params->referrer = blink::mojom::Referrer::New();
1987
Rakina Zata Amniafd3c6582021-11-30 06:19:171988 auto new_entry = std::make_unique<NavigationEntryImpl>(
1989 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381990 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211991 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1992 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1993 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171994 UpdateNavigationEntryDetails(
1995 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001996 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1997 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171998
1999 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
2000 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:002001 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:172002}
2003
Charlie Reisc0f17d2d2021-01-12 18:52:492004void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:322005 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072006 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362007 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442008 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562009 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002010 NavigationRequest* request,
2011 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572012 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372013 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452014 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372015 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522016 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2017 initiator_base_url = request->common_params().initiator_base_url;
2018 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062019
creisf49dfc92016-07-26 17:05:182020 // First check if this is an in-page navigation. If so, clone the current
2021 // entry instead of looking at the pending entry, because the pending entry
2022 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452023 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302024 FrameNavigationEntry* previous_frame_entry =
2025 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452026 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482027 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572028 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082029 rfh->GetSiteInstance(), nullptr, params.url,
2030 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212031 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092032 request->GetRedirectChain(), params.page_state, params.method,
2033 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392034 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302035 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572036 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302037 // FrameNavigationEntry.
2038 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572039 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032040
creisf49dfc92016-07-26 17:05:182041 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032042 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522043 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2044 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572045 // TODO(jam): we had one report of this with a URL that was redirecting to
2046 // only tildes. Until we understand that better, don't copy the cert in
2047 // this case.
2048 new_entry->GetSSL() = SSLStatus();
2049 }
creisf49dfc92016-07-26 17:05:182050
Patrick Monette50e8bd82019-06-13 22:40:452051 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2052 // that |frame_entry| should now have a reference count of exactly 2: one
2053 // due to the local variable |frame_entry|, and another due to |new_entry|
2054 // also retaining one. This should never fail, because it's the main frame.
2055 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182056 }
2057
Harkiran Bolaria59290d62021-03-17 01:53:012058 // If this is an activation navigation from a prerendered page, transfer the
2059 // new entry from an entry already created and stored in the
2060 // NavigationRequest. |new_entry| will not have been set prior to this as
2061 // |is_same_document| is mutually exclusive with
2062 // |IsPrerenderedPageActivation|.
2063 if (request->IsPrerenderedPageActivation()) {
2064 DCHECK(!is_same_document);
2065 DCHECK(!new_entry);
2066 new_entry = request->TakePrerenderNavigationEntry();
2067 DCHECK(new_entry);
2068 }
2069
Charlie Reisc0f17d2d2021-01-12 18:52:492070 // Only make a copy of the pending entry if it is appropriate for the new
2071 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452072 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042073 // 1. The SiteInstance hasn't been assigned to something else.
2074 // 2. The pending entry was intended as a new entry, rather than being a
2075 // history navigation that was interrupted by an unrelated,
2076 // renderer-initiated navigation.
2077 // TODO(csharrison): Investigate whether we can remove some of the coarser
2078 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452079 if (!new_entry && PendingEntryMatchesRequest(request) &&
2080 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342081 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432082 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352083 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432084
Camille Lamy62b826012019-02-26 09:15:472085 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452086 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182087 }
2088
Charlie Reisc0f17d2d2021-01-12 18:52:492089 // For cross-document commits with no matching pending entry, create a new
2090 // entry.
creisf49dfc92016-07-26 17:05:182091 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062092 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072093 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212094 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582095 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452096 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172097 nullptr, // blob_url_loader_factory
2098 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242099
2100 // Find out whether the new entry needs to update its virtual URL on URL
2101 // change and set up the entry accordingly. This is needed to correctly
2102 // update the virtual URL when replaceState is called after a pushState.
2103 GURL url = params.url;
2104 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492105 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412106 // update the virtual URL based on the new URL. For example, this is needed
2107 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2108 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372109 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2110 &url, browser_context_, &needs_update);
2111 new_entry->set_update_virtual_url_with_url(needs_update);
2112
Camille Lamy62b826012019-02-26 09:15:472113 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452114 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432115 }
2116
Alison Gale770f3fc2024-04-27 00:39:582117 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2118 // set for prerendered contents, if any. This is because
2119 // prerendering/activation technically won't be creating a new document.
2120 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2121 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012122 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372123 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2124 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002125 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082126
Harkiran Bolaria59290d62021-03-17 01:53:012127 // history.pushState() is classified as a navigation to a new page, but sets
2128 // is_same_document to true. In this case, we already have the title and
2129 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452130 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012131 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2132 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2133 }
[email protected]3a868f212014-08-09 10:41:192134 }
[email protected]ff64b3e2014-05-31 04:07:332135
[email protected]60d6cca2013-04-30 08:47:132136 DCHECK(!params.history_list_was_cleared || !replace_entry);
2137 // The browser requested to clear the session history when it initiated the
2138 // navigation. Now we know that the renderer has updated its state accordingly
2139 // and it is safe to also clear the browser side history.
2140 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552141 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132142 entries_.clear();
2143 last_committed_entry_index_ = -1;
2144 }
2145
Nasko Oskovaee2f862018-06-15 00:05:522146 // If this is a new navigation with replacement and there is a
2147 // pending_entry_ which matches the navigation reported by the renderer
2148 // process, then it should be the one replaced, so update the
2149 // last_committed_entry_index_ to use it.
2150 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092151 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522152 last_committed_entry_index_ = pending_entry_index_;
2153 }
2154
Alexander Timine3ec4192020-04-20 16:39:402155 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562156 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402157 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052158
Yuzu Saijoa725585f2022-11-28 04:14:032159 // If this is a history navigation and the old entry has an existing
2160 // back/forward cache metrics object, keep using the old one so that the
2161 // reasons logged from the last time the page navigated gets preserved.
2162 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2163 request)) {
2164 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2165 // because some tests do not have a pending entry.
2166 NavigationEntryImpl* entry =
2167 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2168 if (entry && entry->back_forward_cache_metrics()) {
2169 scoped_refptr<BackForwardCacheMetrics> metrics =
2170 entry->TakeBackForwardCacheMetrics();
2171 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2172 }
2173 }
2174
Carlos IL42b416592019-10-07 23:10:362175 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312176 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152177 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432178}
2179
Charlie Reisc0f17d2d2021-01-12 18:52:492180void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322181 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072182 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362183 bool is_same_document,
jam48cea9082017-02-15 06:13:292184 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452185 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002186 bool keep_pending_entry,
2187 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562188 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2189 << "that a last committed entry exists.";
2190
[email protected]e9ba4472008-09-14 15:42:432191 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002192 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432193
Charlie Reis7e2cb6d2021-01-26 01:27:162194 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002195 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162196 // We're guaranteed to have a last committed entry if intended_as_new_entry
2197 // is true.
avicbdc4c12015-07-01 16:07:112198 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162199
2200 // If the NavigationRequest matches a new pending entry and is classified as
2201 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2202 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092203 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162204 // Note: The pending entry will usually have a real ReloadType here, but
2205 // it can still be ReloadType::NONE in cases that
2206 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2207
2208 // If we classified this correctly, the SiteInstance should not have
2209 // changed.
2210 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2211
2212 // For converted reloads, we assign the entry's unique ID to be that of
2213 // the new one. Since this is always the result of a user action, we want
2214 // to dismiss infobars, etc. like a regular user-initiated navigation.
2215 entry->set_unique_id(pending_entry_->GetUniqueID());
2216
2217 // The extra headers may have changed due to reloading with different
2218 // headers.
2219 entry->set_extra_headers(pending_entry_->extra_headers());
2220 }
2221 // Otherwise, this was intended as a new entry but the pending entry was
2222 // lost in the meantime and no new entry was created. We are stuck at the
2223 // last committed entry.
2224
2225 // Even if this is a converted reload from pressing enter in the omnibox,
2226 // the server could redirect, requiring an update to the SSL status. If this
2227 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452228 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162229 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472230 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452231 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162232 }
Rakina Zata Amnif6950d552020-11-24 03:26:102233 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112234 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102235 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162236
eugenebut604866f2017-05-10 21:35:362237 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452238 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362239 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2240 // this was a restored same document navigation entry, then it won't have
2241 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2242 // navigated it.
jam48cea9082017-02-15 06:13:292243 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522244 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2245 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292246 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2247 was_restored) {
2248 entry->GetSSL() = last_entry->GetSSL();
2249 }
2250 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452251 // In rapid back/forward navigations |request| sometimes won't have a cert
2252 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192253 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452254 if (request->GetSSLInfo().has_value() &&
2255 request->GetSSLInfo()->is_valid()) {
2256 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522257 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2258 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192259 entry->GetSSL() = SSLStatus();
2260 }
jam48cea9082017-02-15 06:13:292261 }
avicbdc4c12015-07-01 16:07:112262 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272263 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572264 // navigations that are EXISTING_ENTRY are same-document navigations that
2265 // result in replacement (e.g. history.replaceState(), location.replace(),
2266 // forced replacements for trivial session history contexts). For these
2267 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112268 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102269
Alison Gale81f4f2c72024-04-22 19:33:312270 // TODO(crbug.com/40532777): Set page transition type to
2271 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2272 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2273 // well as to fix the inconsistency with what we report to observers
2274 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102275
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572276 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102277
eugenebut604866f2017-05-10 21:35:362278 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452279 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362280 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472281 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452282 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112283 }
2284 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432285
Rakina Zata Amni3460d382021-10-29 00:43:372286 UpdateNavigationEntryDetails(entry, rfh, params, request,
2287 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002288 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302289
[email protected]5ccd4dc2012-10-24 02:28:142290 // The redirected to page should not inherit the favicon from the previous
2291 // page.
eugenebut604866f2017-05-10 21:35:362292 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482293 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142294
Charlie Reis951f43372023-05-05 00:30:072295 // Update the last committed index to reflect the committed entry. Do this
2296 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2297 // delegate sees the correct committed index when notified of navigation
2298 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2299 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212300 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072301
Peter Boströmd7592132019-01-30 04:50:312302 // We should also usually discard the pending entry if it corresponds to a
2303 // different navigation, since that one is now likely canceled. In rare
2304 // cases, we leave the pending entry for another navigation in place when we
2305 // know it is still ongoing, to avoid a flicker in the omnibox (see
2306 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432307 //
2308 // Note that we need to use the "internal" version since we don't want to
2309 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312310 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002311 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432312}
2313
[email protected]d202a7c2012-01-04 07:53:472314void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322315 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072316 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362317 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472318 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562319 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002320 NavigationRequest* request,
2321 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262322 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2323 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552324 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2325 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112326
[email protected]e9ba4472008-09-14 15:42:432327 // Manual subframe navigations just get the current entry cloned so the user
2328 // can go back or forward to it. The actual subframe information will be
2329 // stored in the page state for each of those entries. This happens out of
2330 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092331 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2332 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382333
Mikel Astizba9cf2fd2017-12-17 10:38:102334 // The DCHECK below documents the fact that we don't know of any situation
2335 // where |replace_entry| is true for subframe navigations. This simplifies
2336 // reasoning about the replacement struct for subframes (see
2337 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2338 DCHECK(!replace_entry);
2339
Patrick Monette50e8bd82019-06-13 22:40:452340 // This FrameNavigationEntry might not end up being used in the
2341 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372342 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452343 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372344 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522345 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2346 initiator_base_url = request->common_params().initiator_base_url;
2347 }
Nate Chapin63db0d12022-01-20 22:03:302348 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2349 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212350 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302351 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572352 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302353 if (is_same_document) {
2354 FrameNavigationEntry* previous_frame_entry =
2355 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572356 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302357 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572358 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302359 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572360 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302361 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572362 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302363 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572364 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302365 policy_container_policies->referrer_policy);
2366 }
2367
Patrick Monette50e8bd82019-06-13 22:40:452368 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482369 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572370 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082371 rfh->GetSiteInstance(), nullptr, params.url,
2372 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212373 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2374 request->GetRedirectChain(), params.page_state, params.method,
2375 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572376 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032377
creisce0ef3572017-01-26 17:53:082378 std::unique_ptr<NavigationEntryImpl> new_entry =
2379 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452380 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032381 frame_tree_->root());
creise062d542015-08-25 02:01:552382
Alexander Timine3ec4192020-04-20 16:39:402383 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562384 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402385 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472386
creisce0ef3572017-01-26 17:53:082387 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452388 // to replace, which can happen due to a unique name change. See
2389 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2390 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382391
Dave Tapuska87696ae2021-11-18 18:48:312392 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152393 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432394}
2395
[email protected]d202a7c2012-01-04 07:53:472396bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322397 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072398 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392399 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252400 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002401 NavigationRequest* request,
2402 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292403 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2404 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2405
[email protected]e9ba4472008-09-14 15:42:432406 // We're guaranteed to have a previously committed entry, and we now need to
2407 // handle navigation inside of a subframe in it without creating a new entry.
2408 DCHECK(GetLastCommittedEntry());
2409
creis913c63ce2016-07-16 19:52:522410 // For newly created subframes, we don't need to send a commit notification.
2411 // This is only necessary for history navigations in subframes.
2412 bool send_commit_notification = false;
2413
Rakina Zata Amnif6950d552020-11-24 03:26:102414 // If |nav_entry_id| is non-zero and matches an existing entry, this
2415 // is a history navigation. Update the last committed index accordingly. If
2416 // we don't recognize the |nav_entry_id|, it might be a recently
2417 // pruned entry. We'll handle it below.
2418 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2419 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472420 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062421 // Make sure that a subframe commit isn't changing the main frame's
2422 // origin. Otherwise the renderer process may be confused, leading to a
2423 // URL spoof. We can't check the path since that may change
2424 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572425 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2426 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242427 // We should use checks similar to RenderFrameHostImpl's
2428 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2429 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572430 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2431 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2432 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2433 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522434 current_top_url.DeprecatedGetOriginAsURL() !=
2435 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442436 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512437 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062438 }
creis3cdc3b02015-05-29 23:00:472439
creis913c63ce2016-07-16 19:52:522440 // We only need to discard the pending entry in this history navigation
2441 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062442 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002443 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522444
2445 // History navigations should send a commit notification.
2446 send_commit_notification = true;
avi98405c22015-05-21 20:47:062447 }
[email protected]e9ba4472008-09-14 15:42:432448 }
[email protected]f233e4232013-02-23 00:55:142449
creisce0ef3572017-01-26 17:53:082450 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2451 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372452 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2453 // exists), or we may want to clobber it and create a new one. We update in
2454 // cases where the corresponding FrameNavigationEntry is conceptually similar
2455 // to the document described by the commit params: same-document
2456 // navigations, history traversal to an existing entry, and reloads (including
2457 // a "soft reload" where we navigate to the same url without flagging it as a
2458 // reload). But in the case of a different document that is not logically
2459 // related to the committed FrameNavigationEntry's document (cross-document,
2460 // not same url, not a reload, not a history traversal), we replace rather
2461 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252462 //
Nate Chapin9f169072021-06-09 19:32:372463 // In the case where we update, the FrameNavigationEntry will potentially be
2464 // shared across multiple NavigationEntries, and any updates will be reflected
2465 // in all of those NavigationEntries. In the replace case, any existing
2466 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252467 //
2468 // When navigating away from the initial empty document, we also update rather
2469 // than replace. Either update or replace will overwrite the initial empty
2470 // document state for |last_committed|, but if the FrameNavigationEntry for
2471 // the initial empty document is shared across multiple NavigationEntries (due
2472 // to a navigation in another frame), we want to make sure we overwrite the
2473 // initial empty document state everywhere this FrameNavigationEntry is used,
2474 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452475 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372476 FrameNavigationEntry* last_committed_frame_entry =
2477 last_committed->GetFrameEntry(rfh->frame_tree_node());
2478 NavigationEntryImpl::UpdatePolicy update_policy =
2479 NavigationEntryImpl::UpdatePolicy::kUpdate;
2480 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312481 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372482 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252483 last_committed_frame_entry->url() != params.url &&
2484 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372485 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2486 }
2487
Rakina Zata Amni3460d382021-10-29 00:43:372488 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002489 update_policy, false /* is_new_entry */,
2490 commit_details);
creis625a0c7d2015-03-24 23:17:122491
creis913c63ce2016-07-16 19:52:522492 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432493}
2494
[email protected]d202a7c2012-01-04 07:53:472495int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232496 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032497 for (size_t i = 0; i < entries_.size(); ++i) {
2498 if (entries_[i].get() == entry)
2499 return i;
2500 }
2501 return -1;
[email protected]765b35502008-08-21 00:51:202502}
2503
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572504void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242505 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572506 NavigationControllerImpl* source =
2507 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572508 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382509 DCHECK_EQ(1, GetEntryCount());
2510 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472511 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172512 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572513
Francois Dorayeaace782017-06-21 16:37:242514 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442515 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572516 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572517
Fergal Dalya1d569972021-03-16 03:24:532518 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302519 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532520 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2521 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302522 }
[email protected]4e6419c2010-01-15 04:50:342523
Lukasz Anforowicz0de0f452020-12-02 19:57:152524 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572525}
2526
[email protected]79368982013-11-13 01:11:012527bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022528 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162529 if (last_committed_entry_index_ == -1)
2530 return false;
[email protected]9350602e2013-02-26 23:27:442531
[email protected]474f8512013-05-31 22:31:162532 // We cannot prune if there is a pending entry at an existing entry index.
2533 // It may not commit, so we have to keep the last committed entry, and thus
2534 // there is no sensible place to keep the pending entry. It is ok to have
2535 // a new pending entry, which can optionally commit as a new navigation.
2536 if (pending_entry_index_ != -1)
2537 return false;
2538
[email protected]474f8512013-05-31 22:31:162539 return true;
2540}
2541
[email protected]79368982013-11-13 01:11:012542void NavigationControllerImpl::PruneAllButLastCommitted() {
2543 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162544
avi2b177592014-12-10 02:08:022545 DCHECK_EQ(0, last_committed_entry_index_);
2546 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442547
Charlie Reis99b2eba22025-01-31 19:18:572548 BroadcastHistoryIndexAndLength();
[email protected]9350602e2013-02-26 23:27:442549}
2550
[email protected]79368982013-11-13 01:11:012551void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162552 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012553 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262554
Nate Chapin9eb16be72022-09-23 22:54:312555 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2556
[email protected]474f8512013-05-31 22:31:162557 // Erase all entries but the last committed entry. There may still be a
2558 // new pending entry after this.
2559 entries_.erase(entries_.begin(),
2560 entries_.begin() + last_committed_entry_index_);
2561 entries_.erase(entries_.begin() + 1, entries_.end());
2562 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262563}
2564
Christian Dullweber1af31e62018-02-22 11:49:482565void NavigationControllerImpl::DeleteNavigationEntries(
2566 const DeletionPredicate& deletionPredicate) {
2567 // It is up to callers to check the invariants before calling this.
2568 CHECK(CanPruneAllButLastCommitted());
2569 std::vector<int> delete_indices;
2570 for (size_t i = 0; i < entries_.size(); i++) {
2571 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572572 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482573 delete_indices.push_back(i);
2574 }
2575 }
2576 if (delete_indices.empty())
2577 return;
2578
2579 if (delete_indices.size() == GetEntryCount() - 1U) {
2580 PruneAllButLastCommitted();
2581 } else {
2582 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382583 for (const auto& index : base::Reversed(delete_indices)) {
2584 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482585 }
Charlie Reis99b2eba22025-01-31 19:18:572586 BroadcastHistoryIndexAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482587 }
2588 delegate()->NotifyNavigationEntriesDeleted();
2589}
2590
Carlos Caballero35ce710c2019-09-19 10:59:452591BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2592 return back_forward_cache_;
2593}
2594
William Liu055a3542023-04-02 17:21:192595NavigationEntryScreenshotCache*
2596NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212597 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262598 if (!nav_entry_screenshot_cache_ &&
2599 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192600 nav_entry_screenshot_cache_ =
2601 std::make_unique<NavigationEntryScreenshotCache>(
2602 BrowserContextImpl::From(browser_context_)
2603 ->GetNavigationEntryScreenshotManager()
2604 ->GetSafeRef(),
2605 this);
2606 }
2607 return nav_entry_screenshot_cache_.get();
2608}
2609
clamy987a3752018-05-03 17:36:262610void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2611 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2612 // progress, since this will cause a use-after-free. (We only allow this
2613 // when the tab is being destroyed for shutdown, since it won't return to
2614 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032615 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
Minoru Chikamune646eba42025-04-14 01:25:032616 if (can_be_in_navigate_to_pending_entry_ &&
2617 !frame_tree_->IsBeingDestroyed()) {
2618 CheckPotentialNavigationReentrancy();
2619 }
clamy987a3752018-05-03 17:36:262620
2621 if (was_failure && pending_entry_) {
2622 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2623 } else {
2624 failed_pending_entry_id_ = 0;
2625 }
2626
2627 if (pending_entry_) {
2628 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332629 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262630 pending_entry_index_ = -1;
2631 pending_entry_ = nullptr;
2632 }
arthursonzogni66f711c2019-10-08 14:40:362633
2634 // Ensure any refs to the current pending entry are ignored if they get
2635 // deleted, by clearing the set of known refs. All future pending entries will
2636 // only be affected by new refs.
2637 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262638}
2639
2640void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2641 if (pending_entry_)
2642 pending_entry_->set_ssl_error(error);
2643}
2644
Xiaohan Wang7f8052e02022-01-14 18:44:282645#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422646// static
2647bool NavigationControllerImpl::ValidateDataURLAsString(
2648 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2649 if (!data_url_as_string)
2650 return false;
2651
2652 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2653 return false;
2654
2655 // The number of characters that is enough for validating a data: URI.
2656 // From the GURL's POV, the only important part here is scheme, it doesn't
2657 // check the actual content. Thus we can take only the prefix of the url, to
2658 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562659 constexpr size_t kDataUriPrefixMaxLen = 64;
2660 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2661 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422662 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2663 return false;
2664
2665 return true;
2666}
2667#endif
2668
Shivani Sharma194877032019-03-07 17:52:472669void NavigationControllerImpl::NotifyUserActivation() {
2670 // When a user activation occurs, ensure that all adjacent entries for the
2671 // same document clear their skippable bit, so that the history manipulation
2672 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012673 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172674 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012675 // If the value of CanGoBack changes as a result of making some entries
2676 // non-skippable, then we must let the delegate know to update its UI state.
2677 // See https://crbug.com/1477784.
2678 if (!can_go_back && CanGoBack()) {
2679 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2680 }
Shivani Sharma194877032019-03-07 17:52:472681}
2682
clamy987a3752018-05-03 17:36:262683bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2684 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332685 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2686 blink::LocalFrameToken initiator_frame_token,
2687 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262688 NavigationEntryImpl* entry =
2689 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2690 if (!entry)
2691 return false;
2692
2693 FrameNavigationEntry* frame_entry =
2694 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2695 if (!frame_entry)
2696 return false;
2697
Camille Lamy5193caa2018-10-12 11:59:422698 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572699 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232700 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332701 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2702 initiator_process_id);
clamyea99ea12018-05-28 13:54:232703
2704 if (!request)
2705 return false;
2706
arthursonzognif046d4a2019-12-12 19:08:102707 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412708
Rakina Zata Amni1c83b082023-02-08 01:09:002709 SCOPED_CRASH_KEY_STRING256(
2710 "Bug1400009", "req_url",
2711 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2712 SCOPED_CRASH_KEY_NUMBER(
2713 "Bug1400009", "nav_entry_si",
2714 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2715 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2716 frame_entry->site_instance()
2717 ? ((int)frame_entry->site_instance()->GetId())
2718 : -1);
2719 bool has_sig =
2720 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2721 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2722 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2723 has_sig ? (!!frame_tree_->GetRenderViewHost(
2724 frame_entry->site_instance()->group()))
2725 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052726 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2727 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232728
2729 return true;
clamy987a3752018-05-03 17:36:262730}
2731
Tsuyoshi Horo52fd08e2020-07-07 07:03:452732bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2733 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2734 if (!entry)
2735 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432736
2737 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2738 // We should never navigate to an existing initial NavigationEntry that is
2739 // the initial NavigationEntry for the initial empty document that hasn't
2740 // been overridden by the synchronous about:blank commit, to preserve
2741 // legacy behavior where trying to reload when the main frame is on the
2742 // initial empty document won't result in a navigation. See also
2743 // https://crbug.com/1277414.
2744 return false;
2745 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452746 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2747 if (!frame_entry)
2748 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142749 ReloadType reload_type = ReloadType::NORMAL;
2750 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452751 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142752 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452753 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432754 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372755 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332756 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452757 if (!request)
2758 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052759 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452760 return true;
2761}
2762
clamy987a3752018-05-03 17:36:262763void NavigationControllerImpl::NavigateFromFrameProxy(
2764 RenderFrameHostImpl* render_frame_host,
2765 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022766 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452767 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372768 const std::optional<url::Origin>& initiator_origin,
2769 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262770 bool is_renderer_initiated,
2771 SiteInstance* source_site_instance,
2772 const Referrer& referrer,
2773 ui::PageTransition page_transition,
2774 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252775 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262776 const std::string& method,
2777 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092778 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142779 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212780 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502781 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372782 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292783 blink::mojom::NavigationInitiatorActivationAndAdStatus
2784 initiator_activation_and_ad_status,
Charlie Reise1d9b8182025-04-02 04:32:122785 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:222786 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492787 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462788 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452789 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582790 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032791 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342792 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372793 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582794 if (is_renderer_initiated)
2795 DCHECK(initiator_origin.has_value());
2796
clamy987a3752018-05-03 17:36:262797 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582798
Rakina Zata Amni2322f4f82022-01-24 13:24:242799 // Don't allow an entry replacement if there is no entry to replace.
2800 // http://crbug.com/457149
2801 if (GetEntryCount() == 0)
2802 should_replace_current_entry = false;
2803
clamy987a3752018-05-03 17:36:262804 // Create a NavigationEntry for the transfer, without making it the pending
2805 // entry. Subframe transfers should have a clone of the last committed entry
2806 // with a FrameNavigationEntry for the target frame. Main frame transfers
2807 // should have a new NavigationEntry.
2808 // TODO(creis): Make this unnecessary by creating (and validating) the params
2809 // directly, passing them to the destination RenderFrameHost. See
2810 // https://crbug.com/536906.
2811 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262812 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262813 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452814 DCHECK(GetLastCommittedEntry());
2815 entry = GetLastCommittedEntry()->Clone();
2816 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172817 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2818 // Renderer-initiated navigation that target a remote frame are currently
2819 // classified as browser-initiated when this one has already navigated.
2820 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372821 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2822 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2823 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2824 // same-document navigation), they will still be present in the
2825 // committed NavigationEntry that will be referenced to construct the new
2826 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262827 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082828 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582829 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372830 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212831 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152832 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262833 } else {
2834 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172835 // If `node` is the outermost main frame, it rewrites a virtual url in order
2836 // to adjust the original input url if needed. For inner frames such as
2837 // fenced frames or subframes, they don't rewrite urls as the urls are not
2838 // input urls by users.
2839 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372840 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322841 if (source_site_instance && source_site_instance->HasProcess()) {
2842 source_process_site_url =
2843 source_site_instance->GetProcess()->GetProcessLock().site_url();
2844 }
clamy987a3752018-05-03 17:36:262845 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212846 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322847 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212848 extra_headers, browser_context_, blob_url_loader_factory,
2849 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262850 entry->root_node()->frame_entry->set_source_site_instance(
2851 static_cast<SiteInstanceImpl*>(source_site_instance));
2852 entry->root_node()->frame_entry->set_method(method);
2853 }
clamy987a3752018-05-03 17:36:262854
Camille Lamy5193caa2018-10-12 11:59:422855 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452856 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262857 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422858 override_user_agent = true;
clamy987a3752018-05-03 17:36:262859 }
2860 // TODO(creis): Set user gesture and intent received timestamp on Android.
2861
2862 // We may not have successfully added the FrameNavigationEntry to |entry|
2863 // above (per https://crbug.com/608402), in which case we create it from
2864 // scratch. This works because we do not depend on |frame_entry| being inside
2865 // |entry| during NavigateToEntry. This will go away when we shortcut this
2866 // further in https://crbug.com/536906.
2867 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2868 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452869 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082870 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582871 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372872 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212873 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152874 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572875 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262876 }
2877
Camille Lamy5193caa2018-10-12 11:59:422878 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022879 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452880 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292881 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212882 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422883 params.source_site_instance = source_site_instance;
2884 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2885 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032886 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422887 params.referrer = referrer;
2888 /* params.redirect_chain: skip */
2889 params.extra_headers = extra_headers;
2890 params.is_renderer_initiated = is_renderer_initiated;
2891 params.override_user_agent = UA_OVERRIDE_INHERIT;
2892 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542893 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422894 /* params.data_url_as_string: skip */
2895 params.post_data = post_body;
2896 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582897 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422898 /* params.frame_name: skip */
2899 // TODO(clamy): See if user gesture should be propagated to this function.
2900 params.has_user_gesture = false;
2901 params.should_clear_history_list = false;
2902 params.started_from_context_menu = false;
2903 /* params.navigation_ui_data: skip */
2904 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222905 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542906 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212907 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412908 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502909 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292910 params.initiator_activation_and_ad_status =
2911 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032912 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422913
2914 std::unique_ptr<NavigationRequest> request =
2915 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032916 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142917 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392918 ReloadType::NONE, entry.get(), frame_entry.get(),
Charlie Reise1d9b8182025-04-02 04:32:122919 actual_navigation_start_time, navigation_start_time,
2920 is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582921 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:342922 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232923
2924 if (!request)
2925 return;
2926
Garrett Tanzerbb8db412022-09-27 21:59:462927 // Force the navigation to take place in a new browsing instance.
2928 // This is used by _unfencedTop in fenced frames to ensure that navigations
2929 // leaving the fenced context create a new browsing instance.
2930 if (force_new_browsing_instance) {
2931 request->coop_status().ForceBrowsingInstanceSwap();
2932 }
2933
Arthur Hemery948742762019-09-18 10:06:242934 // At this stage we are proceeding with this navigation. If this was renderer
2935 // initiated with user gesture, we need to make sure we clear up potential
2936 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2937 DiscardNonCommittedEntries();
2938
Lukasz Anforowicz9ee83c272020-12-01 20:14:052939 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262940}
2941
[email protected]d1198fd2012-08-13 22:50:192942void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252943 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212944 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192945 if (!session_storage_namespace)
2946 return;
2947
2948 // We can't overwrite an existing SessionStorage without violating spec.
2949 // Attempts to do so may give a tab access to another tab's session storage
2950 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152951 bool successful_insert =
2952 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252953 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052954 static_cast<SessionStorageNamespaceImpl*>(
2955 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302956 .second;
2957 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192958}
2959
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572960bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452961 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032962 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462963}
2964
Aran Gilman37d11632019-10-08 23:07:152965SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252966 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302967 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252968 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032969 DOMStorageContextWrapper* context_wrapper =
2970 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2971
2972 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252973 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032974 if (it != session_storage_namespace_map_.end()) {
2975 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152976 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2977 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472978
michaelnbacbcbd2016-02-09 00:32:032979 return it->second.get();
2980 }
2981
2982 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102983 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2984 SessionStorageNamespaceImpl::Create(context_wrapper);
2985 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2986 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252987 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102988 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302989
Daniel Murphy31bbb8b12018-02-07 21:44:102990 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302991}
2992
2993SessionStorageNamespace*
2994NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252995 return GetSessionStorageNamespace(
2996 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302997}
2998
2999const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573000NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303001 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553002}
[email protected]d202a7c2012-01-04 07:53:473003
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573004bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563005 return needs_reload_;
3006}
[email protected]a26023822011-12-29 00:23:553007
[email protected]46bb5e9c2013-10-03 22:16:473008void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413009 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3010}
3011
3012void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473013 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413014 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543015
3016 if (last_committed_entry_index_ != -1) {
3017 entries_[last_committed_entry_index_]->SetTransitionType(
3018 ui::PAGE_TRANSITION_RELOAD);
3019 }
[email protected]46bb5e9c2013-10-03 22:16:473020}
3021
[email protected]d202a7c2012-01-04 07:53:473022void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573023 DCHECK_LT(index, GetEntryCount());
3024 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313025 DiscardNonCommittedEntries();
3026
Nate Chapin9eb16be72022-09-23 22:54:313027 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313028 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123029 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313030 last_committed_entry_index_--;
3031}
3032
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573033NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273034 // If there is no pending_entry_, there should be no pending_entry_index_.
3035 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3036
3037 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363038 // at that index. An exception is while a reload of a post commit error page
3039 // is ongoing; in that case pending entry will point to the entry replaced
3040 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273041 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363042 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3043 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273044
[email protected]022af742011-12-28 18:37:253045 return pending_entry_;
3046}
3047
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573048int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273049 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273050 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553051 return pending_entry_index_;
3052}
3053
avi25764702015-06-23 15:43:373054void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573055 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363056 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313057 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003058 bool in_fenced_frame_tree,
3059 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313060 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3061 // set because:
3062 // 1) They don't influence the history of the outer page.
3063 // 2) They are always replace only navigation (there is always only one entry
3064 // in their history stack).
3065 // 3) Are not top level navigations and appear similar to iframes.
3066 // Navigations of the fenced frame might create a new NavigationEntry, which
3067 // will call this function. Non fenced frame navigations will never have
3068 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3069 // InsertOrReplaceEntry.
3070 DCHECK_EQ(in_fenced_frame_tree,
3071 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3072 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203073
avi5cad4912015-06-19 05:25:443074 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3075 // need to keep continuity with the pending entry, so copy the pending entry's
3076 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3077 // then the renderer navigated on its own, independent of the pending entry,
3078 // so don't copy anything.
3079 if (pending_entry_ && pending_entry_index_ == -1)
3080 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203081
Rakina Zata Amnia4e27222021-12-22 01:05:003082 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203083
creisee17e932015-07-17 17:56:223084 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453085 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103086 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573087 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363088 // If the new entry is a post-commit error page, we store the current last
3089 // committed entry to the side so that we can put it back when navigating
3090 // away from the error.
3091 if (was_post_commit_error) {
3092 DCHECK(!entry_replaced_by_post_commit_error_);
3093 entry_replaced_by_post_commit_error_ =
3094 std::move(entries_[last_committed_entry_index_]);
3095 }
dcheng36b6aec92015-12-26 06:16:363096 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223097 return;
3098 }
[email protected]765b35502008-08-21 00:51:203099
creis37979a62015-08-04 19:48:183100 // We shouldn't see replace == true when there's no committed entries.
3101 DCHECK(!replace);
3102
Michael Thiessen9b14d512019-09-23 21:19:473103 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203104
Shivani Sharmad8c8d652019-02-13 17:27:573105 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203106
dcheng36b6aec92015-12-26 06:16:363107 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203108 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293109}
3110
Shivani Sharmad8c8d652019-02-13 17:27:573111void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163112 if (entries_.size() < max_entry_count())
3113 return;
3114
3115 DCHECK_EQ(max_entry_count(), entries_.size());
3116 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573117 CHECK_EQ(pending_entry_index_, -1);
3118
3119 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423120 // Retrieve the oldest skippable entry.
3121 for (; index < GetEntryCount(); index++) {
3122 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3123 break;
Shivani Sharmad8c8d652019-02-13 17:27:573124 }
3125
3126 // If there is no skippable entry or if it is the last committed entry then
3127 // fall back to pruning the oldest entry. It is not safe to prune the last
3128 // committed entry.
3129 if (index == GetEntryCount() || index == last_committed_entry_index_)
3130 index = 0;
3131
3132 bool should_succeed = RemoveEntryAtIndex(index);
3133 DCHECK_EQ(true, should_succeed);
3134
3135 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253136}
3137
William Liu62ae26c2024-08-08 14:28:163138std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273139NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163140 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203141 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373142 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133143 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203144 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503145 TRACE_EVENT0("navigation",
3146 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273147 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023148 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363149 if (pending_entry_index_ != -1) {
3150 // The pending entry may not be in entries_ if a post-commit error page is
3151 // showing.
3152 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3153 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3154 }
Gyuyoung Kim107c2a02021-04-13 01:49:303155 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573156 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013157 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033158 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573159 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133160 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3161 // the same as the top level frame being navigated.
3162 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373163 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133164 }
Arthur Sonzogni620cec62018-12-13 13:08:573165
[email protected]83c2e232011-10-07 21:36:463166 // If we were navigating to a slow-to-commit page, and the user performs
3167 // a session history navigation to the last committed page, RenderViewHost
3168 // will force the throbber to start, but WebKit will essentially ignore the
3169 // navigation, and won't send a message to stop the throbber. To prevent this
3170 // from happening, we drop the navigation here and stop the slow-to-commit
3171 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023172 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083173 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273174 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033175 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123176
[email protected]83c2e232011-10-07 21:36:463177 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163178 return {};
[email protected]83c2e232011-10-07 21:36:463179 }
3180
Arthur Sonzognic686e8f2024-01-11 08:36:373181 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333182 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3183 if (initiator_rfh) {
3184 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543185 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333186 DCHECK(initiator_frame_token);
3187 }
3188
creisce0ef3572017-01-26 17:53:083189 // Compare FrameNavigationEntries to see which frames in the tree need to be
3190 // navigated.
clamy3cb9bea92018-07-10 12:42:023191 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3192 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333193 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3194 initiator_process_id, soft_navigation_heuristics_task_id,
3195 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303196
3197 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573198 // We were unable to match any frames to navigate. This can happen if a
3199 // history navigation targets a subframe that no longer exists
3200 // (https://crbug.com/705550). In this case, we need to update the current
3201 // history entry to the pending one but keep the main document loaded. We
3202 // also need to ensure that observers are informed about the updated
3203 // current history entry (e.g., for greying out back/forward buttons), and
Charlie Reis99b2eba22025-01-31 19:18:573204 // that renderer processes update their history indices. The easiest way
Alex Moshchuk3a4e77a2020-05-29 21:32:573205 // to do all that is to schedule a "redundant" same-document navigation in
3206 // the main frame.
3207 //
3208 // Note that we don't want to remove this history entry, as it might still
3209 // be valid later, since a frame that it's targeting may be recreated.
3210 //
3211 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3212 // need to repeat history navigations until finding the one that works.
3213 // Consider changing this behavior to keep looking for the first valid
3214 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023215 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423216 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573217 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573218 ReloadType::NONE /* reload_type */,
3219 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433220 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333221 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023222 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573223 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023224 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163225 return {};
clamy3cb9bea92018-07-10 12:42:023226 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573227 same_document_loads.push_back(std::move(navigation_request));
3228
3229 // Sanity check that we never take this branch for any kinds of reloads,
3230 // as those should've queued a different-document load in the main frame.
3231 DCHECK(!is_forced_reload);
3232 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303233 }
3234
Nate Chapinbf682fa32022-09-26 22:41:203235 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163236 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203237 if (initiator_rfh && initiator_rfh->IsSandboxed(
3238 network::mojom::WebSandboxFlags::kTopNavigation)) {
3239 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3240 initiator_rfh, same_document_loads) &&
3241 DoesSandboxNavigationStayWithinSubtree(
3242 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503243 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163244 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203245 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3246 initiator_rfh,
3247 navigates_inside_tree
3248 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3249 : blink::mojom::WebFeature::
3250 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523251
3252 // If the navigation occurred outside the tree discard it because
3253 // the sandboxed frame didn't have permission to navigate outside
3254 // its tree. If it is possible that the navigation is both inside and
3255 // outside the frame tree and we discard it entirely because we don't
3256 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143257 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203258 // If a |navigation_api_key| was provided, this navigation originated from
3259 // the navigation API. Notify the renderer that the navigation was
3260 // cancelled so the navigation API can fire an error event and reject the
3261 // relevant promise.
3262 if (navigation_api_key) {
3263 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3264 *navigation_api_key,
3265 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3266 }
Dave Tapuska855c1e12019-08-23 20:45:523267 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133268
3269 for (auto& unused_request : same_document_loads) {
3270 unused_request->set_navigation_discard_reason(
3271 NavigationDiscardReason::kNeverStarted);
3272 }
3273 for (auto& unused_request : different_document_loads) {
3274 unused_request->set_navigation_discard_reason(
3275 NavigationDiscardReason::kNeverStarted);
3276 }
William Liu62ae26c2024-08-08 14:28:163277 return {};
Dave Tapuska855c1e12019-08-23 20:45:523278 }
Dave Tapuska8bfd84c2019-03-26 20:47:163279 }
3280
Nate Chapin6c43c022023-02-13 23:32:423281 // If it is possible that this traverse may involve a same-document navigation
3282 // in the initiator and there is a Navigation API key involved, then we may
3283 // need to notify the initiator if it fails. (The early returns above either
3284 // do not involve these cases or already notify the initiator.)
3285 // The event only needs to fire for the initiator, and only if the initiator
3286 // itself is performing a same-document navigation (because the event will not
3287 // fire if it navigates cross-document).
3288 if (navigation_api_key) {
3289 for (auto& item : same_document_loads) {
3290 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3291 item->set_pending_navigation_api_key(*navigation_api_key);
3292 break;
3293 }
3294 }
3295 }
3296
Carlos Caballero539a421c2020-07-06 10:25:573297 // BackForwardCache:
3298 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563299 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573300 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3301 DCHECK_EQ(reload_type, ReloadType::NONE);
3302 auto navigation_request = CreateNavigationRequestFromEntry(
3303 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3304 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333305 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3306 initiator_process_id);
William Liuec04e382024-05-23 18:03:273307 base::WeakPtr<NavigationRequest> request = navigation_request->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053308 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Rakina Zata Amni58681c62024-06-25 06:32:133309
3310 for (auto& unused_request : same_document_loads) {
3311 unused_request->set_navigation_discard_reason(
3312 NavigationDiscardReason::kNeverStarted);
3313 }
3314 for (auto& unused_request : different_document_loads) {
3315 unused_request->set_navigation_discard_reason(
3316 NavigationDiscardReason::kNeverStarted);
3317 }
3318
William Liu62ae26c2024-08-08 14:28:163319 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_request;
3320 if (request) {
3321 bf_cache_request.push_back(std::move(request));
3322 }
3323 return bf_cache_request;
Carlos Caballero539a421c2020-07-06 10:25:573324 }
3325
3326 // History navigation might try to reuse a specific BrowsingInstance, already
3327 // used by a page in the cache. To avoid having two different main frames that
3328 // live in the same BrowsingInstance, evict the all pages with this
3329 // BrowsingInstance from the cache.
3330 //
3331 // For example, take the following scenario:
3332 //
3333 // A1 = Some page on a.com
3334 // A2 = Some other page on a.com
3335 // B3 = An uncacheable page on b.com
3336 //
3337 // Then the following navigations occur:
3338 // A1->A2->B3->A1
3339 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3340 // take its place) and A1 will be created in the same BrowsingInstance (and
3341 // SiteInstance), as A2.
3342 //
3343 // If we didn't do anything, both A1 and A2 would remain alive in the same
3344 // BrowsingInstance/SiteInstance, which is unsupported by
3345 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3346 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483347 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3348 pending_entry_->site_instance()
3349 ? pending_entry_->site_instance()->GetId().value()
3350 : -1);
3351 SCOPED_CRASH_KEY_NUMBER(
3352 "rvh_double", "pending_entry_bi",
3353 pending_entry_->site_instance()
3354 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3355 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573356 if (pending_entry_->site_instance()) {
3357 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3358 pending_entry_->site_instance());
3359 }
3360
Rakina Zata Amnid605d462022-06-01 10:17:033361 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3362 pending_entry_ && pending_entry_->IsRestored());
3363 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3364 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3365 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3366 pending_entry_index_);
3367 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3368 last_committed_entry_index_);
3369 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3370 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3371 pending_entry_ && pending_entry_->IsInitialEntry());
3372 SCOPED_CRASH_KEY_BOOL(
3373 "nav_reentrancy", "pending_entry_initial2",
3374 pending_entry_ &&
3375 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3376 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3377 IsInitialNavigation());
3378 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3379 IsInitialBlankNavigation());
3380 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3381 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3382 (int)pending_reload_);
3383
clamy3cb9bea92018-07-10 12:42:023384 // This call does not support re-entrancy. See http://crbug.com/347742.
3385 CHECK(!in_navigate_to_pending_entry_);
3386 in_navigate_to_pending_entry_ = true;
Minoru Chikamune646eba42025-04-14 01:25:033387 CheckPotentialNavigationReentrancy();
creis4e2ecb72015-06-20 00:46:303388
Rakina Zata Amnid605d462022-06-01 10:17:033389 // If the navigation-reentrancy is caused by calling
3390 // NavigateToExistingPendingEntry twice, this will note the previous call's
3391 // pending entry's ID.
3392 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3393 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3394
arthursonzogni66f711c2019-10-08 14:40:363395 // It is not possible to delete the pending NavigationEntry while navigating
3396 // to it. Grab a reference to delay potential deletion until the end of this
3397 // function.
3398 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3399
Nate Chapin154b14b2023-02-17 18:28:163400 // If there is a main-frame same-document history navigation, we may defer
3401 // the subframe history navigations in order to give JS in the main frame the
3402 // opportunity to cancel the entire traverse via the navigate event. In that
3403 // case, we need to stash the main frame request's navigation token on the
3404 // subframes, so they can look up the main frame request and defer themselves
3405 // until it completes.
3406 if (!same_document_loads.empty() &&
3407 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3408 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3409 // The token will only be returned in cases where deferring the navigation
3410 // is necessary.
3411 if (auto main_frame_same_document_token =
3412 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3413 for (auto& item : same_document_loads) {
3414 if (item.get() != main_frame_request) {
3415 item->set_main_frame_same_document_history_token(
3416 main_frame_same_document_token);
3417 }
3418 }
3419 for (auto& item : different_document_loads) {
3420 item->set_main_frame_same_document_history_token(
3421 main_frame_same_document_token);
3422 }
3423 }
3424 }
3425
William Liu122754942024-01-18 22:34:393426 if (!initiator_rfh) {
3427 // A browser-initiated navigation won't have a `initiator_rfh`.
3428 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3429 different_document_loads, same_document_loads);
3430 }
3431
William Liu62ae26c2024-08-08 14:28:163432 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3433 all_requests.reserve(same_document_loads.size() +
3434 different_document_loads.size());
3435 bool seen_primary_main_frame_request = false;
3436
creis4e2ecb72015-06-20 00:46:303437 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023438 for (auto& item : same_document_loads) {
3439 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273440 // The request could be destroyed before `navigator().Navigate()` returns.
3441 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053442 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163443 if (request) {
3444 // Can only have one primary main frame request.
3445 CHECK(!seen_primary_main_frame_request ||
3446 !request->IsInPrimaryMainFrame());
3447 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3448 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273449 }
creis4e2ecb72015-06-20 00:46:303450 }
clamy3cb9bea92018-07-10 12:42:023451 for (auto& item : different_document_loads) {
3452 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273453 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053454 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163455 if (request) {
3456 // Can only have one primary main frame request.
3457 CHECK(!seen_primary_main_frame_request ||
3458 !request->IsInPrimaryMainFrame());
3459 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3460 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273461 }
creis4e2ecb72015-06-20 00:46:303462 }
clamy3cb9bea92018-07-10 12:42:023463
3464 in_navigate_to_pending_entry_ = false;
William Liuec04e382024-05-23 18:03:273465
William Liu62ae26c2024-08-08 14:28:163466 return all_requests;
creis4e2ecb72015-06-20 00:46:303467}
3468
Alex Moshchuk3a4e77a2020-05-29 21:32:573469NavigationControllerImpl::HistoryNavigationAction
3470NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303471 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573472 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423473 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583474 // Only active and prerendered documents are allowed to navigate in their
3475 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423476 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013477 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583478 // - If the document is in pending deletion, the browser already committed
3479 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3480 // - If the document is in back-forward cache, it's not allowed to navigate
3481 // as it should remain frozen. Ignore the request and evict the document
3482 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423483 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583484 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423485 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113486 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3487 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423488 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113489 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423490 }
arthursonzogni03f76152019-02-12 10:35:203491
Alex Moshchuk3a4e77a2020-05-29 21:32:573492 // Reloads should result in a different-document load. Note that reloads may
3493 // also happen via the |needs_reload_| mechanism where the reload_type is
3494 // NONE, so detect this by comparing whether we're going to the same
3495 // entry that we're currently on. Similarly to above, only main frames
3496 // should reach this. Note that subframes support reloads, but that's done
3497 // via a different path that doesn't involve FindFramesToNavigate (see
3498 // RenderFrameHost::Reload()).
3499 if (reload_type != ReloadType::NONE ||
3500 pending_entry_index_ == last_committed_entry_index_) {
3501 DCHECK(frame->IsMainFrame());
3502 return HistoryNavigationAction::kDifferentDocument;
3503 }
3504
Alex Moshchuk47d1a4bd2020-06-01 22:15:343505 // If there is no new FrameNavigationEntry for the frame, ignore the
3506 // load. For example, this may happen when going back to an entry before a
3507 // frame was created. Suppose we commit a same-document navigation that also
3508 // results in adding a new subframe somewhere in the tree. If we go back,
3509 // the new subframe will be missing a FrameNavigationEntry in the previous
3510 // NavigationEntry, but we shouldn't delete or change what's loaded in
3511 // it.
3512 //
Alex Moshchuke65c39272020-06-03 17:55:373513 // Note that in this case, there is no need to keep looking for navigations
3514 // in subframes, which would be missing FrameNavigationEntries as well.
3515 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343516 // It's important to check this before checking |old_item| below, since both
3517 // might be null, and in that case we still shouldn't change what's loaded in
3518 // this frame. Note that scheduling any loads assumes that |new_item| is
3519 // non-null. See https://crbug.com/1088354.
3520 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3521 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373522 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343523
Charlie Reisa474fb62022-03-17 02:31:363524 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3525 // which history item it is currently on, since this may be different than the
3526 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3527 // (e.g., if a history navigation is targeting multiple frames and only some
3528 // have committed so far).
creis4e2ecb72015-06-20 00:46:303529 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363530 frame->current_frame_host()->last_committed_frame_entry();
3531 if (!old_item) {
3532 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3533 // fall back to the last committed NavigationEntry's record for this frame.
3534 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583535 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363536 // accurate FrameNavigationEntry and eliminate this case.
3537 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3538 }
3539 // If neither approach finds a FrameNavigationEntry, schedule a
3540 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583541 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573542 if (!old_item)
3543 return HistoryNavigationAction::kDifferentDocument;
3544
Alex Moshchuk3a4e77a2020-05-29 21:32:573545 // If the new item is not in the same SiteInstance, schedule a
3546 // different-document load. Newly restored items may not have a SiteInstance
3547 // yet, in which case it will be assigned on first commit.
3548 if (new_item->site_instance() &&
3549 new_item->site_instance() != old_item->site_instance())
3550 return HistoryNavigationAction::kDifferentDocument;
3551
Charlie Reis71e4ae32025-01-29 21:37:573552 // If the origins of the new and old items are both present but don't match,
3553 // schedule a different document load even if the document sequence numbers
3554 // somehow match.
3555 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3556 // committed origin on `new_item`, and update the Blink DSN computation to
3557 // avoid a cross-origin DSN match when possible.
3558 if (new_item->committed_origin().has_value() &&
3559 old_item->committed_origin().has_value() &&
3560 !new_item->committed_origin()->IsSameOriginWith(
3561 old_item->committed_origin().value())) {
3562 return HistoryNavigationAction::kDifferentDocument;
3563 }
3564
Alex Moshchuk3a4e77a2020-05-29 21:32:573565 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313566 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3567 // that we do this even if the history navigation would not be modifying this
3568 // frame were it live.
3569 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573570 return HistoryNavigationAction::kDifferentDocument;
3571
3572 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313573 // Starting a navigation after a crash early-promotes the speculative
3574 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3575 // committed yet, so we can not possibly perform a same-document history
3576 // navigation. The frame would need to be reloaded with a cross-document
3577 // navigation.
3578 if (!frame->current_frame_host()->has_committed_any_navigation())
3579 return HistoryNavigationAction::kDifferentDocument;
3580
creis54131692016-08-12 18:32:253581 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493582 // sequence number but different item sequence number.
3583 if (new_item->document_sequence_number() ==
3584 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573585 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493586 }
avib48cb312016-05-05 21:35:003587
Alex Moshchuk3a4e77a2020-05-29 21:32:573588 // Otherwise, if both item and document sequence numbers differ, this
3589 // should be a different document load.
3590 return HistoryNavigationAction::kDifferentDocument;
3591 }
3592
3593 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373594 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573595 DCHECK_EQ(new_item->document_sequence_number(),
3596 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373597 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573598}
3599
3600void NavigationControllerImpl::FindFramesToNavigate(
3601 FrameTreeNode* frame,
3602 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373603 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333604 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373605 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133606 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573607 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3608 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3609 DCHECK(pending_entry_);
3610 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3611
3612 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3613
3614 if (action == HistoryNavigationAction::kSameDocument) {
3615 std::unique_ptr<NavigationRequest> navigation_request =
3616 CreateNavigationRequestFromEntry(
3617 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133618 /*is_same_document_history_load=*/true,
3619 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333620 initiator_frame_token, initiator_process_id,
3621 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573622 if (navigation_request) {
3623 // Only add the request if was properly created. It's possible for the
3624 // creation to fail in certain cases, e.g. when the URL is invalid.
3625 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303626 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573627 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473628 std::unique_ptr<NavigationRequest> navigation_request =
3629 CreateNavigationRequestFromEntry(
3630 frame, pending_entry_, new_item, reload_type,
3631 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433632 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333633 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473634 if (navigation_request) {
3635 // Only add the request if was properly created. It's possible for the
3636 // creation to fail in certain cases, e.g. when the URL is invalid.
3637 different_document_loads->push_back(std::move(navigation_request));
3638 }
3639 // For a different document, the subframes will be destroyed, so there's
3640 // no need to consider them.
3641 return;
Alex Moshchuke65c39272020-06-03 17:55:373642 } else if (action == HistoryNavigationAction::kStopLooking) {
3643 return;
creis4e2ecb72015-06-20 00:46:303644 }
3645
Yoav Weiss8c573952022-11-17 17:35:133646 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3647 // we currently only support soft navigation heuristics for the top level
3648 // frame.
creis4e2ecb72015-06-20 00:46:303649 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333650 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3651 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373652 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433653 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303654 }
3655}
3656
Harkiran Bolariaba823e42021-05-21 18:30:363657base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243658 const LoadURLParams& params) {
3659 // Find the appropriate FrameTreeNode.
3660 FrameTreeNode* node = nullptr;
Avi Drissmanbd153642024-09-03 18:58:053661 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3662 node = params.frame_tree_node_id
Ali Hijazid87307d2022-11-07 20:15:033663 ? frame_tree_->FindByID(params.frame_tree_node_id)
3664 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503665 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243666 }
3667
3668 // If no FrameTreeNode was specified, navigate the main frame.
3669 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033670 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243671
Camille Lamy5193caa2018-10-12 11:59:423672 // Compute overrides to the LoadURLParams for |override_user_agent|,
3673 // |should_replace_current_entry| and |has_user_gesture| that will be used
3674 // both in the creation of the NavigationEntry and the NavigationRequest.
3675 // Ideally, the LoadURLParams themselves would be updated, but since they are
3676 // passed as a const reference, this is not possible.
3677 // TODO(clamy): When we only create a NavigationRequest, move this to
3678 // CreateNavigationRequestFromLoadURLParams.
3679 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3680 GetLastCommittedEntry());
3681
Rakina Zata Amnie2d31312022-11-18 03:38:453682 // An entry replacement must happen if the current browsing context should
3683 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333684 bool should_replace_current_entry =
3685 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453686 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423687
clamy21718cc22018-06-13 13:34:243688 // Javascript URLs should not create NavigationEntries. All other navigations
3689 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243690 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373691 std::unique_ptr<NavigationEntryImpl> entry =
3692 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3693 should_replace_current_entry,
3694 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243695 DiscardPendingEntry(false);
3696 SetPendingEntry(std::move(entry));
3697 }
3698
Tim Judkins59548192023-05-17 17:51:203699 // Renderer-debug URLs are sent to the current renderer process immediately
3700 // for processing and don't need to create a NavigationRequest. Note: this
3701 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243702 // renderer-debug URLs.
3703 // Note: we intentionally leave the pending entry in place for renderer debug
3704 // URLs, unlike the cases below where we clear it if the navigation doesn't
3705 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303706 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483707 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3708 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153709 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203710 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483711 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363712 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483713 }
3714
clamy21718cc22018-06-13 13:34:243715 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363716 return nullptr;
clamy21718cc22018-06-13 13:34:243717 }
3718
Antonio Sartori78a749f2020-11-30 12:03:393719 DCHECK(pending_entry_);
3720
clamy21718cc22018-06-13 13:34:243721 // Convert navigations to the current URL to a reload.
3722 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3723 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3724 // DevTools sometimes issues navigations to main frames that they do not
3725 // expect to see treated as reload, and it only works because they pass a
3726 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3727 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543728 ReloadType reload_type = params.reload_type;
3729 if (reload_type == ReloadType::NONE &&
3730 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043731 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243732 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243733 params.load_type ==
3734 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543735 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243736 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473737 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393738
3739 // If this is a reload of an existing FrameNavigationEntry and we had a
3740 // policy container for it, then we should copy it into the pending entry,
3741 // so that it is copied to the navigation request in
3742 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453743 FrameNavigationEntry* previous_frame_entry =
3744 GetLastCommittedEntry()->GetFrameEntry(node);
3745 if (previous_frame_entry &&
3746 previous_frame_entry->policy_container_policies()) {
3747 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3748 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393749 }
3750 }
3751
3752 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173753 // document, then we should copy the document polices from RenderFrameHost's
3754 // PolicyContainerHost. The NavigationRequest will create a new
3755 // PolicyContainerHost with the document policies from the |pending_entry_|,
3756 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3757 // the navigation. This way, we ensure that we keep enforcing the right
3758 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453759 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393760 if (node->current_frame_host() &&
3761 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193762 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163763 node->current_frame_host()
3764 ->policy_container_host()
3765 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233766 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393767 }
clamy21718cc22018-06-13 13:34:243768 }
3769
3770 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263771 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243772
Tsuyoshi Horo167ca6432022-03-09 05:16:393773 // This will be used to set the Navigation Timing API navigationStart
3774 // parameter for browser navigations in new tabs (intents, tabs opened through
3775 // "Open link in new tab"). If the navigation must wait on the current
3776 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3777 // will be updated when the BeforeUnload ack is received.
3778 const auto navigation_start_time = base::TimeTicks::Now();
Charlie Reise1d9b8182025-04-02 04:32:123779 // For now, treat this as the actual navigation start time as well, even
3780 // though a fair amount of work is done in the browser process between the
3781 // various ways to start a navigation and reaching here (e.g., sending
3782 // OpenURLParams through the embedder and converting them to LoadURLParams).
3783 // Note that this may be used for some renderer-initiated navigations that go
3784 // through RenderFrameHostImpl::OpenURL as well.
3785 // TODO(crbug.com/385170155): Consider whether tracking this earlier work with
3786 // an earlier start time is worthwhile for metrics.
3787 const auto actual_navigation_start_time = navigation_start_time;
Tsuyoshi Horo167ca6432022-03-09 05:16:393788
Camille Lamy5193caa2018-10-12 11:59:423789 std::unique_ptr<NavigationRequest> request =
3790 CreateNavigationRequestFromLoadParams(
3791 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143792 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393793 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
Charlie Reise1d9b8182025-04-02 04:32:123794 actual_navigation_start_time, navigation_start_time);
clamy21718cc22018-06-13 13:34:243795
3796 // If the navigation couldn't start, return immediately and discard the
3797 // pending NavigationEntry.
3798 if (!request) {
3799 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363800 return nullptr;
clamy21718cc22018-06-13 13:34:243801 }
3802
Camille Lamy5193caa2018-10-12 11:59:423803#if DCHECK_IS_ON()
3804 // Safety check that NavigationRequest and NavigationEntry match.
3805 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3806#endif
3807
clamy21718cc22018-06-13 13:34:243808 // This call does not support re-entrancy. See http://crbug.com/347742.
3809 CHECK(!in_navigate_to_pending_entry_);
3810 in_navigate_to_pending_entry_ = true;
Minoru Chikamune646eba42025-04-14 01:25:033811 CheckPotentialNavigationReentrancy();
clamy21718cc22018-06-13 13:34:243812
arthursonzogni66f711c2019-10-08 14:40:363813 // It is not possible to delete the pending NavigationEntry while navigating
3814 // to it. Grab a reference to delay potential deletion until the end of this
3815 // function.
3816 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3817
Harkiran Bolariaba823e42021-05-21 18:30:363818 base::WeakPtr<NavigationHandle> created_navigation_handle(
3819 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053820 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243821
3822 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363823 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243824}
3825
clamyea99ea12018-05-28 13:54:233826void NavigationControllerImpl::HandleRendererDebugURL(
3827 FrameTreeNode* frame_tree_node,
3828 const GURL& url) {
3829 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243830 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3831 // the renderer process is not live, unless it is the initial navigation
3832 // of the tab.
clamyea99ea12018-05-28 13:54:233833 if (!IsInitialNavigation()) {
3834 DiscardNonCommittedEntries();
3835 return;
3836 }
Fergal Dalyecd3b0202020-06-25 01:57:373837 // The current frame is always a main frame. If IsInitialNavigation() is
3838 // true then there have been no navigations and any frames of this tab must
3839 // be in the same renderer process. If that has crashed then the only frame
3840 // that can be revived is the main frame.
3841 frame_tree_node->render_manager()
3842 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233843 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223844
3845 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3846 // notification, so set is loading to true here to properly surface it when
3847 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313848 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223849 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223850 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223851 }
clamyea99ea12018-05-28 13:54:233852 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3853}
3854
clamy21718cc22018-06-13 13:34:243855std::unique_ptr<NavigationEntryImpl>
3856NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3857 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423858 const LoadURLParams& params,
3859 bool override_user_agent,
3860 bool should_replace_current_entry,
3861 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393862 // Browser initiated navigations might not have a blob_url_loader_factory set
3863 // in params even if the navigation is to a blob URL. If that happens, lookup
3864 // the correct url loader factory to use here.
3865 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483866 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473867 // Resolve the blob URL in the storage partition associated with the target
3868 // frame. This is the storage partition the URL will be loaded in, and only
3869 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393870 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473871 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393872 }
3873
clamy21718cc22018-06-13 13:34:243874 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443875 // extra_headers in params are \n separated; navigation entries want \r\n.
3876 std::string extra_headers_crlf;
3877 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243878
3879 // For subframes, create a pending entry with a corresponding frame entry.
3880 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453881 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243882 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083883 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243884 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373885 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213886 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3887 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393888 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163889 // a conversion of a new navigation into a reload, we will set the right
3890 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193891 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243892 } else {
3893 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173894 // If `node` is the outermost main frame, it rewrites a virtual url in order
3895 // to adjust the original input url if needed. For inner frames such as
3896 // fenced frames or subframes, they don't rewrite urls as the urls are not
3897 // input urls by users.
3898 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323899 scoped_refptr<SiteInstance> source_site_instance =
3900 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373901 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323902 if (source_site_instance && source_site_instance->HasProcess()) {
3903 source_process_site_url =
3904 source_site_instance->GetProcess()->GetProcessLock().site_url();
3905 }
clamy21718cc22018-06-13 13:34:243906 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063907 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323908 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213909 params.transition_type, params.is_renderer_initiated,
3910 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3911 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243912 entry->set_source_site_instance(
3913 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3914 entry->SetRedirectChain(params.redirect_chain);
3915 }
3916
3917 // Set the FTN ID (only used in non-site-per-process, for tests).
3918 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243919 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423920 entry->SetIsOverridingUserAgent(override_user_agent);
3921 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543922 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243923
clamy21718cc22018-06-13 13:34:243924 switch (params.load_type) {
3925 case LOAD_TYPE_DEFAULT:
3926 break;
3927 case LOAD_TYPE_HTTP_POST:
3928 entry->SetHasPostData(true);
3929 entry->SetPostData(params.post_data);
3930 break;
3931 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:543932 // LoadDataWithBaseURL is a special case that needs to assign both a base
3933 // URL and a virtual URL, while loading the actual content from a data
3934 // URL.
clamy21718cc22018-06-13 13:34:243935 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:543936 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:283937#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243938 entry->SetDataURLAsString(params.data_url_as_string);
3939#endif
3940 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3941 break;
Shu Yang112ad492024-07-25 17:11:543942#if BUILDFLAG(IS_ANDROID)
3943 case LOAD_TYPE_PDF_ANDROID:
3944 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
3945 // internal URL is used for the navigation URL.
3946 entry->SetVirtualURL(params.virtual_url_for_special_cases);
3947 break;
3948#endif
clamy21718cc22018-06-13 13:34:243949 }
3950
3951 // TODO(clamy): NavigationEntry is meant for information that will be kept
3952 // after the navigation ended and therefore is not appropriate for
3953 // started_from_context_menu. Move started_from_context_menu to
3954 // NavigationUIData.
3955 entry->set_started_from_context_menu(params.started_from_context_menu);
3956
3957 return entry;
3958}
3959
clamyea99ea12018-05-28 13:54:233960std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423961NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3962 FrameTreeNode* node,
3963 const LoadURLParams& params,
3964 bool override_user_agent,
3965 bool should_replace_current_entry,
3966 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143967 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423968 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573969 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393970 FrameNavigationEntry* frame_entry,
Charlie Reise1d9b8182025-04-02 04:32:123971 base::TimeTicks actual_navigation_start_time,
Nan Lin944e9b4e2022-04-12 13:51:223972 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493973 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453974 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583975 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343976 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:373977 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573978 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:523979
3980 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
3981 // subframes have FrameNavigationEntries associated with them. Until then,
3982 // there may be cases where a subframe navigation is missing `frame_entry`
3983 // (e.g., see https://crbug.com/358084015).
3984
Nasko Oskov3c2f9e252019-01-10 17:45:533985 // All renderer-initiated navigations must have an initiator_origin.
3986 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513987
Camille Lamy5193caa2018-10-12 11:59:423988 GURL url_to_load;
3989 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323990
Camille Lamy2baa8022018-10-19 16:43:173991 // For main frames, rewrite the URL if necessary and compute the virtual URL
3992 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263993 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423994 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173995 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423996 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423997
Shu Yang112ad492024-07-25 17:11:543998 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
3999 // that need to define a virtual URL to display, which differs from the
4000 // navigation URL.
4001 if (params.load_type == LOAD_TYPE_DATA) {
4002 virtual_url = params.virtual_url_for_special_cases;
4003 }
4004#if BUILDFLAG(IS_ANDROID)
4005 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
4006 virtual_url = params.virtual_url_for_special_cases;
4007 }
4008#endif
Camille Lamy5193caa2018-10-12 11:59:424009
Camille Lamy2baa8022018-10-19 16:43:174010 if (virtual_url.is_empty())
4011 virtual_url = url_to_load;
4012
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574013 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:284014
Aran Gilman249eb122019-12-02 23:32:464015 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
4016 // behavior: it is possible for two calls to RewriteUrlForNavigation to
4017 // return different results, leading to a different URL in the
4018 // NavigationRequest and FrameEntry. This will be fixed once we remove the
4019 // pending NavigationEntry, as we'll only make one call to
4020 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:524021 if (frame_entry) {
4022 VLOG_IF(1, (url_to_load != frame_entry->url()))
4023 << "NavigationRequest and FrameEntry have different URLs: "
4024 << url_to_load << " vs " << frame_entry->url();
4025 }
Camille Lamyb9ed3c52018-11-19 15:34:284026
Camille Lamy2baa8022018-10-19 16:43:174027 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424028 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174029 // NavigationRequest.
4030 } else {
4031 url_to_load = params.url;
4032 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244033 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174034 }
Camille Lamy5193caa2018-10-12 11:59:424035
Ehsan Karamad44fc72112019-02-26 18:15:474036 if (node->render_manager()->is_attaching_inner_delegate()) {
4037 // Avoid starting any new navigations since this node is now preparing for
4038 // attaching an inner delegate.
4039 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204040 }
Camille Lamy5193caa2018-10-12 11:59:424041
Alex Moshchuk99242832023-05-22 17:21:444042 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424043 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444044 }
Camille Lamy5193caa2018-10-12 11:59:424045
danakjd83d706d2020-11-25 22:11:124046 // Look for a pending commit that is to another document in this
4047 // FrameTreeNode. If one exists, then the last committed URL will not be the
4048 // current URL by the time this navigation commits.
4049 bool has_pending_cross_document_commit =
4050 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214051 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124052
Minggang Wangb9f3fa92021-07-01 15:30:314053 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494054 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524055 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494056 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134057 /*is_same_document_history_load=*/false,
4058 is_embedder_initiated_fenced_frame_navigation,
4059 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424060
4061 // Create the NavigationParams based on |params|.
4062
Hiroki Nakagawa4ed61282021-06-18 05:37:234063 bool is_view_source_mode = entry->IsViewSourceMode();
4064 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294065
Antonio Sartori6984c742021-08-26 08:03:414066 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294067
Hiroki Nakagawa4ed61282021-06-18 05:37:234068 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294069 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254070 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294071
Charlie Reisf21cd182024-08-09 21:44:524072 std::string page_state_data =
4073 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4074
Minggang Wangb9f3fa92021-07-01 15:30:314075 blink::mojom::CommonNavigationParamsPtr common_params =
4076 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214077 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514078 blink::mojom::Referrer::New(params.referrer.url,
4079 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214080 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514081 should_replace_current_entry, params.base_url_for_data_url,
Charlie Reise1d9b8182025-04-02 04:32:124082 actual_navigation_start_time, navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514083 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144084 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414085 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274086 false /* has_text_fragment_token */,
4087 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4088 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514089 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054090 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424091
Minggang Wangb9f3fa92021-07-01 15:30:314092 blink::mojom::CommitNavigationParamsPtr commit_params =
4093 blink::mojom::CommitNavigationParams::New(
Diana Quae845bf2025-04-03 20:12:374094 url::Origin(),
Ari Chivukulac7533522024-05-14 21:52:344095 // The correct storage key will be computed before committing the
4096 // navigation.
4097 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324098 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504099 std::vector<net::RedirectInfo>(), params.post_content_type,
4100 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524101 params.can_load_local_resources, page_state_data,
4102 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134103 /*intended_as_new_entry=*/true,
Charlie Reis99b2eba22025-01-31 19:18:574104 /*pending_history_list_index=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144105 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4106 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134107 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314108 params.should_clear_history_list,
4109 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224110 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134111 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514112 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284113#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134114 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144115#endif
Yoav Weiss8c573952022-11-17 17:35:134116 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154117 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134118 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074119 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134120 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4121 /*origin_agent_cluster=*/false,
4122 /*origin_agent_cluster_left_as_default=*/true,
4123 /*enabled_client_hints=*/
4124 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264125 /*is_cross_site_cross_browsing_context_group=*/false,
4126 /*should_have_sticky_user_activation=*/false,
4127 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134128 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014129 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134130 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584131 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134132 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134133 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284134 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134135 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444136 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424137 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374138 /*view_transition_state=*/std::nullopt,
4139 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054140 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464141 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374142 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054143 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094144 /*load_with_storage_access=*/
4145 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374146 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374147 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484148 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314149 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164150 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174151 node->current_frame_host()->GetCachedPermissionStatuses(),
Charlie Reiscdb798342025-02-14 22:04:464152 /*should_skip_screentshot=*/false,
4153 /*force_new_document_sequence_number=*/false);
Xiaohan Wang7f8052e02022-01-14 18:44:284154#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424155 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564156 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424157 }
4158#endif
4159
Lucas Furukawa Gadania9c45682019-07-31 22:05:144160 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074161 commit_params->navigation_timing->system_entropy_at_navigation_start =
4162 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4163 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424164
Camille Lamy5193caa2018-10-12 11:59:424165 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4166 std::string extra_headers_crlf;
4167 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094168
Alex Moshchuk9321e6a2022-12-07 21:58:314169 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144170 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084171 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094172 params.initiator_frame_token, params.initiator_process_id,
4173 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214174 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294175 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454176 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344177 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034178 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134179
4180 if (!navigation_request) {
4181 return nullptr;
4182 }
4183
Yao Xiaodc5ed102019-06-04 19:19:094184 navigation_request->set_from_download_cross_origin_redirect(
4185 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554186 navigation_request->set_force_new_browsing_instance(
4187 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514188 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434189 if (params.force_no_https_upgrade) {
4190 navigation_request->set_force_no_https_upgrade();
4191 }
Yao Xiaodc5ed102019-06-04 19:19:094192 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424193}
4194
4195std::unique_ptr<NavigationRequest>
4196NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234197 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574198 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234199 FrameNavigationEntry* frame_entry,
4200 ReloadType reload_type,
4201 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434202 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374203 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334204 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374205 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134206 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344207 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234208 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434209 // We should never navigate to an existing initial NavigationEntry that is the
4210 // initial NavigationEntry for the initial empty document that hasn't been
4211 // overridden by the synchronous about:blank commit, to preserve previous
4212 // behavior where trying to reload when the main frame is on the initial empty
4213 // document won't result in a navigation.
4214 // See also https://crbug.com/1277414.
4215 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324216
clamyea99ea12018-05-28 13:54:234217 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234218
Ehsan Karamad44fc72112019-02-26 18:15:474219 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4220 // Avoid starting any new navigations since this node is now preparing for
4221 // attaching an inner delegate.
4222 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204223 }
4224
Alex Moshchuk99242832023-05-22 17:21:444225 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4226 dest_url)) {
clamyea99ea12018-05-28 13:54:234227 return nullptr;
4228 }
4229
clamyea99ea12018-05-28 13:54:234230 // This will be used to set the Navigation Timing API navigationStart
4231 // parameter for browser navigations in new tabs (intents, tabs opened through
4232 // "Open link in new tab"). If the navigation must wait on the current
4233 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4234 // will be updated when the BeforeUnload ack is received.
Charlie Reise1d9b8182025-04-02 04:32:124235 // TODO(crbug.com/385170155): Consider whether to track an earlier
4236 // `actual_navigation_start` by plumbing it from the the initiator (e.g.,
4237 // for renderer-initiated history navigations, etc).
clamyea99ea12018-05-28 13:54:234238 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074239 const auto navigation_start_system_entropy =
4240 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4241 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234242
danakjd83d706d2020-11-25 22:11:124243 // Look for a pending commit that is to another document in this
4244 // FrameTreeNode. If one exists, then the last committed URL will not be the
4245 // current URL by the time this navigation commits.
4246 bool has_pending_cross_document_commit =
4247 frame_tree_node->render_manager()
4248 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494249 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214250 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124251
Minggang Wangb9f3fa92021-07-01 15:30:314252 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124253 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524254 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494255 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494256 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134257 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494258 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424259
4260 // A form submission may happen here if the navigation is a
4261 // back/forward/reload navigation that does a form resubmission.
4262 scoped_refptr<network::ResourceRequestBody> request_body;
4263 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394264 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504265 // entry. This way, it could be directly retrieved here. Right now, it is only
4266 // partially recovered when request.method == "POST" and request.body exists.
4267 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424268 if (frame_entry->method() == "POST") {
4269 request_body = frame_entry->GetPostData(&post_content_type);
4270 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304271 post_content_type = std::string(
4272 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504273 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424274 }
4275
4276 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314277 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514278 entry->ConstructCommonNavigationParams(
4279 *frame_entry, request_body, dest_url,
4280 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Charlie Reise1d9b8182025-04-02 04:32:124281 navigation_type, /*actual_navigation_start=*/navigation_start,
4282 navigation_start,
4283 /*input_start=*/base::TimeTicks());
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514284 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554285 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424286
4287 // TODO(clamy): |intended_as_new_entry| below should always be false once
4288 // Reload no longer leads to this being called for a pending NavigationEntry
4289 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314290 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144291 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404292 *frame_entry, common_params->url, common_params->method,
4293 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144294 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534295 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484296 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134297 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074298 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144299 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074300 commit_params->navigation_timing->system_entropy_at_navigation_start =
4301 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4302 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164303 commit_params->initial_permission_statuses =
4304 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424305
W. James MacLeanb7d6092682022-10-05 15:23:264306 if (common_params->url.IsAboutSrcdoc()) {
4307 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4308 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594309 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264310 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334311 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314312 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144313 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434314 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334315 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4316 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374317 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294318 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4319 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474320 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234321}
4322
[email protected]d202a7c2012-01-04 07:53:474323void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214324 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274325 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404326
Takashi Toyoshimaea534ef22021-07-21 03:27:594327 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404328 // location bar will have up-to-date information about the security style
4329 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134330 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404331
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374332 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574333 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294334}
4335
initial.commit09911bf2008-07-26 23:55:294336// static
[email protected]d202a7c2012-01-04 07:53:474337size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234338 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154339 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214340 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234341}
4342
[email protected]d202a7c2012-01-04 07:53:474343void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224344 if (is_active && needs_reload_)
4345 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214346
4347 if (frame_tree_->is_primary();
4348 auto* cache = GetNavigationEntryScreenshotCache()) {
4349 cache->SetVisible(is_active);
4350 }
initial.commit09911bf2008-07-26 23:55:294351}
4352
[email protected]d202a7c2012-01-04 07:53:474353void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034354 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4355 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294356 if (!needs_reload_)
4357 return;
4358
Bo Liucdfa4b12018-11-06 00:21:444359 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4360 needs_reload_type_);
4361
initial.commit09911bf2008-07-26 23:55:294362 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004363 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294364 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004365 if (entry_replaced_by_post_commit_error_) {
4366 // If the current entry is a post commit error, we reload the entry it
4367 // replaced instead. We leave the error entry in place until a commit
4368 // replaces it, but the pending entry points to the original entry in the
4369 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4370 // case that pending_entry_ != entries_[pending_entry_index_].
4371 // Note that this handling is similar to
4372 // `NavigationControllerImpl::Reload()`.
4373 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4374 pending_entry_index_ = GetCurrentEntryIndex();
4375 NavigateToExistingPendingEntry(
4376 ReloadType::NONE,
4377 /*initiator_rfh=*/nullptr,
4378 /*soft_navigation_heuristics_task_id=*/std::nullopt,
4379 /*navigation_api_key=*/nullptr);
4380 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134381 NavigateToExistingPendingEntry(
4382 ReloadType::NONE,
4383 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374384 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134385 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454386 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434387 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274388 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344389 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134390 NavigateToExistingPendingEntry(
4391 ReloadType::NONE,
4392 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374393 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134394 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344395 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434396 // We should never navigate to an existing initial NavigationEntry that is
4397 // the initial NavigationEntry for the initial empty document that hasn't
4398 // been overridden by the synchronous about:blank commit, to preserve
4399 // legacy behavior where trying to reload when the main frame is on the
4400 // initial empty document won't result in a navigation. See also
4401 // https://crbug.com/1277414. If there is something to reload, the
4402 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4403 // it here.
avicc872d7242015-08-19 21:26:344404 needs_reload_ = false;
4405 }
initial.commit09911bf2008-07-26 23:55:294406}
4407
Kevin McNeeccca6172021-10-19 17:11:144408base::WeakPtr<NavigationHandle>
4409NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364410 RenderFrameHost* render_frame_host,
4411 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364412 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134413 RenderFrameHostImpl* rfhi =
4414 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584415
4416 // Only active documents can load post-commit error pages:
4417 // - If the document is in pending deletion, the browser already committed to
4418 // destroying this RenderFrameHost so ignore loading the error page.
4419 // - If the document is in back-forward cache, it's not allowed to navigate as
4420 // it should remain frozen. Ignore the request and evict the document from
4421 // back-forward cache.
4422 // - If the document is prerendering, it can navigate but when loading error
4423 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114424 if (rfhi->IsInactiveAndDisallowActivation(
4425 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144426 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114427 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584428
Rakina Zata Amni919b7922020-12-11 09:03:134429 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414430
Minggang Wangb9f3fa92021-07-01 15:30:314431 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434432 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594433 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4434 // the frame actually committed (e.g. iframe with "src" set to a
4435 // slow-responding URL). We should rewrite the URL to about:blank in this
4436 // case, as the renderer will only think a page is an error page if it has a
4437 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134438 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314439 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434440 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334441 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414442
Mike Jacksone2aa7af2023-05-17 06:45:074443 commit_params->navigation_timing->system_entropy_at_navigation_start =
4444 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4445 node, blink::mojom::SystemEntropy::kNormal);
4446
arthursonzogni70ac7302020-05-28 08:49:054447 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4448 // error pages.
Liam Brady34639ec92023-10-13 19:50:454449 commit_params->frame_policy = node->pending_frame_policy();
arthursonzogni70ac7302020-05-28 08:49:054450
John Delaney131ad362019-08-08 21:57:414451 std::unique_ptr<NavigationRequest> navigation_request =
4452 NavigationRequest::CreateBrowserInitiated(
4453 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094454 false /* was_opener_suppressed */, "" /* extra_headers */,
4455 nullptr /* frame_entry */, nullptr /* entry */,
4456 false /* is_form_submission */, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374457 std::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364458 navigation_request->set_post_commit_error_page_html(error_page_html);
Lei Zhanga4770832023-07-19 18:02:364459 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
Charlie Reis09952ee2022-12-08 16:35:074460 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414461 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144462
4463 // Calling BeginNavigation may destroy the NavigationRequest.
4464 base::WeakPtr<NavigationRequest> created_navigation_request(
4465 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414466 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144467 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414468}
4469
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574470void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214471 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094472 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154473 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144474 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294475}
4476
[email protected]d202a7c2012-01-04 07:53:474477void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364478 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584479 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474480 // represent a no-committed-entry state.
4481 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364482 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584483 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474484 // if `entries_` contains pre-existing entries from the NavigationController
4485 // before restore, which would not be removed and will be at the front of the
4486 // entries list, causing the index to be off by the amount of pre-existing
4487 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294488 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294489}
[email protected]765b35502008-08-21 00:51:204490
arthursonzogni69a6a1b2019-09-17 09:23:004491void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004492 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4493}
4494
4495void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4496 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474497 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104498 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4499 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294500 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474501 return;
Michael Thiessenc5676d22019-09-25 22:32:104502 }
avi45a72532015-04-07 21:01:454503 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314504
4505 if (!delegate_)
4506 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374507 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484508}
4509
avi7c6f35e2015-05-08 17:52:384510int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4511 int nav_entry_id) const {
4512 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4513 if (entries_[i]->GetUniqueID() == nav_entry_id)
4514 return i;
4515 }
4516 return -1;
4517}
4518
[email protected]d202a7c2012-01-04 07:53:474519void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574520 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254521 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574522 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594523 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254524 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374525 // Normally, cloning a NavigationEntryImpl results in sharing
4526 // FrameNavigationEntries between the original and the clone. However, when
4527 // cloning from a different NavigationControllerImpl, we want to fork the
4528 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374529 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594530 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254531 }
Rakina Zata Amnie2d31312022-11-18 03:38:454532 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274533 DCHECK(pending_entry_index_ == -1 ||
4534 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254535}
[email protected]c5b88d82012-10-06 17:03:334536
4537void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184538 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334539 get_timestamp_callback_ = get_timestamp_callback;
4540}
[email protected]8ff00d72012-10-23 19:12:214541
Shivani Sharmaffb32b82019-04-09 16:58:474542// History manipulation intervention:
4543void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474544 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564545 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404546 bool is_renderer_initiated,
4547 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564548 // Note that for a subframe,
4549 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454550 // gesture happened in any subframe (propagated to main frame) or in the main
4551 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564552 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274553 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474554 return;
4555 }
4556 if (last_committed_entry_index_ == -1)
4557 return;
4558
Shivani Sharmac4cc8922019-04-18 03:11:174559 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474560
Alexander Timine3ec4192020-04-20 16:39:404561 // Log UKM with the URL we are navigating away from.
4562 ukm::builders::HistoryManipulationIntervention(
4563 previous_page_load_ukm_source_id)
4564 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474565}
4566
Shivani Sharmac4cc8922019-04-18 03:11:174567void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4568 int reference_index,
4569 bool skippable) {
4570 auto* reference_entry = GetEntryAtIndex(reference_index);
4571 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4572
4573 int64_t document_sequence_number =
4574 reference_entry->root_node()->frame_entry->document_sequence_number();
4575 for (int index = 0; index < GetEntryCount(); index++) {
4576 auto* entry = GetEntryAtIndex(index);
4577 if (entry->root_node()->frame_entry->document_sequence_number() ==
4578 document_sequence_number) {
4579 entry->set_should_skip_on_back_forward_ui(skippable);
4580 }
4581 }
4582}
4583
arthursonzogni66f711c2019-10-08 14:40:364584std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4585NavigationControllerImpl::ReferencePendingEntry() {
4586 DCHECK(pending_entry_);
4587 auto pending_entry_ref =
4588 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4589 pending_entry_refs_.insert(pending_entry_ref.get());
4590 return pending_entry_ref;
4591}
4592
4593void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4594 // Ignore refs that don't correspond to the current pending entry.
4595 auto it = pending_entry_refs_.find(ref);
4596 if (it == pending_entry_refs_.end())
4597 return;
4598 pending_entry_refs_.erase(it);
4599
4600 if (!pending_entry_refs_.empty())
4601 return;
4602
4603 // The pending entry may be deleted before the last PendingEntryRef.
4604 if (!pending_entry_)
4605 return;
4606
4607 // We usually clear the pending entry when the matching NavigationRequest
4608 // fails, so that an arbitrary URL isn't left visible above a committed page.
4609 //
4610 // However, we do preserve the pending entry in some cases, such as on the
4611 // initial navigation of an unmodified blank tab. We also allow the delegate
4612 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4613 // user edit the URL and try again. This may be useful in cases that the
4614 // committed page cannot be attacker-controlled. In these cases, we still
4615 // allow the view to clear the pending entry and typed URL if the user
4616 // requests (e.g., hitting Escape with focus in the address bar).
4617 //
4618 // Do not leave the pending entry visible if it has an invalid URL, since this
4619 // might be formatted in an unexpected or unsafe way.
4620 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364621 bool should_preserve_entry =
4622 (pending_entry_ == GetVisibleEntry()) &&
4623 pending_entry_->GetURL().is_valid() &&
4624 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4625 if (should_preserve_entry)
4626 return;
4627
4628 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374629 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364630}
4631
Titouan Rigoudy6ec70402021-02-02 15:42:194632std::unique_ptr<PolicyContainerPolicies>
4633NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394634 RenderFrameHostImpl* rfh,
4635 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214636 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174637 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214638 if (navigation_encountered_error) {
4639 // We should never reload the policy container of an error page from
4640 // history, see https://crbug.com/364773822.
4641 return nullptr;
4642 }
4643
Antonio Sartori78a749f2020-11-30 12:03:394644 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454645 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394646 FrameNavigationEntry* previous_frame_entry =
4647 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4648
Alison Gale770f3fc2024-04-27 00:39:584649 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394650 // ensure we always have a FrameNavigationEntry here.
4651 if (!previous_frame_entry)
4652 return nullptr;
4653
Titouan Rigoudy6ec70402021-02-02 15:42:194654 const PolicyContainerPolicies* previous_policies =
4655 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394656
Titouan Rigoudy6ec70402021-02-02 15:42:194657 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394658 return nullptr;
4659
4660 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234661 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394662 }
4663
Titouan Rigoudy72f892d2022-05-02 18:21:234664 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394665}
4666
Charlie Reis99b2eba22025-01-31 19:18:574667void NavigationControllerImpl::BroadcastHistoryIndexAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504668 OPTIONAL_TRACE_EVENT2(
Charlie Reis99b2eba22025-01-31 19:18:574669 "content", "NavigationControllerImpl::BroadcastHistoryIndexAndLength",
4670 "history_index", GetLastCommittedEntryIndex(), "history_length",
Hayato Ito2c8c08d02021-06-23 03:38:434671 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504672
Charlie Reis99b2eba22025-01-31 19:18:574673 int history_index = GetLastCommittedEntryIndex();
Kevin McNee7705fe82024-11-07 18:56:314674 int history_length = GetEntryCount();
Charlie Reis99b2eba22025-01-31 19:18:574675 auto callback = [history_index, history_length](RenderViewHostImpl* rvh) {
Kevin McNee7705fe82024-11-07 18:56:314676 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
Charlie Reis99b2eba22025-01-31 19:18:574677 broadcast->SetHistoryIndexAndLength(history_index, history_length);
Kevin McNee7705fe82024-11-07 18:56:314678 }
4679 };
Ali Hijazid87307d2022-11-07 20:15:034680 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504681}
4682
4683void NavigationControllerImpl::DidAccessInitialMainDocument() {
4684 // We may have left a failed browser-initiated navigation in the address bar
4685 // to let the user edit it and try again. Clear it now that content might
4686 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034687 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504688 DiscardPendingEntry(false);
4689
4690 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374691 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504692}
4693
4694void NavigationControllerImpl::UpdateStateForFrame(
4695 RenderFrameHostImpl* rfhi,
4696 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564697 OPTIONAL_TRACE_EVENT1("content",
4698 "NavigationControllerImpl::UpdateStateForFrame",
4699 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504700 // The state update affects the last NavigationEntry associated with the given
4701 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4702 // in the case of an UpdateState from a frame being swapped out). We track
4703 // which entry this is in the RenderFrameHost's nav_entry_id.
4704 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4705 if (!entry)
4706 return;
4707
4708 FrameNavigationEntry* frame_entry =
4709 entry->GetFrameEntry(rfhi->frame_tree_node());
4710 if (!frame_entry)
4711 return;
4712
4713 // The SiteInstance might not match if we do a cross-process navigation with
4714 // replacement (e.g., auto-subframe), in which case the swap out of the old
4715 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4716 // has already been replaced and destroyed.
4717 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4718 return;
4719
4720 if (page_state == frame_entry->page_state())
4721 return; // Nothing to update.
4722
4723 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4724
4725 // The document_sequence_number and item_sequence_number recorded in the
4726 // FrameNavigationEntry should not differ from the one coming with the update,
4727 // since it must come from the same document. Do not update it if a difference
4728 // is detected, as this indicates that |frame_entry| is not the correct one.
4729 blink::ExplodedPageState exploded_state;
4730 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4731 return;
4732
4733 if (exploded_state.top.document_sequence_number !=
4734 frame_entry->document_sequence_number() ||
4735 exploded_state.top.item_sequence_number !=
4736 frame_entry->item_sequence_number()) {
4737 return;
4738 }
4739
4740 frame_entry->SetPageState(page_state);
4741 NotifyEntryChanged(entry);
4742}
4743
Nate Chapina2c881f52023-11-07 17:02:094744namespace {
4745
4746// The caller is responsible for ensuring the entry is same-origin to the
4747// origin to be committed.
4748blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4749 FrameNavigationEntry* frame_entry,
4750 int64_t pending_document_sequence_number) {
4751 blink::ExplodedPageState exploded_state;
4752 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4753 &exploded_state)) {
4754 return nullptr;
4755 }
4756 blink::ExplodedFrameState frame_state = exploded_state.top;
4757
4758 // If the document represented by this FNE hid its full url from appearing in
4759 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4760 // in the navigation API as well (unless we're navigating to that document).
4761 std::u16string url;
4762 if (pending_document_sequence_number ==
4763 frame_entry->document_sequence_number() ||
4764 !frame_entry->protect_url_in_navigation_api()) {
4765 url = frame_state.url_string.value_or(std::u16string());
4766 }
4767
4768 return blink::mojom::NavigationApiHistoryEntry::New(
4769 frame_state.navigation_api_key.value_or(std::u16string()),
4770 frame_state.navigation_api_id.value_or(std::u16string()), url,
4771 frame_state.item_sequence_number, frame_state.document_sequence_number,
4772 frame_state.navigation_api_state);
4773}
4774
4775} // namespace
4776
Domenic Denicolacd30f5f82022-03-16 21:48:014777std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4778NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574779 Direction direction,
4780 int entry_index,
4781 const url::Origin& pending_origin,
4782 FrameTreeNode* node,
4783 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304784 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094785 int64_t pending_document_sequence_number,
4786 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014787 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454788 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174789 // Don't process the initial entry.
4790 DCHECK_EQ(GetEntryCount(), 1);
4791 return entries;
4792 }
Nate Chapind1fe3612021-04-16 20:45:574793 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304794 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574795 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4796 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094797 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574798 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414799 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574800 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014801 // An entry should only appear in the navigation API entries if it is for
4802 // the same origin as the document being committed. Check the committed
4803 // origin, or if that is not available (during restore), check against the
4804 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584805 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094806 // once we can be sure that entries with the same ISN will never be
4807 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414808 url::Origin frame_entry_origin =
4809 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4810 frame_entry->url(),
4811 frame_entry->initiator_origin().value_or(url::Origin())));
4812 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574813 break;
4814 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4815 continue;
Nate Chapina2c881f52023-11-07 17:02:094816 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4817 ToNavigationApiHistoryEntry(frame_entry,
4818 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304819 DCHECK(entry->url.empty() ||
4820 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574821 entries.push_back(std::move(entry));
4822 previous_item_sequence_number = frame_entry->item_sequence_number();
4823 }
4824 }
4825 // If |entries| was constructed by iterating backwards from
4826 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4827 // earliest-at-the-front. Reverse it.
4828 if (direction == Direction::kBack)
4829 std::reverse(entries.begin(), entries.end());
4830 return entries;
4831}
4832
Domenic Denicolacd30f5f82022-03-16 21:48:014833blink::mojom::NavigationApiHistoryEntryArraysPtr
4834NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554835 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574836 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404837 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444838 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404839 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574840
Nate Chapind1fe3612021-04-16 20:45:574841 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554842 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574843
Nate Chapine82339d02022-05-03 23:48:254844 // NOTE: |entry_index| is the index where this entry will commit if no
4845 // modifications are made between now and DidCommitNavigation. This is used to
4846 // walk |entries_| and determine which entries should be exposed by the
4847 // navigation API. It is important to calculate this correctly, because blink
4848 // will cancel a same-document history commit if it's not present in the
4849 // entries blink knows about.
4850 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574851 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304852 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254853 bool will_create_new_entry = false;
4854 if (GetPendingEntryIndex() != -1) {
4855 entry_index = GetPendingEntryIndex();
4856 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4857 pending_item_sequence_number = frame_entry->item_sequence_number();
4858 pending_document_sequence_number =
4859 frame_entry->document_sequence_number();
4860 }
4861 } else if (request &&
4862 !NavigationTypeUtils::IsReload(
4863 request->common_params().navigation_type) &&
4864 !NavigationTypeUtils::IsHistory(
4865 request->common_params().navigation_type) &&
4866 !request->common_params().should_replace_current_entry &&
4867 !request->common_params()
4868 .is_history_navigation_in_new_child_frame) {
4869 will_create_new_entry = true;
4870 entry_index = GetLastCommittedEntryIndex() + 1;
4871 // Don't set pending_item_sequence_number or
4872 // pending_document_sequence_number in this case - a new unique isn/dsn will
4873 // be calculated in the renderer later.
4874 } else if (GetLastCommittedEntryIndex() != -1) {
4875 entry_index = GetLastCommittedEntryIndex();
4876 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574877 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304878 pending_document_sequence_number =
4879 frame_entry->document_sequence_number();
4880 }
Nate Chapind1fe3612021-04-16 20:45:574881 }
4882
Domenic Denicolacd30f5f82022-03-16 21:48:014883 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254884 if (entry_index == -1) {
4885 // TODO(rakina): Exit early when there is no last committed entry.
4886 // Remove when InitialNavigationEntry ships.
4887 return entry_arrays;
4888 }
4889
Nate Chapina2c881f52023-11-07 17:02:094890 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014891 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574892 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094893 pending_item_sequence_number, pending_document_sequence_number,
4894 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574895
4896 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094897 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574898 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014899 entry_arrays->forward_entries =
4900 PopulateSingleNavigationApiHistoryEntryVector(
4901 Direction::kForward, entry_index, pending_origin, node,
4902 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094903 pending_document_sequence_number, forwardmost_index);
4904 }
4905
4906 // If the previous entry is within the block of contiguous entries being
4907 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254908 FrameNavigationEntry* previous_entry = nullptr;
4909 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:054910 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4911 .initiator_frame_tree_node_id();
4912 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:254913 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4914 previous_entry = initiator_node->frame_tree()
4915 .controller()
4916 .GetLastCommittedEntry()
4917 ->GetFrameEntry(initiator_node);
4918 }
4919 } else if (GetLastCommittedEntryIndex() != -1 &&
4920 GetLastCommittedEntryIndex() >= backmost_index &&
4921 GetLastCommittedEntryIndex() <= forwardmost_index) {
4922 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4923 }
4924 if (previous_entry) {
4925 url::Origin previous_entry_origin =
4926 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4927 previous_entry->url(),
4928 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:584929 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:254930 // once we can be sure that entries with the same ISN will never be
4931 // cross-origin.
4932 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4933 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4934 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094935 }
Nate Chapind1fe3612021-04-16 20:45:574936 }
Nate Chapinc06cf80a2023-11-18 01:12:254937
Nate Chapin4e657a472022-02-06 03:38:374938 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574939}
4940
Nate Chapinfbfe5af2021-06-10 17:22:084941NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574942NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084943 FrameNavigationEntry* current_entry,
4944 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574945 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084946 if (!target_entry || !target_entry->committed_origin())
4947 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084948 if (!current_entry->committed_origin()->IsSameOriginWith(
4949 *target_entry->committed_origin())) {
4950 return HistoryNavigationAction::kStopLooking;
4951 }
4952
4953 // NOTE: We don't actually care between kSameDocument and
4954 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574955 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084956 return HistoryNavigationAction::kDifferentDocument;
4957 return HistoryNavigationAction::kKeepLooking;
4958}
4959
Domenic Denicolacc094fb2022-03-16 23:40:574960void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204961 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374962 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144963 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574964 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204965 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084966 FrameNavigationEntry* current_entry =
4967 GetLastCommittedEntry()->GetFrameEntry(node);
Nate Chapin0dbc93af2025-03-28 17:02:524968 if (!current_entry || !current_entry->committed_origin()) {
Nate Chapinfbfe5af2021-06-10 17:22:084969 return;
Nate Chapin0dbc93af2025-03-28 17:02:524970 }
Nate Chapinfbfe5af2021-06-10 17:22:084971
Alison Gale47d1537d2024-04-19 21:31:464972 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:134973 // when `navigation.traverseTo()` is called.
4974
Nate Chapinfbfe5af2021-06-10 17:22:084975 // We want to find the nearest matching entry that is contiguously
4976 // same-instance and same-origin. Check back first, then forward.
4977 // TODO(japhet): Link spec here once it exists.
4978 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574979 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084980 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4981 if (result == HistoryNavigationAction::kStopLooking)
4982 break;
4983 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144984 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084985 return;
4986 }
4987 }
4988 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574989 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084990 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4991 if (result == HistoryNavigationAction::kStopLooking)
4992 break;
4993 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144994 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084995 return;
4996 }
4997 }
Nate Chapinbf682fa32022-09-26 22:41:204998
4999 // If we fall through to here, a matching NavigationEntry couldn't be found.
5000 // Notify the renderer that the navigation was cancelled.
5001 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
5002 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:085003}
5004
Domenic Denicolacc094fb2022-03-16 23:40:575005bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:305006 network::mojom::ReferrerPolicy referrer_policy) {
5007 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
5008 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
5009}
5010
shivanigithubf405bf0d2021-11-05 17:58:335011bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
5012 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:315013 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:335014 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:545015 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:465016 // The preview mode appears as prerendered page in renderers, and
5017 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:035018 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:515019 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:335020 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:545021}
5022
Julie Jeongeun Kim0e242242022-11-30 10:45:095023void NavigationControllerImpl::DidChangeReferrerPolicy(
5024 FrameTreeNode* node,
5025 network::mojom::ReferrerPolicy referrer_policy) {
5026 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
5027 if (!entry)
5028 return;
5029
5030 // The FrameNavigationEntry may want to change whether to protect its url
5031 // in the navigation API when the referrer policy changes.
5032 entry->set_protect_url_in_navigation_api(
5033 ShouldProtectUrlInNavigationApi(referrer_policy));
5034}
5035
Minoru Chikamune646eba42025-04-14 01:25:035036void NavigationControllerImpl::CheckPotentialNavigationReentrancy() {
5037 // DumpWithoutCrashing will be reported just once in one Chrome session since
5038 // we want to avoid too many reports.
5039 static bool has_dumped_without_crashing = false;
5040 if (can_be_in_navigate_to_pending_entry_ && !has_dumped_without_crashing) {
5041 has_dumped_without_crashing = true;
5042 // This DumpWithoutCrashing is an investigation code for
5043 // https://crbug.com/396998476.
5044 base::debug::DumpWithoutCrashing();
5045 }
5046}
5047
[email protected]8ff00d72012-10-23 19:12:215048} // namespace content