blob: 12c7b7535bba88d4edbfcae2746938bb820c82f3 [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"
danakjc492bf82020-09-09 20:02:4475#include "content/browser/renderer_host/navigator.h"
Takashi Toyoshima4dad2c12023-11-13 10:04:4676#include "content/browser/renderer_host/page_delegate.h"
danakjc492bf82020-09-09 20:02:4477#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0078#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0779#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3280#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3381#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4282#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5783#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5184#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1185#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1986#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1187#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4688#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0089#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4790#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5891#include "content/public/browser/render_widget_host.h"
92#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1093#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3494#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1995#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3896#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1097#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4798#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:4399#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59100#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36101#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57102#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18103#include "services/metrics/public/cpp/ukm_builders.h"
104#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17105#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37106#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44107#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58108#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39109#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30110#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21111#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06112#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43113#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50114#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31115#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51116#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46117#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26118#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29119
[email protected]8ff00d72012-10-23 19:12:21120namespace content {
[email protected]e9ba4472008-09-14 15:42:43121namespace {
122
123// Invoked when entries have been pruned, or removed. For example, if the
124// current entries are [google, digg, yahoo], with the current entry google,
125// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47126void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50127 int index,
[email protected]c12bf1a12008-09-17 16:28:49128 int count) {
[email protected]8ff00d72012-10-23 19:12:21129 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50130 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49131 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14132 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43133}
134
[email protected]e9ba4472008-09-14 15:42:43135// Configure all the NavigationEntries in entries for restore. This resets
136// the transition type to reload and makes sure the content state isn't empty.
137void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57138 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48139 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47140 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43141 // Use a transition type of reload so that we don't incorrectly increase
142 // the typed count.
Lei Zhang96031532019-10-10 19:05:47143 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
144 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43145 }
146}
147
[email protected]bf70edce2012-06-20 22:32:22148// Determines whether or not we should be carrying over a user agent override
149// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57150bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22151 return last_entry && last_entry->GetIsOverridingUserAgent();
152}
153
Camille Lamy5193caa2018-10-12 11:59:42154// Determines whether to override user agent for a navigation.
155bool ShouldOverrideUserAgent(
156 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57157 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42158 switch (override_user_agent) {
159 case NavigationController::UA_OVERRIDE_INHERIT:
160 return ShouldKeepOverride(last_committed_entry);
161 case NavigationController::UA_OVERRIDE_TRUE:
162 return true;
163 case NavigationController::UA_OVERRIDE_FALSE:
164 return false;
Camille Lamy5193caa2018-10-12 11:59:42165 }
Peter Boström8472105d2024-05-15 04:36:02166 NOTREACHED_IN_MIGRATION();
Camille Lamy5193caa2018-10-12 11:59:42167 return false;
168}
169
Rakina Zata Amni312822d72021-06-04 16:13:37170// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28171// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37172// link which results in a navigation to the last committed URL (but wasn't
173// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04174// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
175// |base_url_for_data_url|, |transition_type| correspond to the new navigation
176// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
177// navigation that committed.
178bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
179 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57180 const GURL& virtual_url,
181 const GURL& base_url_for_data_url,
182 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57183 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37184 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57185 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37186 // Navigations intended to do a replacement shouldn't be converted to do a
187 // reload.
188 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28189 return false;
clamy0a656e42018-02-06 18:18:28190 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45191 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55192 return false;
193
arthursonzogni7a8243682017-12-14 16:41:42194 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28195 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42196 return false;
197
ananta3bdd8ae2016-12-22 17:11:55198 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
199 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
200 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28201 bool transition_type_can_be_converted = false;
202 if (ui::PageTransitionCoreTypeIs(transition_type,
203 ui::PAGE_TRANSITION_RELOAD) &&
204 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
205 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55206 }
clamy0a656e42018-02-06 18:18:28207 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55208 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28209 transition_type_can_be_converted = true;
210 }
211 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
212 transition_type_can_be_converted = true;
213 if (!transition_type_can_be_converted)
214 return false;
215
216 // This check is required for cases like view-source:, etc. Here the URL of
217 // the navigation entry would contain the url of the page, while the virtual
218 // URL contains the full URL including the view-source prefix.
219 if (virtual_url != last_committed_entry->GetVirtualURL())
220 return false;
221
Fergal Daly766177d2020-07-07 07:54:04222 // Check that the URLs match.
223 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
224 // If there's no frame entry then by definition the URLs don't match.
225 if (!frame_entry)
226 return false;
227
228 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28229 return false;
230
231 // This check is required for Android WebView loadDataWithBaseURL. Apps
232 // can pass in anything in the base URL and we need to ensure that these
233 // match before classifying it as a reload.
234 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
235 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
236 return false;
ananta3bdd8ae2016-12-22 17:11:55237 }
238
clamy0a656e42018-02-06 18:18:28239 // Skip entries with SSL errors.
240 if (last_committed_entry->ssl_error())
241 return false;
242
243 // Don't convert to a reload when the last navigation was a POST or the new
244 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04245 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28246 return false;
247
248 return true;
ananta3bdd8ae2016-12-22 17:11:55249}
250
Arthur Sonzognic686e8f2024-01-11 08:36:37251std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12252 const mojom::DidCommitProvisionalLoadParams& params,
253 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32254 // Error pages commit in an opaque origin, yet have the real URL that resulted
255 // in an error as the |params.url|. Since successful reload of an error page
256 // should commit in the correct origin, setting the opaque origin on the
257 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17258 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37259 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32260
Arthur Sonzognic686e8f2024-01-11 08:36:37261 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32262}
263
Alex Moshchuk99242832023-05-22 17:21:44264bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42265 const GURL& virtual_url,
266 const GURL& dest_url) {
267 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44268 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
269 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42270 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
271 << virtual_url.possibly_invalid_spec();
272 return false;
273 }
274
275 // Don't attempt to navigate to non-empty invalid URLs.
276 if (!dest_url.is_valid() && !dest_url.is_empty()) {
277 LOG(WARNING) << "Refusing to load invalid URL: "
278 << dest_url.possibly_invalid_spec();
279 return false;
280 }
281
282 // The renderer will reject IPC messages with URLs longer than
283 // this limit, so don't attempt to navigate with a longer URL.
284 if (dest_url.spec().size() > url::kMaxURLChars) {
285 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
286 << " characters.";
287 return false;
288 }
289
Aaron Colwell33109c592020-04-21 21:31:19290 // Reject renderer debug URLs because they should have been handled before
291 // we get to this point. This check handles renderer debug URLs
292 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
293 // provides defense-in-depth if a renderer debug URL manages to get here via
294 // some other path. We want to reject the navigation here so it doesn't
295 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30296 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19297 LOG(WARNING) << "Refusing to load renderer debug URL: "
298 << dest_url.possibly_invalid_spec();
299 return false;
300 }
301
Alex Moshchuk99242832023-05-22 17:21:44302 // Guests only support navigations to known-safe schemes. This check already
303 // exists in the extensions layer, where it also dispatches proper events to
304 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
305 // for defense-in-depth to ensure that no other places in the codebase
306 // accidentally navigate guests to schemes such as WebUI, which is not
307 // supported. See https://crbug.com/1444221.
308 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
309 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
310 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
311 !dest_url.SchemeIs(url::kAboutScheme)) {
312 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
313 << dest_url.possibly_invalid_spec();
314 return false;
315 }
316 }
317
Camille Lamy5193caa2018-10-12 11:59:42318 return true;
319}
320
Mikel Astizba9cf2fd2017-12-17 10:38:10321// See replaced_navigation_entry_data.h for details: this information is meant
322// to ensure |*output_entry| keeps track of its original URL (landing page in
323// case of server redirects) as it gets replaced (e.g. history.replaceState()),
324// without overwriting it later, for main frames.
325void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57326 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10327 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17328 if (output_entry->GetReplacedEntryData().has_value() ||
329 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10330 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17331 }
Mikel Astizba9cf2fd2017-12-17 10:38:10332
333 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57334 data.first_committed_url = replaced_entry->GetURL();
335 data.first_timestamp = replaced_entry->GetTimestamp();
336 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29337 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10338}
339
Minggang Wangb9f3fa92021-07-01 15:30:31340blink::mojom::NavigationType GetNavigationType(
341 const GURL& old_url,
342 const GURL& new_url,
343 ReloadType reload_type,
344 NavigationEntryImpl* entry,
345 const FrameNavigationEntry& frame_entry,
346 bool has_pending_cross_document_commit,
347 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49348 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13349 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49350 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23351 // Reload navigations
352 switch (reload_type) {
353 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31354 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23355 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31356 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23357 case ReloadType::NONE:
358 break; // Fall through to rest of function.
359 }
360
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08361 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31362 return entry->GetHasPostData()
363 ? blink::mojom::NavigationType::RESTORE_WITH_POST
364 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23365 }
366
danakjb952ef12021-01-14 19:58:49367 const bool can_be_same_document =
368 // A pending cross-document commit means this navigation will not occur in
369 // the current document, as that document would end up being replaced in
370 // the meantime.
371 !has_pending_cross_document_commit &&
372 // If the current document is an error page, we should always treat it as
373 // a different-document navigation so that we'll attempt to load the
374 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49375 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13376 // If the navigation is an embedder-initiated navigation of a fenced
377 // frame root (i.e. enters a fenced frame tree from outside),
378 // same-document navigations should be disabled because we don't want to
379 // allow information to be joined across multiple embedder-initiated
380 // fenced frame navigations (which may contain separate cross-site data).
381 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49382 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
383 // same-document navigations should be disabled because we want to force
384 // the creation of a new browsing context group.
385 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12386
clamyea99ea12018-05-28 13:54:23387 // History navigations.
388 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12389 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31390 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
391 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23392 }
393 DCHECK(!is_same_document_history_load);
394
395 // A same-document fragment-navigation happens when the only part of the url
396 // that is modified is after the '#' character.
397 //
398 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12399 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23400 //
401 // Note: this check is only valid for navigations that are not history
402 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
403 // history navigation from 'A#foo' to 'A#bar' is not a same-document
404 // navigation, but a different-document one. This is why history navigation
405 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47406 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
407 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12408
409 // The one case where we do the wrong thing here and incorrectly choose
410 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
411 // the renderer is a frameset. All frameset navigations should be
412 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
413 // navigation would do the right thing, as it would send it to the browser and
414 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
415 // into this method). But since we can't tell that case here for browser-
416 // initiated navigations, we have to get the renderer involved. In that case
417 // the navigation would be restarted due to the renderer spending a reply of
418 // mojom::CommitResult::RestartCrossDocument.
419
420 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31421 ? blink::mojom::NavigationType::SAME_DOCUMENT
422 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23423}
424
Camille Lamy5193caa2018-10-12 11:59:42425// Adjusts the original input URL if needed, to get the URL to actually load and
426// the virtual URL, which may differ.
427void RewriteUrlForNavigation(const GURL& original_url,
428 BrowserContext* browser_context,
429 GURL* url_to_load,
430 GURL* virtual_url,
431 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42432 // Allow the browser URL handler to rewrite the URL. This will, for example,
433 // remove "view-source:" from the beginning of the URL to get the URL that
434 // will actually be loaded. This real URL won't be shown to the user, just
435 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31436 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42437 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
438 url_to_load, browser_context, reverse_on_redirect);
439}
440
441#if DCHECK_IS_ON()
442// Helper sanity check function used in debug mode.
443void ValidateRequestMatchesEntry(NavigationRequest* request,
444 NavigationEntryImpl* entry) {
445 if (request->frame_tree_node()->IsMainFrame()) {
446 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
447 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31448 ui::PageTransitionFromInt(request->common_params().transition),
449 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42450 }
Nasko Oskovc36327d2019-01-03 23:23:04451 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42452 entry->should_clear_history_list());
453 DCHECK_EQ(request->common_params().has_user_gesture,
454 entry->has_user_gesture());
455 DCHECK_EQ(request->common_params().base_url_for_data_url,
456 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04457 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42458 entry->GetCanLoadLocalResources());
459 DCHECK_EQ(request->common_params().started_from_context_menu,
460 entry->has_started_from_context_menu());
461
462 FrameNavigationEntry* frame_entry =
463 entry->GetFrameEntry(request->frame_tree_node());
464 if (!frame_entry) {
Peter Boström8472105d2024-05-15 04:36:02465 NOTREACHED_IN_MIGRATION();
Camille Lamy5193caa2018-10-12 11:59:42466 return;
467 }
468
Camille Lamy5193caa2018-10-12 11:59:42469 DCHECK_EQ(request->common_params().method, frame_entry->method());
470
Nasko Oskovc36327d2019-01-03 23:23:04471 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42472 if (redirect_size == frame_entry->redirect_chain().size()) {
473 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04474 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42475 frame_entry->redirect_chain()[i]);
476 }
477 } else {
Peter Boström8472105d2024-05-15 04:36:02478 NOTREACHED_IN_MIGRATION();
Camille Lamy5193caa2018-10-12 11:59:42479 }
480}
481#endif // DCHECK_IS_ON()
482
Dave Tapuska8bfd84c2019-03-26 20:47:16483// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20484// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16485bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20486 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16487 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20488 DCHECK(sandboxed_initiator_rfh);
489 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
490 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16491 for (auto& item : navigations) {
492 bool within_subtree = false;
493 // Check whether this NavigationRequest affects a frame within the
494 // sandboxed frame's subtree by walking up the tree looking for the
495 // sandboxed frame.
496 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03497 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20498 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16499 within_subtree = true;
500 break;
501 }
502 }
503 if (!within_subtree)
504 return false;
505 }
506 return true;
507}
508
William Liu122754942024-01-18 22:34:39509// Used for "Navigation.SessionHistoryCount" histogram.
510enum class HistoryNavTypeForHistogram {
511 // A same-doc or cross-doc navigation of the main frame. We can only have one
512 // main frame request per `NavigationController::GoToIndex()`.
513 kMainFrame = 0,
514 // `NavigationController::GoToIndex()` creates one main frame request and
515 // one or more subframe requests.
516 kMainFrameAndSubframe,
517 // `NavigationController::GoToIndex()` creates one or more subframe requests.
518 kSubframe,
519 // Used for histogram boundary.
520 kCount
521};
522
523void CountRequests(
524 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
525 int& mutable_main_frame_cnt,
526 int& mutable_subframe_cnt) {
527 for (const auto& req : requests) {
528 if (req->IsInPrimaryMainFrame()) {
529 // We can only have one main frame navigation at a time.
530 CHECK_EQ(mutable_main_frame_cnt, 0);
531 ++mutable_main_frame_cnt;
532 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
533 ++mutable_subframe_cnt;
534 }
535 }
536}
537
538// Record the number of different types of navigations as histograms. See
539// `HistoryNavTypeForHistogram` for the types.
540void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
541 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
542 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
543 // We must have one request.
544 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
545
546 int main_frame_cnt = 0;
547 int subframe_cnt = 0;
548 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
549 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
550
551 std::optional<HistoryNavTypeForHistogram> history_nav_type;
552 if (main_frame_cnt > 0) {
553 if (subframe_cnt == 0) {
554 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
555 } else {
556 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
557 }
558 } else if (subframe_cnt > 0) {
559 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
560 }
561 if (history_nav_type.has_value()) {
562 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
563 history_nav_type.value(),
564 HistoryNavTypeForHistogram::kCount);
565 }
566}
567
[email protected]e9ba4472008-09-14 15:42:43568} // namespace
569
arthursonzogni66f711c2019-10-08 14:40:36570// NavigationControllerImpl::PendingEntryRef------------------------------------
571
572NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
573 base::WeakPtr<NavigationControllerImpl> controller)
574 : controller_(controller) {}
575
576NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
577 if (!controller_) // Can be null with interstitials.
578 return;
579
580 controller_->PendingEntryRefDeleted(this);
581}
582
[email protected]d202a7c2012-01-04 07:53:47583// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29584
[email protected]23a918b2014-07-15 09:51:36585const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23586
[email protected]765b35502008-08-21 00:51:20587// static
[email protected]d202a7c2012-01-04 07:53:47588size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23589 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20590
[email protected]e6fec472013-05-14 05:29:02591// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20592// when testing.
593static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29594
[email protected]71fde352011-12-29 03:29:56595// static
dcheng9bfa5162016-04-09 01:00:57596std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
597 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10598 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37599 std::optional<url::Origin> initiator_origin,
600 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10601 ui::PageTransition transition,
602 bool is_renderer_initiated,
603 const std::string& extra_headers,
604 BrowserContext* browser_context,
605 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
606 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21607 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37608 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32609 is_renderer_initiated, extra_headers, browser_context,
610 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10611}
612
613// static
614std::unique_ptr<NavigationEntryImpl>
615NavigationControllerImpl::CreateNavigationEntry(
616 const GURL& url,
617 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37618 std::optional<url::Origin> initiator_origin,
619 std::optional<GURL> initiator_base_url,
620 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57621 ui::PageTransition transition,
622 bool is_renderer_initiated,
623 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09624 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17625 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
626 bool rewrite_virtual_urls) {
627 GURL url_to_load = url;
628 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56629 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17630 if (rewrite_virtual_urls) {
631 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
632 &reverse_on_redirect);
633 }
Lukasz Anforowicz641234d52019-11-07 21:07:10634 // Let the NTP override the navigation params and pretend that this is a
635 // browser-initiated, bookmark-like navigation.
636 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32637 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21638 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10639
Patrick Monettef507e982019-06-19 20:18:06640 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28641 nullptr, // The site instance for tabs is sent on navigation
642 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21643 url_to_load, referrer, initiator_origin, initiator_base_url,
644 std::u16string(), transition, is_renderer_initiated,
645 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17646 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42647 entry->SetVirtualURL(virtual_url);
648 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56649 entry->set_update_virtual_url_with_url(reverse_on_redirect);
650 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06651 return entry;
[email protected]71fde352011-12-29 03:29:56652}
653
[email protected]cdcb1dee2012-01-04 00:46:20654// static
655void NavigationController::DisablePromptOnRepost() {
656 g_check_for_repost = false;
657}
658
[email protected]c5b88d82012-10-06 17:03:33659base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
660 base::Time t) {
661 // If |t| is between the water marks, we're in a run of duplicates
662 // or just getting out of it, so increase the high-water mark to get
663 // a time that probably hasn't been used before and return it.
664 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35665 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33666 return high_water_mark_;
667 }
668
669 // Otherwise, we're clear of the last duplicate run, so reset the
670 // water marks.
671 low_water_mark_ = high_water_mark_ = t;
672 return t;
673}
674
ckitagawa0faa5e42020-06-17 17:30:54675NavigationControllerImpl::ScopedShowRepostDialogForTesting::
676 ScopedShowRepostDialogForTesting()
677 : was_disallowed_(g_check_for_repost) {
678 g_check_for_repost = true;
679}
680
681NavigationControllerImpl::ScopedShowRepostDialogForTesting::
682 ~ScopedShowRepostDialogForTesting() {
683 g_check_for_repost = was_disallowed_;
684}
685
Nate Chapin9eb16be72022-09-23 22:54:31686NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
687 base::SafeRef<NavigationControllerImpl> controller)
688 : controller_(controller) {
689 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
690 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
691 frame_tree_node_id_to_keys_.insert(
692 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
693 if (auto* frame_entry = frame_tree_node->current_frame_host()
694 ->last_committed_frame_entry()) {
695 frame_tree_node_id_to_doc_seq_nos_.insert(
696 {frame_tree_node->frame_tree_node_id(),
697 frame_entry->document_sequence_number()});
698 }
699 }
700 PopulateKeySet(Direction::kBack);
701 PopulateKeySet(Direction::kForward);
702}
703
704void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
705 Direction direction) {
706 // Keep track of which FrameTreeNodes may still have relevant API keys in
707 // additional FrameNavigationEntries.
708 std::set<FrameTreeNode*> nodes_to_process;
709 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
710 nodes_to_process.insert(node);
711 }
712
713 const int offset = direction == Direction::kForward ? 1 : -1;
714 const int start = direction == Direction::kForward
715 ? controller_->GetLastCommittedEntryIndex()
716 : controller_->GetLastCommittedEntryIndex() - 1;
717 for (int i = start;
718 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
719 i += offset) {
720 std::set<FrameTreeNode*> nodes_to_continue_processing;
721
722 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
723 entry->ForEachFrameEntry([this, &nodes_to_process,
724 &nodes_to_continue_processing,
725 &entry](FrameNavigationEntry* frame_entry) {
726 // Find the |node| that matches |frame_entry|, if any.
727 FrameTreeNode* node = nullptr;
728 if (frame_entry == entry->root_node()->frame_entry) {
729 node = controller_->frame_tree().root();
730 } else {
731 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
732 if (it == names_to_nodes_.end())
733 return;
734 node = it->second;
735 }
736
737 // Skip this node if a previous step determine there are no longer
738 // relevant navigation API keys in this direction.
739 if (nodes_to_process.find(node) == nodes_to_process.end())
740 return;
741
742 // Stop processing |node| if we reach a point where it's cross-origin.
743 // See also PopulateSingleNavigationApiHistoryEntryVector().
744 url::Origin frame_entry_origin =
745 frame_entry->committed_origin().value_or(url::Origin::Resolve(
746 frame_entry->url(),
747 frame_entry->initiator_origin().value_or(url::Origin())));
748 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
749 return;
750
751 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
752 frame_entry->navigation_api_key());
753 // Mark |node| as needing more processing for the next entry.
754 nodes_to_continue_processing.insert(node);
755
756 // Check whether |node| went cross-document. If so, its children are
757 // no longer the same conceptual iframe as the current one, and
758 // should no longer be processed. This check is intentionally done
759 // after processing the current |node|, which may still have relevant
760 // discarded API keys.
761 if (frame_entry->document_sequence_number() !=
762 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50763 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31764 nodes_to_process.erase(descendant);
765 }
766 });
767
768 nodes_to_process.swap(nodes_to_continue_processing);
769 }
770}
771
772NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
773 std::set<std::string> all_keys;
774 // Find all remaining navigation API keys after some entries have been
775 // removed.
776 for (auto& entry : controller_->entries_) {
777 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
778 all_keys.insert(frame_entry->navigation_api_key());
779 });
780 }
781
782 // Notify each frame in the renderer of any disposed navigation API keys.
783 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
784 std::vector<std::string> disposed_keys;
785 for (const auto& key : id_to_keys.second) {
786 if (all_keys.find(key) == all_keys.end())
787 disposed_keys.push_back(key);
788 }
789 if (disposed_keys.empty())
790 continue;
791
792 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
793 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
794 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
795 }
796}
797
[email protected]d202a7c2012-01-04 07:53:47798NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00799 BrowserContext* browser_context,
800 FrameTree& frame_tree,
801 NavigationControllerDelegate* delegate)
802 : frame_tree_(frame_tree),
803 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57804 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22805 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37806 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
807 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37808 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29809}
810
[email protected]d202a7c2012-01-04 07:53:47811NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00812 // The NavigationControllerImpl might be called inside its delegate
813 // destructor. Calling it is not valid anymore.
814 delegate_ = nullptr;
815 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29816}
817
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57818BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55819 return browser_context_;
820}
821
[email protected]d202a7c2012-01-04 07:53:47822void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30823 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36824 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57825 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47826 // Note that it's possible for `entries_` to contain multiple entries at this
827 // point, as Restore() might be called on a NavigationController that is
828 // already used (e.g. due to WebView's restoreState() API), not only for fresh
829 // NavigationControllers. These entries are not cleared to preserve legacy
830 // behavior and also because `pending_entry_` might point to one of the
831 // pre-existing entries. An exception for this is when `entries_` contains
832 // only the initial NavigationEntry, which must be removed.
833
834 // Do not proceed if selected_navigation will be out of bounds for the updated
835 // entries_ list, since it will be assigned to last_committed_entry_index_ and
836 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58837 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47838 // is empty, since there should be no work to do (rather than marking the
839 // existing entries as needing reload). Also consider returning early if the
840 // selected index is -1, which represents a no-committed-entry state.
841 if (selected_navigation < -1 ||
842 selected_navigation >=
843 base::checked_cast<int>(entries->size() + entries_.size())) {
844 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24845 }
Charlie Reis23c26da2022-01-29 00:57:47846
Rakina Zata Amni46087a12022-11-11 08:28:38847 // There will always be at least one entry (new NavigationControllers will
848 // have the initial NavigationEntry).
849 if (selected_navigation == -1)
850 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47851
Rakina Zata Amni46087a12022-11-11 08:28:38852 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
853 // If we are on the initial NavigationEntry, it must be the only entry in
854 // the list. Since it's impossible to do a history navigation to the
855 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
856 // `pending_entry` might be set for a new non-history navigation).
857 // Note that we should not clear `entries_` if `entries` is empty (when
858 // InitialNavigationEntry mode is enabled), since that would leave us
859 // without any NavigationEntry.
860 CHECK_EQ(1, GetEntryCount());
861 CHECK_EQ(-1, pending_entry_index_);
862 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47863 }
[email protected]ce3fa3c2009-04-20 19:55:57864
[email protected]ce3fa3c2009-04-20 19:55:57865 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44866 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03867 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47868 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43869 if (entry->GetURL().is_empty()) {
870 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01871 // persisting the initial NavigationEntry [which is no longer possible but
872 // some old persisted sessions might still contain it] or when the
873 // serializer failed to write the URL because it's too long). Trying to
874 // restore and navigate to an entry with an empty URL will result in
875 // crashes, so change the URL to about:blank. See also
876 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43877 entry->SetURL(GURL(url::kAboutBlankURL));
878 }
dcheng36b6aec92015-12-26 06:16:36879 entries_.push_back(
880 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47881 }
avif16f85a72015-11-13 18:25:03882
883 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
884 // cleared out safely.
885 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57886
887 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36888 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57889}
890
toyoshim6142d96f2016-12-19 09:07:25891void NavigationControllerImpl::Reload(ReloadType reload_type,
892 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03893 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
894 (int)reload_type);
895 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
896 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28897 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28898 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32899 int current_index = -1;
900
Carlos IL42b416592019-10-07 23:10:36901 if (entry_replaced_by_post_commit_error_) {
902 // If there is an entry that was replaced by a currently active post-commit
903 // error navigation, this can't be the initial navigation.
904 DCHECK(!IsInitialNavigation());
905 // If the current entry is a post commit error, we reload the entry it
906 // replaced instead. We leave the error entry in place until a commit
907 // replaces it, but the pending entry points to the original entry in the
908 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
909 // case that pending_entry_ != entries_[pending_entry_index_].
910 entry = entry_replaced_by_post_commit_error_.get();
911 current_index = GetCurrentEntryIndex();
912 } else if (IsInitialNavigation() && pending_entry_) {
913 // If we are reloading the initial navigation, just use the current
914 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32915 entry = pending_entry_;
916 // The pending entry might be in entries_ (e.g., after a Clone), so we
917 // should also update the current_index.
918 current_index = pending_entry_index_;
919 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00920 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32921 current_index = GetCurrentEntryIndex();
922 if (current_index != -1) {
creis3da03872015-02-20 21:12:32923 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32924 }
[email protected]979a4bc2013-04-24 01:27:15925 }
[email protected]241db352013-04-22 18:04:05926
[email protected]59167c22013-06-03 18:07:32927 // If we are no where, then we can't reload. TODO(darin): We should add a
928 // CanReload method.
929 if (!entry)
930 return;
931
Rakina Zata Amnif297a802022-01-18 03:53:43932 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
933 // We should never navigate to an existing initial NavigationEntry that is
934 // the initial NavigationEntry for the initial empty document that hasn't
935 // been overridden by the synchronous about:blank commit, to preserve
936 // legacy behavior where trying to reload when the main frame is on the
937 // initial empty document won't result in a navigation. See also
938 // https://crbug.com/1277414.
939 return;
940 }
941
Aran Gilman37d11632019-10-08 23:07:15942 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30943 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07944 // they really want to do this. If they do, the dialog will call us back
945 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57946 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02947
[email protected]106a0812010-03-18 00:15:12948 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57949 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47950 return;
initial.commit09911bf2008-07-26 23:55:29951 }
Lei Zhang96031532019-10-10 19:05:47952
Wang Huia25efabc2022-09-24 17:27:22953 // Set ReloadType for |entry|.
954 entry->set_reload_type(reload_type);
955
Lei Zhang96031532019-10-10 19:05:47956 if (!IsInitialNavigation())
957 DiscardNonCommittedEntries();
958
959 pending_entry_ = entry;
960 pending_entry_index_ = current_index;
961 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
962
Nate Chapin45f620582021-09-30 17:45:43963 // location.reload() goes through BeginNavigation, so all reloads triggered
964 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13965 NavigateToExistingPendingEntry(
966 reload_type,
967 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:37968 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:13969 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29970}
971
[email protected]d202a7c2012-01-04 07:53:47972void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48973 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12974}
975
[email protected]d202a7c2012-01-04 07:53:47976void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49977 // If the pending reload type has been cleared by another navigation
978 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48979 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49980 return;
[email protected]106a0812010-03-18 00:15:12981 }
Wang Hui96ab1012022-10-11 02:05:49982 Reload(pending_reload_, false);
983 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12984}
985
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57986bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09987 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11988}
989
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57990bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38991 // Check that we're on the initial NavigationEntry and that this is not a
992 // cloned tab.
993 return IsInitialNavigation() && GetEntryCount() == 1 &&
994 GetLastCommittedEntry()->IsInitialEntry() &&
995 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40996}
997
Aran Gilman37d11632019-10-08 23:07:15998NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
999 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581000 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031001 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581002}
1003
Adithya Srinivasan9b0c99c2021-08-10 15:19:451004NavigationEntryImpl*
1005NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1006 int nav_entry_id) const {
1007 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1008 if (entry)
1009 return entry;
1010 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521011 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451012 : nullptr;
1013}
1014
W. James MacLeanc07dc41b2022-07-25 18:52:161015void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571016 const url::Origin& origin) {
1017 for (int i = 0; i < GetEntryCount(); i++) {
1018 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161019 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571020 }
1021 if (entry_replaced_by_post_commit_error_) {
1022 // It's possible we could come back to this entry if the error
1023 // page/interstitial goes away.
1024 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161025 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571026 }
W. James MacLean1c40862c2020-04-27 21:05:571027}
1028
avi25764702015-06-23 15:43:371029void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571030 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001031 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371032 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271033 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201034}
1035
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571036NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471037 if (pending_entry_)
1038 return pending_entry_;
1039 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201040}
1041
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571042NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321043 // The pending entry is safe to return for new (non-history), browser-
1044 // initiated navigations. Most renderer-initiated navigations should not
1045 // show the pending entry, to prevent URL spoof attacks.
1046 //
1047 // We make an exception for renderer-initiated navigations in new tabs, as
1048 // long as no other page has tried to access the initial empty document in
1049 // the new tab. If another page modifies this blank page, a URL spoof is
1050 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321051 bool safe_to_show_pending =
1052 pending_entry_ &&
1053 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091054 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321055 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461056 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321057
1058 // Also allow showing the pending entry for history navigations in a new tab,
1059 // such as Ctrl+Back. In this case, no existing page is visible and no one
1060 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151061 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1062 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321063 safe_to_show_pending = true;
1064
1065 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191066 return pending_entry_;
1067 return GetLastCommittedEntry();
1068}
1069
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571070int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201071 if (pending_entry_index_ != -1)
1072 return pending_entry_index_;
1073 return last_committed_entry_index_;
1074}
1075
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571076NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381077 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031078 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201079}
1080
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571081bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351082 const std::string& mime_type = frame_tree_->root()
1083 ->current_frame_host()
1084 ->GetPage()
1085 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531086 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1087 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271088 NavigationEntry* visible_entry = GetVisibleEntry();
1089 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391090 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161091}
1092
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571093int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271094 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451095 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271096 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551097 return last_committed_entry_index_;
1098}
1099
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571100int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451101 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291102 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551103 return static_cast<int>(entries_.size());
1104}
1105
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571106NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371107 if (index < 0 || index >= GetEntryCount())
1108 return nullptr;
1109
avif16f85a72015-11-13 18:25:031110 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251111}
1112
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571113NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471114 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201115}
1116
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571117int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461118 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031119}
1120
Arthur Sonzognic686e8f2024-01-11 08:36:371121std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031122 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591123 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1124 return index;
1125 }
Shivani Sharma298d12852019-01-22 20:04:031126 }
Arthur Sonzognic686e8f2024-01-11 08:36:371127 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591128}
1129
1130bool NavigationControllerImpl::CanGoBack() {
1131 return GetIndexForGoBack().has_value();
1132}
1133
Arthur Sonzognic686e8f2024-01-11 08:36:371134std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591135 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1136 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1137 return index;
1138 }
1139 }
Arthur Sonzognic686e8f2024-01-11 08:36:371140 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201141}
1142
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571143bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591144 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201145}
1146
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571147bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031148 int index = GetIndexForOffset(offset);
1149 return index >= 0 && index < GetEntryCount();
1150}
1151
Xiaohan Wang7f8052e02022-01-14 18:44:281152#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151153bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151154 if (offset == 0)
1155 return true;
1156 int increment = offset > 0 ? 1 : -1;
1157 int non_skippable_entries = 0;
1158 for (int index = GetIndexForOffset(increment);
1159 index >= 0 && index < GetEntryCount(); index += increment) {
1160 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1161 non_skippable_entries++;
1162
1163 if (non_skippable_entries == std::abs(offset))
1164 return true;
1165 }
1166 return false;
1167}
1168#endif
1169
[email protected]d202a7c2012-01-04 07:53:471170void NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371171 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061172
Kevin McNeeedc481c2023-04-27 22:30:581173 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211174
Kevin McNee3b3a56192023-03-17 14:40:591175 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201176}
1177
[email protected]d202a7c2012-01-04 07:53:471178void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161179 // Note that at least one entry (the last one) will be non-skippable since
1180 // entries are marked skippable only when they add another entry because of
1181 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371182 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591183
Kevin McNeeedc481c2023-04-27 22:30:581184 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591185
1186 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201187}
1188
[email protected]d202a7c2012-01-04 07:53:471189void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131190 GoToIndex(index, /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371191 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:131192 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161193}
1194
William Liuec04e382024-05-23 18:03:271195base::WeakPtr<NavigationRequest> NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201196 int index,
1197 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371198 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131199 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201200 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441201 TRACE_EVENT0("browser,navigation,benchmark",
1202 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501203 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1204 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1205 entries_.size());
1206 // Indices should have have been validated by the caller.
1207 CHECK_GE(index, 0);
1208 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201209
Rakina Zata Amnif297a802022-01-18 03:53:431210 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1211 // We should never navigate to an existing initial NavigationEntry that is
1212 // the initial NavigationEntry for the initial empty document that hasn't
1213 // been overridden by the synchronous about:blank commit, to preserve
1214 // legacy behavior where trying to reload when the main frame is on the
1215 // initial empty document won't result in a navigation. See also
1216 // https://crbug.com/1277414.
William Liuec04e382024-05-23 18:03:271217 return nullptr;
Rakina Zata Amnif297a802022-01-18 03:53:431218 }
1219
[email protected]cbab76d2008-10-13 22:42:471220 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201221
arthursonzogni5c4c202d2017-04-25 23:41:271222 DCHECK_EQ(nullptr, pending_entry_);
1223 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431224
arthursonzogni5c4c202d2017-04-25 23:41:271225 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201226 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271227 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1228 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
William Liuec04e382024-05-23 18:03:271229 return NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
1230 soft_navigation_heuristics_task_id,
1231 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201232}
1233
[email protected]d202a7c2012-01-04 07:53:471234void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121235 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031236 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201237 return;
1238
[email protected]9ba14052012-06-22 23:50:031239 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201240}
1241
Nate Chapinbf682fa32022-09-26 22:41:201242void NavigationControllerImpl::GoToOffsetFromRenderer(
1243 int offset,
Yoav Weiss8c573952022-11-17 17:35:131244 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371245 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131246 soft_navigation_heuristics_task_id) {
Nate Chapinbb74c5a52023-07-21 23:13:351247 // Note: This is actually reached in unit tests.
1248 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431249 return;
1250
Nate Chapinbf682fa32022-09-26 22:41:201251 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131252 soft_navigation_heuristics_task_id,
1253 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431254}
1255
William Liuec04e382024-05-23 18:03:271256base::WeakPtr<NavigationRequest>
1257NavigationControllerImpl::GoToIndexAndReturnPrimaryMainFrameRequest(int index) {
1258 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1259 /*soft_navigation_heuristics_task_id=*/std::nullopt,
1260 /*navigation_api_key=*/nullptr);
1261}
1262
Xiaohan Wang7f8052e02022-01-14 18:44:281263#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151264void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1265 // Note: This is actually reached in unit tests.
1266 if (!CanGoToOffsetWithSkipping(offset))
1267 return;
1268
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421269 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151270 GoToIndex(GetIndexForOffset(offset));
1271 return;
1272 }
1273 int increment = offset > 0 ? 1 : -1;
1274 // Find the offset without counting skippable entries.
1275 int target_index = GetIndexForOffset(increment);
1276 int non_skippable_entries = 0;
1277 for (int index = target_index; index >= 0 && index < GetEntryCount();
1278 index += increment) {
1279 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1280 non_skippable_entries++;
1281
1282 if (non_skippable_entries == std::abs(offset)) {
1283 target_index = index;
1284 break;
1285 }
1286 }
1287
1288 GoToIndex(target_index);
1289}
1290#endif
1291
[email protected]41374f12013-07-24 02:49:281292bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151293 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281294 return false;
[email protected]6a13a6c2011-12-20 21:47:121295
[email protected]43032342011-03-21 14:10:311296 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281297 return true;
[email protected]cbab76d2008-10-13 22:42:471298}
1299
Michael Thiessen9b14d512019-09-23 21:19:471300void NavigationControllerImpl::PruneForwardEntries() {
1301 DiscardNonCommittedEntries();
1302 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471303 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471304 if (num_removed <= 0)
1305 return;
Nate Chapin9eb16be72022-09-23 22:54:311306 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471307 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1308 NotifyPrunedEntries(this, remove_start_index /* start index */,
1309 num_removed /* count */);
1310}
1311
Aran Gilman37d11632019-10-08 23:07:151312void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1313 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321314 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311315 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511316 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1317 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321318 }
1319}
1320
Harkiran Bolariaba823e42021-05-21 18:30:361321base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1322 const GURL& url,
1323 const Referrer& referrer,
1324 ui::PageTransition transition,
1325 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471326 LoadURLParams params(url);
1327 params.referrer = referrer;
1328 params.transition_type = transition;
1329 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361330 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471331}
1332
Harkiran Bolariaba823e42021-05-21 18:30:361333base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1334 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061335 if (params.is_renderer_initiated)
1336 DCHECK(params.initiator_origin.has_value());
1337
naskob8744d22014-08-28 17:07:431338 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151339 "NavigationControllerImpl::LoadURLWithParams", "url",
1340 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291341 bool is_explicit_navigation =
1342 GetContentClient()->browser()->IsExplicitNavigation(
1343 params.transition_type);
1344 if (HandleDebugURL(params.url, params.transition_type,
1345 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431346 // If Telemetry is running, allow the URL load to proceed as if it's
1347 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491348 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431349 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361350 return nullptr;
[email protected]47752982014-07-29 08:01:431351 }
[email protected]8bf1048012012-02-08 01:22:181352
[email protected]cf002332012-08-14 19:17:471353 // Checks based on params.load_type.
1354 switch (params.load_type) {
1355 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431356 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471357 break;
1358 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261359 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boström8472105d2024-05-15 04:36:021360 NOTREACHED_IN_MIGRATION() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361361 return nullptr;
[email protected]cf002332012-08-14 19:17:471362 }
1363 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461364 }
[email protected]e47ae9472011-10-13 19:48:341365
[email protected]e47ae9472011-10-13 19:48:341366 // The user initiated a load, we don't need to reload anymore.
1367 needs_reload_ = false;
1368
Harkiran Bolariaba823e42021-05-21 18:30:361369 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441370}
1371
Charlie Reis4c53a962023-06-21 23:17:531372void NavigationControllerImpl::LoadOriginalRequestURL() {
1373 // If the original request URL is not valid, matches the current URL, or
1374 // involves POST data, then simply reload. The POST check avoids issues with
1375 // sending data to the wrong page.
1376 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1377 const GURL& original_request_url =
1378 GetLastCommittedEntry()->GetOriginalRequestURL();
1379 if (!original_request_url.is_valid() ||
1380 original_request_url == last_committed_url ||
1381 GetLastCommittedEntry()->GetHasPostData()) {
1382 Reload(ReloadType::NORMAL, true);
1383 return;
1384 }
1385
1386 // Otherwise, attempt to load the original request URL without any of the
1387 // other data from the current NavigationEntry, replacing the current entry.
1388 // Loading the original URL is useful in cases such as modifying the user
1389 // agent.
1390 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1391 std::make_unique<NavigationController::LoadURLParams>(
1392 original_request_url);
1393 load_params->should_replace_current_entry = true;
1394 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1395 LoadURLWithParams(*load_params.get());
1396}
1397
Mohamed Abdelhalim833de902019-09-16 17:41:451398bool NavigationControllerImpl::PendingEntryMatchesRequest(
1399 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191400 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451401 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191402}
1403
[email protected]d202a7c2012-01-04 07:53:471404bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321405 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071406 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331407 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441408 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251409 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561410 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131411 NavigationRequest* navigation_request) {
1412 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331413
1414 // Note: validation checks and renderer kills due to invalid commit messages
1415 // must happen before getting here, in
1416 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1417 // effects of the navigation have already occurred.
1418
[email protected]cd2e15742013-03-08 04:08:311419 is_initial_navigation_ = false;
1420
Wang Hui96ab1012022-10-11 02:05:491421 // Any pending request to repost a form submission is no longer valid, since a
1422 // different NavigationEntry is committing.
1423 pending_reload_ = ReloadType::NONE;
1424
[email protected]0e8db942008-09-24 21:21:481425 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431426 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451427 if (entry_replaced_by_post_commit_error_) {
1428 // Same document navigation events with a post-commit error should already
1429 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1430 // reaching here.
1431 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331432
Xinghui Lub9e86a352024-05-17 16:29:421433 if (pending_entry_) {
1434 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1435 // `pending_entry_` isn't pointing to the last committed entry.
1436 // Instead, all reload approaches (e.g., in `Reload` and
1437 // `LoadIfNecessary`) should attempt to load the
1438 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1439 // entry itself.
1440 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1441 << "Incorrectly reloading the post commit error page entry.";
1442 }
Xinghui Lue4e50be2024-05-15 21:46:001443
Rakina Zata Amnie2d31312022-11-18 03:38:451444 // Any commit while a post-commit error page is showing should put the
1445 // original entry back, replacing the error page's entry. This includes
1446 // reloads, where the original entry was used as the pending entry and
1447 // should now be at the correct index at commit time.
1448 entries_[last_committed_entry_index_] =
1449 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481450 }
Rakina Zata Amnie2d31312022-11-18 03:38:451451 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1452 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001453 // Must honor user agent overrides in the |navigation_request|, such as
1454 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1455 // result, besides comparing |pending_entry_|'s user agent against
1456 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1457 // agent against LastCommittedEntry's.
1458 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541459 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1460 (PendingEntryMatchesRequest(navigation_request) &&
1461 pending_entry_->GetIsOverridingUserAgent() !=
1462 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001463 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451464 }
[email protected]ecd9d8702008-08-28 22:10:171465
Dave Tapuskaa2ab4f252021-07-08 21:31:281466 bool is_main_frame_navigation = !rfh->GetParent();
1467
Alexander Timind2f2e4f22019-04-02 20:04:531468 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1469 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281470 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141471 // BackForwardCacheMetrics to be associated with the new navigation's
1472 // NavigationEntry, by either creating a new object or reusing the previous
1473 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281474 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211475 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141476 back_forward_cache_metrics = BackForwardCacheMetrics::
1477 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281478 GetLastCommittedEntry(), is_main_frame_navigation,
1479 params.document_sequence_number);
1480 }
Yuzu Saijo29f96ca92022-12-08 04:54:121481
Alexander Timind2f2e4f22019-04-02 20:04:531482 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281483 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451484 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1485 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531486 }
1487 }
1488
Rakina Zata Amnifd8370b2022-11-14 13:32:251489 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1490 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091491 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251492 details->did_replace_entry =
1493 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091494
fdegans9caf66a2015-07-30 21:10:421495 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111496 // except for restored entries. This should be true even if the current commit
1497 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291498 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481499 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081500 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111501
1502 // Only make changes based on the pending entry if the NavigationRequest
1503 // matches it. Otherwise, the pending entry may be for a different request
1504 // (e.g., if a slow history navigation is pending while an auto-subframe
1505 // commit occurs).
1506 if (PendingEntryMatchesRequest(navigation_request)) {
1507 // It is no longer necessary to consider the pending entry as restored.
1508 if (pending_entry_->IsRestored()) {
1509 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1510 was_restored = true;
1511 }
[email protected]e9ba4472008-09-14 15:42:431512
Charlie Reisf8cde712022-10-20 16:25:091513 // If the SiteInstance has changed from the matching pending entry, this
1514 // must be treated as a new navigation with replacement. Set the replacement
1515 // bit here and ClassifyNavigation will identify this case and return
1516 // NEW_ENTRY.
1517 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1518 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1519 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251520 // TODO(nasko,creis,rakina): Move this to happen before committing the
1521 // navigation. This is a bit complicated because we don't currently
1522 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091523 details->did_replace_entry = true;
1524 }
Nasko Oskovaee2f862018-06-15 00:05:521525 }
[email protected]bcd904482012-02-01 01:54:221526
[email protected]e9ba4472008-09-14 15:42:431527 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101528 NavigationType navigation_type =
1529 ClassifyNavigation(rfh, params, navigation_request);
1530 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451531
Rakina Zata Amnie2d31312022-11-18 03:38:451532 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451533 // Ensure that this navigation does not add a navigation entry, since
1534 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1535 // beyond the last committed one. Therefore, `should_replace_current_entry`
1536 // should be set, which replaces the current entry, or this should be a
1537 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251538 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331539 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451540 }
1541
Rakina Zata Amnie2d31312022-11-18 03:38:451542 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551543 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241544 // This is a subframe navigation on the initial empty document, which used
1545 // to not have a NavigationEntry to attach to. Now it can attach to the
1546 // initial NavigationEntry, and we must ensure that its NavigationEntry
1547 // will keep the "initial NavigationEntry" status and won't append a new
1548 // NavigationEntry (it should always do replacement instead).
1549 // See also https://crbug.com/1277414.
1550 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551551 // Subframe navigation on initial NavigationEntry must not append a new
1552 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1553 // means every subframe navigation that happens while we're on the initial
1554 // NavigationEntry will always reuse the existing NavigationEntry and
1555 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101556 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1557 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551558 // This is a navigation that modifies the initial NavigationEntry, either
1559 // for a replacement or a reload. The initial NavigationEntry should
1560 // retain its "initial NavigationEntry" status in this case.
1561 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241562 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251563 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1564 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241565 // This is a synchronous about:blank navigation on the main frame, which
1566 // used to not create a NavigationEntry when we have no NavigationEntry on
1567 // FrameTree creation. We now have the initial NavigationEntry and are on
1568 // the initial NavigationEntry. To preserve old behavior, we should still
1569 // keep the "initial" status for the new NavigationEntry that we will
1570 // create for this navigation, so that subframe navigations under the
1571 // synchronously committed about:blank document will never append new
1572 // NavigationEntry, and instead will just reuse the initial
1573 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1574 // See also https://crbug.com/1277414.
1575 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551576 }
1577 }
1578 DCHECK(!details->should_stay_as_initial_entry ||
1579 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201580
eugenebutee08663a2017-04-27 17:43:121581 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441582 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121583
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071584 details->is_prerender_activation =
1585 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241586 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1587 ->GetOutermostMainFrame()
1588 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071589
Peter Boströmd7592132019-01-30 04:50:311590 // Make sure we do not discard the pending entry for a different ongoing
1591 // navigation when a same document commit comes in unexpectedly from the
1592 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1593 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581594 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061595 bool keep_pending_entry =
1596 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101597 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061598 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311599
Miyoung Shin3299cbf2022-11-22 01:41:101600 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061601 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491602 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051603 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561604 previous_document_had_history_intervention_activation,
1605 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431606 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061607 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491608 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1609 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001610 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431611 break;
[email protected]8ff00d72012-10-23 19:12:211612 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471613 RendererDidNavigateNewSubframe(
1614 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561615 previous_document_had_history_intervention_activation,
1616 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431617 break;
[email protected]8ff00d72012-10-23 19:12:211618 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391619 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251620 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001621 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081622 // We don't send a notification about auto-subframe PageState during
1623 // UpdateStateForFrame, since it looks like nothing has changed. Send
1624 // it here at commit time instead.
1625 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431626 return false;
creis59d5a47cb2016-08-24 23:57:191627 }
[email protected]e9ba4472008-09-14 15:42:431628 break;
Aran Gilman37d11632019-10-08 23:07:151629 case NAVIGATION_TYPE_UNKNOWN:
Peter Boström8472105d2024-05-15 04:36:021630 NOTREACHED_IN_MIGRATION();
Aran Gilman37d11632019-10-08 23:07:151631 break;
[email protected]765b35502008-08-21 00:51:201632 }
1633
[email protected]688aa65c62012-09-28 04:32:221634 // At this point, we know that the navigation has just completed, so
1635 // record the time.
1636 //
1637 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261638 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331639 base::Time timestamp =
1640 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1641 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131642 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221643
Peter Boströmd7592132019-01-30 04:50:311644 // If we aren't keeping the pending entry, there shouldn't be one at this
1645 // point. Clear it again in case any error cases above forgot to do so.
1646 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1647 // been cleared instead of protecting against it.
1648 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551649 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141650
[email protected]e9ba4472008-09-14 15:42:431651 // All committed entries should have nonempty content state so WebKit doesn't
1652 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471653 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321654 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221655 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441656 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141657
Alexander Timind2f2e4f22019-04-02 20:04:531658 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1659 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281660 if (back_forward_cache_metrics &&
1661 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531662 active_entry->set_back_forward_cache_metrics(
1663 std::move(back_forward_cache_metrics));
1664 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281665
1666 // `back_forward_cache_metrics()` may return null as we do not record
1667 // back-forward cache metrics for navigations in non-primary frame trees.
1668 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581669 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141670 // These are both only available from details at this point, so we capture
1671 // them here.
1672 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101673 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141674 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1675 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281676 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1677 navigation_request,
1678 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1679 }
naskoc7533512016-05-06 17:01:121680
Charles Reisc0507202017-09-21 00:40:021681 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1682 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1683 // A mismatch can occur if the renderer lies or due to a unique name collision
1684 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121685 FrameNavigationEntry* frame_entry =
1686 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021687 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1688 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031689 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081690 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1691 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031692 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201693
1694 // Remember the bindings the renderer process has at this point, so that
1695 // we do not grant this entry additional bindings if we come back to it.
1696 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301697 }
[email protected]132e281a2012-07-31 18:32:441698
[email protected]97d8f0d2013-10-29 16:49:211699 // Once it is committed, we no longer need to track several pieces of state on
1700 // the entry.
naskoc7533512016-05-06 17:01:121701 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131702
[email protected]49bd30e62011-03-22 20:12:591703 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221704 // TODO(creis): This check won't pass for subframes until we create entries
1705 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001706 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421707 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591708
[email protected]e9ba4472008-09-14 15:42:431709 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001710 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001711 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311712 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531713
arthursonzogni7ddc6542021-04-09 09:16:501714 active_entry->SetIsOverridingUserAgent(
1715 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031716
[email protected]93f230e02011-06-01 14:40:001717 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291718
aelias100c9192017-01-13 00:01:431719 if (overriding_user_agent_changed)
1720 delegate_->UpdateOverridingUserAgent();
1721
creis03b48002015-11-04 00:54:561722 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1723 // one knows the latest NavigationEntry it is showing (whether it has
1724 // committed anything in this navigation or not). This allows things like
1725 // state and title updates from RenderFrames to apply to the latest relevant
1726 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381727 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031728 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381729 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431730
1731 if (navigation_request->IsPrerenderedPageActivation()) {
1732 BroadcastHistoryOffsetAndLength();
Alison Gale47d1537d2024-04-19 21:31:461733 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431734 // is activated. As a result, a "prerenderingchange" event listener sees the
1735 // history.length which is not updated yet. We should guarantee that
1736 // history's length and offset should be updated before a
1737 // "prerenderingchange" event listener runs. One possible approach is to use
1738 // the same IPC which "prerenderingchange" uses, and propagate history's
1739 // length and offset together with that.
1740 }
1741
[email protected]e9ba4472008-09-14 15:42:431742 return true;
initial.commit09911bf2008-07-26 23:55:291743}
1744
[email protected]8ff00d72012-10-23 19:12:211745NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321746 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101747 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241748 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591749 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511750 "ClassifyNavigation");
1751
avi7c6f35e2015-05-08 17:52:381752 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241753 // A new entry. We may or may not have a corresponding pending entry, and
1754 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001755 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491756 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061757 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381758 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241759 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511760 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381761 return NAVIGATION_TYPE_NEW_SUBFRAME;
1762 }
1763
Charlie Reisc0f17d2d2021-01-12 18:52:491764 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381765 DCHECK(!params.history_list_was_cleared);
1766
avi39c1edd32015-06-04 20:06:001767 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381768 // All manual subframes would be did_create_new_entry and handled above, so
1769 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081770 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1771 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381772 }
1773
Rakina Zata Amnif6950d552020-11-24 03:26:101774 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1775 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381776 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1777 // create a new page.
1778
Hayato Ito2ae49442021-07-02 02:59:251779 // This main frame navigation is not a history navigation (since
1780 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1781 // reload or a replacement navigation, which will modify the existing entry.
1782 //
Nasko Oskov332593c2018-08-16 17:21:341783 // TODO(nasko): With error page isolation, reloading an existing session
1784 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491785 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341786 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511787 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491788 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061789 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381790 }
1791
Charlie Reisf8cde712022-10-20 16:25:091792 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521793 // If the SiteInstance of the |pending_entry_| does not match the
1794 // SiteInstance that got committed, treat this as a new navigation with
1795 // replacement. This can happen if back/forward/reload encounters a server
1796 // redirect to a different site or an isolated error page gets successfully
1797 // reloaded into a different SiteInstance.
1798 if (pending_entry_->site_instance() &&
1799 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491800 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061801 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521802 }
creis77c9aa32015-09-25 19:59:421803
Nasko Oskovaee2f862018-06-15 00:05:521804 if (pending_entry_index_ == -1) {
1805 // In this case, we have a pending entry for a load of a new URL but Blink
1806 // didn't do a new navigation (params.did_create_new_entry). First check
1807 // to make sure Blink didn't treat a new cross-process navigation as
1808 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161809 // we must treat it as NEW rather than the converted reload case below,
1810 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451811 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161812 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061813 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521814 }
1815
1816 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161817 // We will create a pending entry, but NavigateWithoutEntry will convert
1818 // it to a reload since it's the same page and not create a new entry for
1819 // it. (The user doesn't want to have a new back/forward entry when they
1820 // do this.) Therefore we want to just ignore the pending entry and go
1821 // back to where we were (the "existing entry").
1822 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061823 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521824 }
avi7c6f35e2015-05-08 17:52:381825 }
1826
Rakina Zata Amni153d5702021-09-13 22:48:001827 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381828 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491829 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1830 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161831 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061832 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381833 }
1834
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121835 if (navigation_request->DidEncounterError() &&
1836 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101837 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381838 // If the renderer was going to a new pending entry that got cleared because
1839 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491840 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381841 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511842 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491843 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061844 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381845 }
1846
Charlie Reisc0f17d2d2021-01-12 18:52:491847 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101848 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511849 trace_return.traced_value()->SetInteger("existing_entry_index",
1850 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381851 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441852 // The renderer has committed a navigation to an entry that no longer
1853 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491854 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061855 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381856 }
1857
avi7c6f35e2015-05-08 17:52:381858 // Since we weeded out "new" navigations above, we know this is an existing
1859 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491860 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061861 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381862}
1863
Rakina Zata Amni3460d382021-10-29 00:43:371864void NavigationControllerImpl::UpdateNavigationEntryDetails(
1865 NavigationEntryImpl* entry,
1866 RenderFrameHostImpl* rfh,
1867 const mojom::DidCommitProvisionalLoadParams& params,
1868 NavigationRequest* request,
1869 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001870 bool is_new_entry,
1871 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371872 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171873 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371874 entry->AddOrUpdateFrameEntry(
1875 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571876 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371877 rfh->GetSiteInstance(), nullptr, params.url,
1878 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171879 Referrer(*params.referrer),
1880 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371881 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171882 request ? request->GetRedirectChain() : redirects, params.page_state,
1883 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371884 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171885 rfh, request && request->IsSameDocument(),
1886 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371887
1888 if (rfh->GetParent()) {
1889 // Only modify the NavigationEntry for main frame navigations.
1890 return;
1891 }
1892 if (entry->update_virtual_url_with_url())
1893 UpdateVirtualURLToURL(entry, params.url);
1894 // Don't use the page type from the pending entry. Some interstitial page
1895 // may have set the type to interstitial. Once we commit, however, the page
1896 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171897 entry->set_page_type((request && request->DidEncounterError())
1898 ? PAGE_TYPE_ERROR
1899 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431900 if (commit_details && commit_details->should_stay_as_initial_entry) {
1901 // Retain the "initial NavigationEntry" status.
1902 if (request->IsSameDocument()) {
1903 // If this is for a same-document navigation, the NavigationEntry must be
1904 // reused and should already be marked as the initial NavigationEntry.
1905 DCHECK(entry->IsInitialEntry());
1906 } else {
1907 // If this is for a cross-document navigation, it can be caused by a
1908 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1909 // "for synchronous about:blank" in the latter case, and also when it is
1910 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1911 // is not for a synchronous about:blank commit.
1912 NavigationEntryImpl::InitialNavigationEntryState new_state =
1913 NavigationEntryImpl::InitialNavigationEntryState::
1914 kInitialNotForSynchronousAboutBlank;
1915 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1916 request->is_synchronous_renderer_commit()) {
1917 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1918 kInitialForSynchronousAboutBlank;
1919 }
1920 entry->set_initial_navigation_entry_state(new_state);
1921 }
1922 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1923 // Remove the "initial NavigationEntry" status.
1924 entry->set_initial_navigation_entry_state(
1925 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001926 }
Rakina Zata Amniddf10502022-01-15 02:56:551927
Rakina Zata Amni3460d382021-10-29 00:43:371928 if (is_new_entry) {
1929 // Some properties of the NavigationEntry are only set when the entry is
1930 // new (we aren't reusing it).
1931 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171932 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:401933 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:011934 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
1935 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:371936 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1937 } else {
1938 // We are reusing the NavigationEntry. The site instance will normally be
1939 // the same except for a few cases:
1940 // 1) session restore, when no site instance will be assigned or
1941 // 2) redirect, when the site instance is reset.
1942 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1943 entry->site_instance() == rfh->GetSiteInstance());
1944 }
1945}
1946
Rakina Zata Amniafd3c6582021-11-30 06:19:171947void NavigationControllerImpl::CreateInitialEntry() {
1948 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031949 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171950 auto params = mojom::DidCommitProvisionalLoadParams::New();
1951 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1952 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1953 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:401954 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:171955 params->http_status_code = 0;
1956 params->url_is_unreachable = false;
1957 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171958 params->post_id = -1;
1959 params->embedding_token = base::UnguessableToken::Create();
1960 params->navigation_token = base::UnguessableToken::Create();
1961 params->did_create_new_entry = true;
1962 params->origin = rfh->GetLastCommittedOrigin();
1963 params->should_update_history = true;
1964 params->item_sequence_number = 0;
1965 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151966 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171967 params->transition = is_in_fenced_frame_tree
1968 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1969 : ui::PAGE_TRANSITION_LINK;
1970 params->referrer = blink::mojom::Referrer::New();
1971
Rakina Zata Amniafd3c6582021-11-30 06:19:171972 auto new_entry = std::make_unique<NavigationEntryImpl>(
1973 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381974 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211975 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1976 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1977 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171978 UpdateNavigationEntryDetails(
1979 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001980 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1981 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171982
1983 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1984 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001985 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171986}
1987
Charlie Reisc0f17d2d2021-01-12 18:52:491988void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321989 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071990 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361991 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441992 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561993 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:001994 NavigationRequest* request,
1995 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571996 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:371997 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451998 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:371999 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522000 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2001 initiator_base_url = request->common_params().initiator_base_url;
2002 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062003
creisf49dfc92016-07-26 17:05:182004 // First check if this is an in-page navigation. If so, clone the current
2005 // entry instead of looking at the pending entry, because the pending entry
2006 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452007 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302008 FrameNavigationEntry* previous_frame_entry =
2009 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452010 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482011 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572012 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082013 rfh->GetSiteInstance(), nullptr, params.url,
2014 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212015 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092016 request->GetRedirectChain(), params.page_state, params.method,
2017 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392018 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302019 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572020 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302021 // FrameNavigationEntry.
2022 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572023 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032024
creisf49dfc92016-07-26 17:05:182025 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032026 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522027 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2028 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572029 // TODO(jam): we had one report of this with a URL that was redirecting to
2030 // only tildes. Until we understand that better, don't copy the cert in
2031 // this case.
2032 new_entry->GetSSL() = SSLStatus();
2033 }
creisf49dfc92016-07-26 17:05:182034
Patrick Monette50e8bd82019-06-13 22:40:452035 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2036 // that |frame_entry| should now have a reference count of exactly 2: one
2037 // due to the local variable |frame_entry|, and another due to |new_entry|
2038 // also retaining one. This should never fail, because it's the main frame.
2039 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182040 }
2041
Harkiran Bolaria59290d62021-03-17 01:53:012042 // If this is an activation navigation from a prerendered page, transfer the
2043 // new entry from an entry already created and stored in the
2044 // NavigationRequest. |new_entry| will not have been set prior to this as
2045 // |is_same_document| is mutually exclusive with
2046 // |IsPrerenderedPageActivation|.
2047 if (request->IsPrerenderedPageActivation()) {
2048 DCHECK(!is_same_document);
2049 DCHECK(!new_entry);
2050 new_entry = request->TakePrerenderNavigationEntry();
2051 DCHECK(new_entry);
2052 }
2053
Charlie Reisc0f17d2d2021-01-12 18:52:492054 // Only make a copy of the pending entry if it is appropriate for the new
2055 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452056 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042057 // 1. The SiteInstance hasn't been assigned to something else.
2058 // 2. The pending entry was intended as a new entry, rather than being a
2059 // history navigation that was interrupted by an unrelated,
2060 // renderer-initiated navigation.
2061 // TODO(csharrison): Investigate whether we can remove some of the coarser
2062 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452063 if (!new_entry && PendingEntryMatchesRequest(request) &&
2064 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342065 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432066 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352067 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432068
Camille Lamy62b826012019-02-26 09:15:472069 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452070 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182071 }
2072
Charlie Reisc0f17d2d2021-01-12 18:52:492073 // For cross-document commits with no matching pending entry, create a new
2074 // entry.
creisf49dfc92016-07-26 17:05:182075 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062076 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072077 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212078 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582079 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452080 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172081 nullptr, // blob_url_loader_factory
2082 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242083
2084 // Find out whether the new entry needs to update its virtual URL on URL
2085 // change and set up the entry accordingly. This is needed to correctly
2086 // update the virtual URL when replaceState is called after a pushState.
2087 GURL url = params.url;
2088 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492089 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412090 // update the virtual URL based on the new URL. For example, this is needed
2091 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2092 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372093 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2094 &url, browser_context_, &needs_update);
2095 new_entry->set_update_virtual_url_with_url(needs_update);
2096
Camille Lamy62b826012019-02-26 09:15:472097 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452098 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432099 }
2100
Alison Gale770f3fc2024-04-27 00:39:582101 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2102 // set for prerendered contents, if any. This is because
2103 // prerendering/activation technically won't be creating a new document.
2104 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2105 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012106 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372107 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2108 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002109 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082110
Harkiran Bolaria59290d62021-03-17 01:53:012111 // history.pushState() is classified as a navigation to a new page, but sets
2112 // is_same_document to true. In this case, we already have the title and
2113 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452114 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012115 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2116 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2117 }
[email protected]3a868f212014-08-09 10:41:192118 }
[email protected]ff64b3e2014-05-31 04:07:332119
[email protected]60d6cca2013-04-30 08:47:132120 DCHECK(!params.history_list_was_cleared || !replace_entry);
2121 // The browser requested to clear the session history when it initiated the
2122 // navigation. Now we know that the renderer has updated its state accordingly
2123 // and it is safe to also clear the browser side history.
2124 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552125 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132126 entries_.clear();
2127 last_committed_entry_index_ = -1;
2128 }
2129
Nasko Oskovaee2f862018-06-15 00:05:522130 // If this is a new navigation with replacement and there is a
2131 // pending_entry_ which matches the navigation reported by the renderer
2132 // process, then it should be the one replaced, so update the
2133 // last_committed_entry_index_ to use it.
2134 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092135 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522136 last_committed_entry_index_ = pending_entry_index_;
2137 }
2138
Alexander Timine3ec4192020-04-20 16:39:402139 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562140 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402141 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052142
Yuzu Saijoa725585f2022-11-28 04:14:032143 // If this is a history navigation and the old entry has an existing
2144 // back/forward cache metrics object, keep using the old one so that the
2145 // reasons logged from the last time the page navigated gets preserved.
2146 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2147 request)) {
2148 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2149 // because some tests do not have a pending entry.
2150 NavigationEntryImpl* entry =
2151 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2152 if (entry && entry->back_forward_cache_metrics()) {
2153 scoped_refptr<BackForwardCacheMetrics> metrics =
2154 entry->TakeBackForwardCacheMetrics();
2155 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2156 }
2157 }
2158
Carlos IL42b416592019-10-07 23:10:362159 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312160 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152161 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432162}
2163
Charlie Reisc0f17d2d2021-01-12 18:52:492164void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322165 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072166 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362167 bool is_same_document,
jam48cea9082017-02-15 06:13:292168 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452169 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002170 bool keep_pending_entry,
2171 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562172 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2173 << "that a last committed entry exists.";
2174
[email protected]e9ba4472008-09-14 15:42:432175 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002176 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432177
Charlie Reis7e2cb6d2021-01-26 01:27:162178 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002179 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162180 // We're guaranteed to have a last committed entry if intended_as_new_entry
2181 // is true.
avicbdc4c12015-07-01 16:07:112182 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162183
2184 // If the NavigationRequest matches a new pending entry and is classified as
2185 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2186 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092187 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162188 // Note: The pending entry will usually have a real ReloadType here, but
2189 // it can still be ReloadType::NONE in cases that
2190 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2191
2192 // If we classified this correctly, the SiteInstance should not have
2193 // changed.
2194 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2195
2196 // For converted reloads, we assign the entry's unique ID to be that of
2197 // the new one. Since this is always the result of a user action, we want
2198 // to dismiss infobars, etc. like a regular user-initiated navigation.
2199 entry->set_unique_id(pending_entry_->GetUniqueID());
2200
2201 // The extra headers may have changed due to reloading with different
2202 // headers.
2203 entry->set_extra_headers(pending_entry_->extra_headers());
2204 }
2205 // Otherwise, this was intended as a new entry but the pending entry was
2206 // lost in the meantime and no new entry was created. We are stuck at the
2207 // last committed entry.
2208
2209 // Even if this is a converted reload from pressing enter in the omnibox,
2210 // the server could redirect, requiring an update to the SSL status. If this
2211 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452212 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162213 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472214 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452215 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162216 }
Rakina Zata Amnif6950d552020-11-24 03:26:102217 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112218 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102219 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162220
eugenebut604866f2017-05-10 21:35:362221 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452222 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362223 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2224 // this was a restored same document navigation entry, then it won't have
2225 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2226 // navigated it.
jam48cea9082017-02-15 06:13:292227 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522228 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2229 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292230 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2231 was_restored) {
2232 entry->GetSSL() = last_entry->GetSSL();
2233 }
2234 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452235 // In rapid back/forward navigations |request| sometimes won't have a cert
2236 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192237 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452238 if (request->GetSSLInfo().has_value() &&
2239 request->GetSSLInfo()->is_valid()) {
2240 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522241 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2242 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192243 entry->GetSSL() = SSLStatus();
2244 }
jam48cea9082017-02-15 06:13:292245 }
avicbdc4c12015-07-01 16:07:112246 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272247 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572248 // navigations that are EXISTING_ENTRY are same-document navigations that
2249 // result in replacement (e.g. history.replaceState(), location.replace(),
2250 // forced replacements for trivial session history contexts). For these
2251 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112252 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102253
Alison Gale81f4f2c72024-04-22 19:33:312254 // TODO(crbug.com/40532777): Set page transition type to
2255 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2256 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2257 // well as to fix the inconsistency with what we report to observers
2258 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102259
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572260 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102261
eugenebut604866f2017-05-10 21:35:362262 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452263 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362264 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472265 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452266 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112267 }
2268 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432269
Rakina Zata Amni3460d382021-10-29 00:43:372270 UpdateNavigationEntryDetails(entry, rfh, params, request,
2271 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002272 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302273
[email protected]5ccd4dc2012-10-24 02:28:142274 // The redirected to page should not inherit the favicon from the previous
2275 // page.
eugenebut604866f2017-05-10 21:35:362276 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482277 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142278
Charlie Reis951f43372023-05-05 00:30:072279 // Update the last committed index to reflect the committed entry. Do this
2280 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2281 // delegate sees the correct committed index when notified of navigation
2282 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2283 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212284 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072285
Peter Boströmd7592132019-01-30 04:50:312286 // We should also usually discard the pending entry if it corresponds to a
2287 // different navigation, since that one is now likely canceled. In rare
2288 // cases, we leave the pending entry for another navigation in place when we
2289 // know it is still ongoing, to avoid a flicker in the omnibox (see
2290 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432291 //
2292 // Note that we need to use the "internal" version since we don't want to
2293 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312294 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002295 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432296}
2297
[email protected]d202a7c2012-01-04 07:53:472298void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322299 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072300 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362301 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472302 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562303 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002304 NavigationRequest* request,
2305 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262306 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2307 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552308 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2309 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112310
[email protected]e9ba4472008-09-14 15:42:432311 // Manual subframe navigations just get the current entry cloned so the user
2312 // can go back or forward to it. The actual subframe information will be
2313 // stored in the page state for each of those entries. This happens out of
2314 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092315 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2316 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382317
Mikel Astizba9cf2fd2017-12-17 10:38:102318 // The DCHECK below documents the fact that we don't know of any situation
2319 // where |replace_entry| is true for subframe navigations. This simplifies
2320 // reasoning about the replacement struct for subframes (see
2321 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2322 DCHECK(!replace_entry);
2323
Patrick Monette50e8bd82019-06-13 22:40:452324 // This FrameNavigationEntry might not end up being used in the
2325 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372326 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452327 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372328 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522329 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2330 initiator_base_url = request->common_params().initiator_base_url;
2331 }
Nate Chapin63db0d12022-01-20 22:03:302332 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2333 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2334 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572335 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302336 if (is_same_document) {
2337 FrameNavigationEntry* previous_frame_entry =
2338 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572339 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302340 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572341 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302342 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572343 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302344 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572345 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302346 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572347 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302348 policy_container_policies->referrer_policy);
2349 }
2350
Patrick Monette50e8bd82019-06-13 22:40:452351 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482352 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572353 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082354 rfh->GetSiteInstance(), nullptr, params.url,
2355 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212356 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2357 request->GetRedirectChain(), params.page_state, params.method,
2358 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572359 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032360
creisce0ef3572017-01-26 17:53:082361 std::unique_ptr<NavigationEntryImpl> new_entry =
2362 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452363 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032364 frame_tree_->root());
creise062d542015-08-25 02:01:552365
Alexander Timine3ec4192020-04-20 16:39:402366 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562367 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402368 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472369
creisce0ef3572017-01-26 17:53:082370 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452371 // to replace, which can happen due to a unique name change. See
2372 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2373 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382374
Dave Tapuska87696ae2021-11-18 18:48:312375 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152376 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432377}
2378
[email protected]d202a7c2012-01-04 07:53:472379bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322380 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072381 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392382 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252383 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002384 NavigationRequest* request,
2385 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292386 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2387 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2388
[email protected]e9ba4472008-09-14 15:42:432389 // We're guaranteed to have a previously committed entry, and we now need to
2390 // handle navigation inside of a subframe in it without creating a new entry.
2391 DCHECK(GetLastCommittedEntry());
2392
creis913c63ce2016-07-16 19:52:522393 // For newly created subframes, we don't need to send a commit notification.
2394 // This is only necessary for history navigations in subframes.
2395 bool send_commit_notification = false;
2396
Rakina Zata Amnif6950d552020-11-24 03:26:102397 // If |nav_entry_id| is non-zero and matches an existing entry, this
2398 // is a history navigation. Update the last committed index accordingly. If
2399 // we don't recognize the |nav_entry_id|, it might be a recently
2400 // pruned entry. We'll handle it below.
2401 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2402 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472403 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062404 // Make sure that a subframe commit isn't changing the main frame's
2405 // origin. Otherwise the renderer process may be confused, leading to a
2406 // URL spoof. We can't check the path since that may change
2407 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572408 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2409 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242410 // We should use checks similar to RenderFrameHostImpl's
2411 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2412 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572413 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2414 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2415 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2416 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522417 current_top_url.DeprecatedGetOriginAsURL() !=
2418 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442419 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512420 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062421 }
creis3cdc3b02015-05-29 23:00:472422
creis913c63ce2016-07-16 19:52:522423 // We only need to discard the pending entry in this history navigation
2424 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062425 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002426 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522427
2428 // History navigations should send a commit notification.
2429 send_commit_notification = true;
avi98405c22015-05-21 20:47:062430 }
[email protected]e9ba4472008-09-14 15:42:432431 }
[email protected]f233e4232013-02-23 00:55:142432
creisce0ef3572017-01-26 17:53:082433 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2434 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372435 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2436 // exists), or we may want to clobber it and create a new one. We update in
2437 // cases where the corresponding FrameNavigationEntry is conceptually similar
2438 // to the document described by the commit params: same-document
2439 // navigations, history traversal to an existing entry, and reloads (including
2440 // a "soft reload" where we navigate to the same url without flagging it as a
2441 // reload). But in the case of a different document that is not logically
2442 // related to the committed FrameNavigationEntry's document (cross-document,
2443 // not same url, not a reload, not a history traversal), we replace rather
2444 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252445 //
Nate Chapin9f169072021-06-09 19:32:372446 // In the case where we update, the FrameNavigationEntry will potentially be
2447 // shared across multiple NavigationEntries, and any updates will be reflected
2448 // in all of those NavigationEntries. In the replace case, any existing
2449 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252450 //
2451 // When navigating away from the initial empty document, we also update rather
2452 // than replace. Either update or replace will overwrite the initial empty
2453 // document state for |last_committed|, but if the FrameNavigationEntry for
2454 // the initial empty document is shared across multiple NavigationEntries (due
2455 // to a navigation in another frame), we want to make sure we overwrite the
2456 // initial empty document state everywhere this FrameNavigationEntry is used,
2457 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452458 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372459 FrameNavigationEntry* last_committed_frame_entry =
2460 last_committed->GetFrameEntry(rfh->frame_tree_node());
2461 NavigationEntryImpl::UpdatePolicy update_policy =
2462 NavigationEntryImpl::UpdatePolicy::kUpdate;
2463 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312464 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372465 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252466 last_committed_frame_entry->url() != params.url &&
2467 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372468 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2469 }
2470
Rakina Zata Amni3460d382021-10-29 00:43:372471 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002472 update_policy, false /* is_new_entry */,
2473 commit_details);
creis625a0c7d2015-03-24 23:17:122474
creis913c63ce2016-07-16 19:52:522475 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432476}
2477
[email protected]d202a7c2012-01-04 07:53:472478int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232479 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032480 for (size_t i = 0; i < entries_.size(); ++i) {
2481 if (entries_[i].get() == entry)
2482 return i;
2483 }
2484 return -1;
[email protected]765b35502008-08-21 00:51:202485}
2486
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572487void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242488 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572489 NavigationControllerImpl* source =
2490 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572491 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382492 DCHECK_EQ(1, GetEntryCount());
2493 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472494 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172495 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572496
Francois Dorayeaace782017-06-21 16:37:242497 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442498 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572499 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572500
Fergal Dalya1d569972021-03-16 03:24:532501 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302502 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532503 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2504 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302505 }
[email protected]4e6419c2010-01-15 04:50:342506
Lukasz Anforowicz0de0f452020-12-02 19:57:152507 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572508}
2509
Aran Gilman37d11632019-10-08 23:07:152510void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2511 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162512 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012513 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162514
[email protected]d202a7c2012-01-04 07:53:472515 NavigationControllerImpl* source =
2516 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252517
avi2b177592014-12-10 02:08:022518 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012519 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252520
[email protected]474f8512013-05-31 22:31:162521 // We now have one entry, possibly with a new pending entry. Ensure that
2522 // adding the entries from source won't put us over the limit.
2523 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572524 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572525 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252526
Carlos IL4dea8902020-05-26 15:14:292527 // Insert the entries from source. Ignore any pending entry, since it has not
2528 // committed in source.
[email protected]474f8512013-05-31 22:31:162529 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172530 DCHECK_NE(max_source_index, -1);
2531 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572532
2533 // Ignore the source's current entry if merging with replacement.
2534 // TODO(davidben): This should preserve entries forward of the current
2535 // too. http://crbug.com/317872
2536 if (replace_entry && max_source_index > 0)
2537 max_source_index--;
2538
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572539 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252540
2541 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552542 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142543
Hayato Ito2c8c08d02021-06-23 03:38:432544 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252545}
2546
[email protected]79368982013-11-13 01:11:012547bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162548 // If there is no last committed entry, we cannot prune. Even if there is a
2549 // pending entry, it may not commit, leaving this WebContents blank, despite
2550 // possibly giving it new entries via CopyStateFromAndPrune.
2551 if (last_committed_entry_index_ == -1)
2552 return false;
[email protected]9350602e2013-02-26 23:27:442553
[email protected]474f8512013-05-31 22:31:162554 // We cannot prune if there is a pending entry at an existing entry index.
2555 // It may not commit, so we have to keep the last committed entry, and thus
2556 // there is no sensible place to keep the pending entry. It is ok to have
2557 // a new pending entry, which can optionally commit as a new navigation.
2558 if (pending_entry_index_ != -1)
2559 return false;
2560
[email protected]474f8512013-05-31 22:31:162561 return true;
2562}
2563
[email protected]79368982013-11-13 01:11:012564void NavigationControllerImpl::PruneAllButLastCommitted() {
2565 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162566
avi2b177592014-12-10 02:08:022567 DCHECK_EQ(0, last_committed_entry_index_);
2568 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442569
Hayato Ito2c8c08d02021-06-23 03:38:432570 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442571}
2572
[email protected]79368982013-11-13 01:11:012573void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162574 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012575 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262576
Nate Chapin9eb16be72022-09-23 22:54:312577 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2578
[email protected]474f8512013-05-31 22:31:162579 // Erase all entries but the last committed entry. There may still be a
2580 // new pending entry after this.
2581 entries_.erase(entries_.begin(),
2582 entries_.begin() + last_committed_entry_index_);
2583 entries_.erase(entries_.begin() + 1, entries_.end());
2584 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262585}
2586
Christian Dullweber1af31e62018-02-22 11:49:482587void NavigationControllerImpl::DeleteNavigationEntries(
2588 const DeletionPredicate& deletionPredicate) {
2589 // It is up to callers to check the invariants before calling this.
2590 CHECK(CanPruneAllButLastCommitted());
2591 std::vector<int> delete_indices;
2592 for (size_t i = 0; i < entries_.size(); i++) {
2593 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572594 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482595 delete_indices.push_back(i);
2596 }
2597 }
2598 if (delete_indices.empty())
2599 return;
2600
2601 if (delete_indices.size() == GetEntryCount() - 1U) {
2602 PruneAllButLastCommitted();
2603 } else {
2604 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382605 for (const auto& index : base::Reversed(delete_indices)) {
2606 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482607 }
Hayato Ito2c8c08d02021-06-23 03:38:432608 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482609 }
2610 delegate()->NotifyNavigationEntriesDeleted();
2611}
2612
Carlos Caballero35ce710c2019-09-19 10:59:452613BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2614 return back_forward_cache_;
2615}
2616
William Liu055a3542023-04-02 17:21:192617NavigationEntryScreenshotCache*
2618NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212619 CHECK(frame_tree_->is_primary());
William Liu055a3542023-04-02 17:21:192620 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2621 nav_entry_screenshot_cache_ =
2622 std::make_unique<NavigationEntryScreenshotCache>(
2623 BrowserContextImpl::From(browser_context_)
2624 ->GetNavigationEntryScreenshotManager()
2625 ->GetSafeRef(),
2626 this);
2627 }
2628 return nav_entry_screenshot_cache_.get();
2629}
2630
clamy987a3752018-05-03 17:36:262631void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2632 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2633 // progress, since this will cause a use-after-free. (We only allow this
2634 // when the tab is being destroyed for shutdown, since it won't return to
2635 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032636 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262637
2638 if (was_failure && pending_entry_) {
2639 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2640 } else {
2641 failed_pending_entry_id_ = 0;
2642 }
2643
2644 if (pending_entry_) {
2645 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332646 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262647 pending_entry_index_ = -1;
2648 pending_entry_ = nullptr;
2649 }
arthursonzogni66f711c2019-10-08 14:40:362650
2651 // Ensure any refs to the current pending entry are ignored if they get
2652 // deleted, by clearing the set of known refs. All future pending entries will
2653 // only be affected by new refs.
2654 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262655}
2656
2657void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2658 if (pending_entry_)
2659 pending_entry_->set_ssl_error(error);
2660}
2661
Xiaohan Wang7f8052e02022-01-14 18:44:282662#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422663// static
2664bool NavigationControllerImpl::ValidateDataURLAsString(
2665 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2666 if (!data_url_as_string)
2667 return false;
2668
2669 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2670 return false;
2671
2672 // The number of characters that is enough for validating a data: URI.
2673 // From the GURL's POV, the only important part here is scheme, it doesn't
2674 // check the actual content. Thus we can take only the prefix of the url, to
2675 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562676 constexpr size_t kDataUriPrefixMaxLen = 64;
2677 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2678 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422679 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2680 return false;
2681
2682 return true;
2683}
2684#endif
2685
Shivani Sharma194877032019-03-07 17:52:472686void NavigationControllerImpl::NotifyUserActivation() {
2687 // When a user activation occurs, ensure that all adjacent entries for the
2688 // same document clear their skippable bit, so that the history manipulation
2689 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012690 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172691 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012692 // If the value of CanGoBack changes as a result of making some entries
2693 // non-skippable, then we must let the delegate know to update its UI state.
2694 // See https://crbug.com/1477784.
2695 if (!can_go_back && CanGoBack()) {
2696 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2697 }
Shivani Sharma194877032019-03-07 17:52:472698}
2699
clamy987a3752018-05-03 17:36:262700bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2701 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332702 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2703 blink::LocalFrameToken initiator_frame_token,
2704 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262705 NavigationEntryImpl* entry =
2706 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2707 if (!entry)
2708 return false;
2709
2710 FrameNavigationEntry* frame_entry =
2711 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2712 if (!frame_entry)
2713 return false;
2714
Camille Lamy5193caa2018-10-12 11:59:422715 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572716 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232717 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332718 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2719 initiator_process_id);
clamyea99ea12018-05-28 13:54:232720
2721 if (!request)
2722 return false;
2723
arthursonzognif046d4a2019-12-12 19:08:102724 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412725
Rakina Zata Amni1c83b082023-02-08 01:09:002726 SCOPED_CRASH_KEY_STRING256(
2727 "Bug1400009", "req_url",
2728 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2729 SCOPED_CRASH_KEY_NUMBER(
2730 "Bug1400009", "nav_entry_si",
2731 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2732 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2733 frame_entry->site_instance()
2734 ? ((int)frame_entry->site_instance()->GetId())
2735 : -1);
2736 bool has_sig =
2737 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2738 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2739 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2740 has_sig ? (!!frame_tree_->GetRenderViewHost(
2741 frame_entry->site_instance()->group()))
2742 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052743 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2744 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232745
2746 return true;
clamy987a3752018-05-03 17:36:262747}
2748
Tsuyoshi Horo52fd08e2020-07-07 07:03:452749bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2750 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2751 if (!entry)
2752 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432753
2754 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2755 // We should never navigate to an existing initial NavigationEntry that is
2756 // the initial NavigationEntry for the initial empty document that hasn't
2757 // been overridden by the synchronous about:blank commit, to preserve
2758 // legacy behavior where trying to reload when the main frame is on the
2759 // initial empty document won't result in a navigation. See also
2760 // https://crbug.com/1277414.
2761 return false;
2762 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452763 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2764 if (!frame_entry)
2765 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142766 ReloadType reload_type = ReloadType::NORMAL;
2767 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452768 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142769 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452770 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432771 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372772 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332773 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452774 if (!request)
2775 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052776 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452777 return true;
2778}
2779
clamy987a3752018-05-03 17:36:262780void NavigationControllerImpl::NavigateFromFrameProxy(
2781 RenderFrameHostImpl* render_frame_host,
2782 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022783 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452784 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372785 const std::optional<url::Origin>& initiator_origin,
2786 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262787 bool is_renderer_initiated,
2788 SiteInstance* source_site_instance,
2789 const Referrer& referrer,
2790 ui::PageTransition page_transition,
2791 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252792 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262793 const std::string& method,
2794 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092795 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142796 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212797 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502798 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372799 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292800 blink::mojom::NavigationInitiatorActivationAndAdStatus
2801 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222802 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492803 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462804 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452805 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582806 bool is_container_initiated,
Arthur Sonzognic686e8f2024-01-11 08:36:372807 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582808 if (is_renderer_initiated)
2809 DCHECK(initiator_origin.has_value());
2810
clamy987a3752018-05-03 17:36:262811 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582812
Rakina Zata Amni2322f4f82022-01-24 13:24:242813 // Don't allow an entry replacement if there is no entry to replace.
2814 // http://crbug.com/457149
2815 if (GetEntryCount() == 0)
2816 should_replace_current_entry = false;
2817
clamy987a3752018-05-03 17:36:262818 // Create a NavigationEntry for the transfer, without making it the pending
2819 // entry. Subframe transfers should have a clone of the last committed entry
2820 // with a FrameNavigationEntry for the target frame. Main frame transfers
2821 // should have a new NavigationEntry.
2822 // TODO(creis): Make this unnecessary by creating (and validating) the params
2823 // directly, passing them to the destination RenderFrameHost. See
2824 // https://crbug.com/536906.
2825 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262826 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262827 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452828 DCHECK(GetLastCommittedEntry());
2829 entry = GetLastCommittedEntry()->Clone();
2830 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172831 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2832 // Renderer-initiated navigation that target a remote frame are currently
2833 // classified as browser-initiated when this one has already navigated.
2834 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372835 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2836 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2837 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2838 // same-document navigation), they will still be present in the
2839 // committed NavigationEntry that will be referenced to construct the new
2840 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262841 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082842 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582843 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372844 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212845 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152846 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262847 } else {
2848 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172849 // If `node` is the outermost main frame, it rewrites a virtual url in order
2850 // to adjust the original input url if needed. For inner frames such as
2851 // fenced frames or subframes, they don't rewrite urls as the urls are not
2852 // input urls by users.
2853 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372854 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322855 if (source_site_instance && source_site_instance->HasProcess()) {
2856 source_process_site_url =
2857 source_site_instance->GetProcess()->GetProcessLock().site_url();
2858 }
clamy987a3752018-05-03 17:36:262859 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212860 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322861 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212862 extra_headers, browser_context_, blob_url_loader_factory,
2863 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262864 entry->root_node()->frame_entry->set_source_site_instance(
2865 static_cast<SiteInstanceImpl*>(source_site_instance));
2866 entry->root_node()->frame_entry->set_method(method);
2867 }
clamy987a3752018-05-03 17:36:262868
Camille Lamy5193caa2018-10-12 11:59:422869 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452870 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262871 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422872 override_user_agent = true;
clamy987a3752018-05-03 17:36:262873 }
2874 // TODO(creis): Set user gesture and intent received timestamp on Android.
2875
2876 // We may not have successfully added the FrameNavigationEntry to |entry|
2877 // above (per https://crbug.com/608402), in which case we create it from
2878 // scratch. This works because we do not depend on |frame_entry| being inside
2879 // |entry| during NavigateToEntry. This will go away when we shortcut this
2880 // further in https://crbug.com/536906.
2881 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2882 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452883 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082884 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582885 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372886 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212887 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152888 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572889 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262890 }
2891
Camille Lamy5193caa2018-10-12 11:59:422892 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022893 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452894 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292895 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212896 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422897 params.source_site_instance = source_site_instance;
2898 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2899 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032900 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422901 params.referrer = referrer;
2902 /* params.redirect_chain: skip */
2903 params.extra_headers = extra_headers;
2904 params.is_renderer_initiated = is_renderer_initiated;
2905 params.override_user_agent = UA_OVERRIDE_INHERIT;
2906 /* params.base_url_for_data_url: skip */
2907 /* params.virtual_url_for_data_url: skip */
2908 /* params.data_url_as_string: skip */
2909 params.post_data = post_body;
2910 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582911 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422912 /* params.frame_name: skip */
2913 // TODO(clamy): See if user gesture should be propagated to this function.
2914 params.has_user_gesture = false;
2915 params.should_clear_history_list = false;
2916 params.started_from_context_menu = false;
2917 /* params.navigation_ui_data: skip */
2918 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222919 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542920 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212921 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412922 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502923 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292924 params.initiator_activation_and_ad_status =
2925 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422926
2927 std::unique_ptr<NavigationRequest> request =
2928 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032929 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142930 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392931 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492932 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582933 is_unfenced_top_navigation, is_container_initiated,
2934 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232935
2936 if (!request)
2937 return;
2938
Garrett Tanzerbb8db412022-09-27 21:59:462939 // Force the navigation to take place in a new browsing instance.
2940 // This is used by _unfencedTop in fenced frames to ensure that navigations
2941 // leaving the fenced context create a new browsing instance.
2942 if (force_new_browsing_instance) {
2943 request->coop_status().ForceBrowsingInstanceSwap();
2944 }
2945
Arthur Hemery948742762019-09-18 10:06:242946 // At this stage we are proceeding with this navigation. If this was renderer
2947 // initiated with user gesture, we need to make sure we clear up potential
2948 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2949 DiscardNonCommittedEntries();
2950
Lukasz Anforowicz9ee83c272020-12-01 20:14:052951 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262952}
2953
[email protected]d1198fd2012-08-13 22:50:192954void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252955 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212956 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192957 if (!session_storage_namespace)
2958 return;
2959
2960 // We can't overwrite an existing SessionStorage without violating spec.
2961 // Attempts to do so may give a tab access to another tab's session storage
2962 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152963 bool successful_insert =
2964 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252965 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052966 static_cast<SessionStorageNamespaceImpl*>(
2967 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302968 .second;
2969 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192970}
2971
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572972bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452973 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032974 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462975}
2976
Aran Gilman37d11632019-10-08 23:07:152977SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252978 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302979 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252980 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032981 DOMStorageContextWrapper* context_wrapper =
2982 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2983
2984 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252985 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032986 if (it != session_storage_namespace_map_.end()) {
2987 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152988 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2989 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472990
michaelnbacbcbd2016-02-09 00:32:032991 return it->second.get();
2992 }
2993
2994 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102995 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2996 SessionStorageNamespaceImpl::Create(context_wrapper);
2997 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2998 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252999 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:103000 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:303001
Daniel Murphy31bbb8b12018-02-07 21:44:103002 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:303003}
3004
3005SessionStorageNamespace*
3006NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:253007 return GetSessionStorageNamespace(
3008 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:303009}
3010
3011const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573012NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303013 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553014}
[email protected]d202a7c2012-01-04 07:53:473015
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573016bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563017 return needs_reload_;
3018}
[email protected]a26023822011-12-29 00:23:553019
[email protected]46bb5e9c2013-10-03 22:16:473020void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413021 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3022}
3023
3024void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473025 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413026 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543027
3028 if (last_committed_entry_index_ != -1) {
3029 entries_[last_committed_entry_index_]->SetTransitionType(
3030 ui::PAGE_TRANSITION_RELOAD);
3031 }
[email protected]46bb5e9c2013-10-03 22:16:473032}
3033
[email protected]d202a7c2012-01-04 07:53:473034void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573035 DCHECK_LT(index, GetEntryCount());
3036 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313037 DiscardNonCommittedEntries();
3038
Nate Chapin9eb16be72022-09-23 22:54:313039 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313040 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123041 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313042 last_committed_entry_index_--;
3043}
3044
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573045NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273046 // If there is no pending_entry_, there should be no pending_entry_index_.
3047 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3048
3049 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363050 // at that index. An exception is while a reload of a post commit error page
3051 // is ongoing; in that case pending entry will point to the entry replaced
3052 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273053 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363054 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3055 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273056
[email protected]022af742011-12-28 18:37:253057 return pending_entry_;
3058}
3059
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573060int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273061 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273062 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553063 return pending_entry_index_;
3064}
3065
avi25764702015-06-23 15:43:373066void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573067 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363068 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313069 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003070 bool in_fenced_frame_tree,
3071 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313072 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3073 // set because:
3074 // 1) They don't influence the history of the outer page.
3075 // 2) They are always replace only navigation (there is always only one entry
3076 // in their history stack).
3077 // 3) Are not top level navigations and appear similar to iframes.
3078 // Navigations of the fenced frame might create a new NavigationEntry, which
3079 // will call this function. Non fenced frame navigations will never have
3080 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3081 // InsertOrReplaceEntry.
3082 DCHECK_EQ(in_fenced_frame_tree,
3083 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3084 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203085
avi5cad4912015-06-19 05:25:443086 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3087 // need to keep continuity with the pending entry, so copy the pending entry's
3088 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3089 // then the renderer navigated on its own, independent of the pending entry,
3090 // so don't copy anything.
3091 if (pending_entry_ && pending_entry_index_ == -1)
3092 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203093
Rakina Zata Amnia4e27222021-12-22 01:05:003094 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203095
creisee17e932015-07-17 17:56:223096 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453097 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103098 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573099 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363100 // If the new entry is a post-commit error page, we store the current last
3101 // committed entry to the side so that we can put it back when navigating
3102 // away from the error.
3103 if (was_post_commit_error) {
3104 DCHECK(!entry_replaced_by_post_commit_error_);
3105 entry_replaced_by_post_commit_error_ =
3106 std::move(entries_[last_committed_entry_index_]);
3107 }
dcheng36b6aec92015-12-26 06:16:363108 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223109 return;
3110 }
[email protected]765b35502008-08-21 00:51:203111
creis37979a62015-08-04 19:48:183112 // We shouldn't see replace == true when there's no committed entries.
3113 DCHECK(!replace);
3114
Michael Thiessen9b14d512019-09-23 21:19:473115 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203116
Shivani Sharmad8c8d652019-02-13 17:27:573117 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203118
dcheng36b6aec92015-12-26 06:16:363119 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203120 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293121}
3122
Shivani Sharmad8c8d652019-02-13 17:27:573123void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163124 if (entries_.size() < max_entry_count())
3125 return;
3126
3127 DCHECK_EQ(max_entry_count(), entries_.size());
3128 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573129 CHECK_EQ(pending_entry_index_, -1);
3130
3131 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423132 // Retrieve the oldest skippable entry.
3133 for (; index < GetEntryCount(); index++) {
3134 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3135 break;
Shivani Sharmad8c8d652019-02-13 17:27:573136 }
3137
3138 // If there is no skippable entry or if it is the last committed entry then
3139 // fall back to pruning the oldest entry. It is not safe to prune the last
3140 // committed entry.
3141 if (index == GetEntryCount() || index == last_committed_entry_index_)
3142 index = 0;
3143
3144 bool should_succeed = RemoveEntryAtIndex(index);
3145 DCHECK_EQ(true, should_succeed);
3146
3147 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253148}
3149
William Liuec04e382024-05-23 18:03:273150base::WeakPtr<NavigationRequest>
3151NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163152 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203153 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373154 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133155 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203156 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503157 TRACE_EVENT0("navigation",
3158 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273159 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023160 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363161 if (pending_entry_index_ != -1) {
3162 // The pending entry may not be in entries_ if a post-commit error page is
3163 // showing.
3164 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3165 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3166 }
Gyuyoung Kim107c2a02021-04-13 01:49:303167 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573168 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013169 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033170 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573171 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133172 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3173 // the same as the top level frame being navigated.
3174 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373175 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133176 }
Arthur Sonzogni620cec62018-12-13 13:08:573177
[email protected]83c2e232011-10-07 21:36:463178 // If we were navigating to a slow-to-commit page, and the user performs
3179 // a session history navigation to the last committed page, RenderViewHost
3180 // will force the throbber to start, but WebKit will essentially ignore the
3181 // navigation, and won't send a message to stop the throbber. To prevent this
3182 // from happening, we drop the navigation here and stop the slow-to-commit
3183 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023184 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083185 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273186 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033187 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123188
[email protected]83c2e232011-10-07 21:36:463189 DiscardNonCommittedEntries();
William Liuec04e382024-05-23 18:03:273190 return nullptr;
[email protected]83c2e232011-10-07 21:36:463191 }
3192
Arthur Sonzognic686e8f2024-01-11 08:36:373193 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333194 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3195 if (initiator_rfh) {
3196 initiator_frame_token = initiator_rfh->GetFrameToken();
3197 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3198 DCHECK(initiator_frame_token);
3199 }
3200
creisce0ef3572017-01-26 17:53:083201 // Compare FrameNavigationEntries to see which frames in the tree need to be
3202 // navigated.
clamy3cb9bea92018-07-10 12:42:023203 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3204 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333205 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3206 initiator_process_id, soft_navigation_heuristics_task_id,
3207 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303208
3209 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573210 // We were unable to match any frames to navigate. This can happen if a
3211 // history navigation targets a subframe that no longer exists
3212 // (https://crbug.com/705550). In this case, we need to update the current
3213 // history entry to the pending one but keep the main document loaded. We
3214 // also need to ensure that observers are informed about the updated
3215 // current history entry (e.g., for greying out back/forward buttons), and
3216 // that renderer processes update their history offsets. The easiest way
3217 // to do all that is to schedule a "redundant" same-document navigation in
3218 // the main frame.
3219 //
3220 // Note that we don't want to remove this history entry, as it might still
3221 // be valid later, since a frame that it's targeting may be recreated.
3222 //
3223 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3224 // need to repeat history navigations until finding the one that works.
3225 // Consider changing this behavior to keep looking for the first valid
3226 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023227 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423228 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573229 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573230 ReloadType::NONE /* reload_type */,
3231 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433232 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333233 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023234 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573235 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023236 DiscardPendingEntry(false);
William Liuec04e382024-05-23 18:03:273237 return nullptr;
clamy3cb9bea92018-07-10 12:42:023238 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573239 same_document_loads.push_back(std::move(navigation_request));
3240
3241 // Sanity check that we never take this branch for any kinds of reloads,
3242 // as those should've queued a different-document load in the main frame.
3243 DCHECK(!is_forced_reload);
3244 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303245 }
3246
Nate Chapinbf682fa32022-09-26 22:41:203247 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163248 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203249 if (initiator_rfh && initiator_rfh->IsSandboxed(
3250 network::mojom::WebSandboxFlags::kTopNavigation)) {
3251 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3252 initiator_rfh, same_document_loads) &&
3253 DoesSandboxNavigationStayWithinSubtree(
3254 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503255 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163256 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203257 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3258 initiator_rfh,
3259 navigates_inside_tree
3260 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3261 : blink::mojom::WebFeature::
3262 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523263
3264 // If the navigation occurred outside the tree discard it because
3265 // the sandboxed frame didn't have permission to navigate outside
3266 // its tree. If it is possible that the navigation is both inside and
3267 // outside the frame tree and we discard it entirely because we don't
3268 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143269 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203270 // If a |navigation_api_key| was provided, this navigation originated from
3271 // the navigation API. Notify the renderer that the navigation was
3272 // cancelled so the navigation API can fire an error event and reject the
3273 // relevant promise.
3274 if (navigation_api_key) {
3275 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3276 *navigation_api_key,
3277 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3278 }
Dave Tapuska855c1e12019-08-23 20:45:523279 DiscardPendingEntry(false);
William Liuec04e382024-05-23 18:03:273280 return nullptr;
Dave Tapuska855c1e12019-08-23 20:45:523281 }
Dave Tapuska8bfd84c2019-03-26 20:47:163282 }
3283
Nate Chapin6c43c022023-02-13 23:32:423284 // If it is possible that this traverse may involve a same-document navigation
3285 // in the initiator and there is a Navigation API key involved, then we may
3286 // need to notify the initiator if it fails. (The early returns above either
3287 // do not involve these cases or already notify the initiator.)
3288 // The event only needs to fire for the initiator, and only if the initiator
3289 // itself is performing a same-document navigation (because the event will not
3290 // fire if it navigates cross-document).
3291 if (navigation_api_key) {
3292 for (auto& item : same_document_loads) {
3293 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3294 item->set_pending_navigation_api_key(*navigation_api_key);
3295 break;
3296 }
3297 }
3298 }
3299
Carlos Caballero539a421c2020-07-06 10:25:573300 // BackForwardCache:
3301 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563302 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573303 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3304 DCHECK_EQ(reload_type, ReloadType::NONE);
3305 auto navigation_request = CreateNavigationRequestFromEntry(
3306 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3307 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333308 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3309 initiator_process_id);
William Liuec04e382024-05-23 18:03:273310 base::WeakPtr<NavigationRequest> request = navigation_request->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053311 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
William Liuec04e382024-05-23 18:03:273312 return (request && request->IsInPrimaryMainFrame()) ? request : nullptr;
Carlos Caballero539a421c2020-07-06 10:25:573313 }
3314
3315 // History navigation might try to reuse a specific BrowsingInstance, already
3316 // used by a page in the cache. To avoid having two different main frames that
3317 // live in the same BrowsingInstance, evict the all pages with this
3318 // BrowsingInstance from the cache.
3319 //
3320 // For example, take the following scenario:
3321 //
3322 // A1 = Some page on a.com
3323 // A2 = Some other page on a.com
3324 // B3 = An uncacheable page on b.com
3325 //
3326 // Then the following navigations occur:
3327 // A1->A2->B3->A1
3328 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3329 // take its place) and A1 will be created in the same BrowsingInstance (and
3330 // SiteInstance), as A2.
3331 //
3332 // If we didn't do anything, both A1 and A2 would remain alive in the same
3333 // BrowsingInstance/SiteInstance, which is unsupported by
3334 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3335 // A2 from the cache.
3336 if (pending_entry_->site_instance()) {
3337 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3338 pending_entry_->site_instance());
3339 }
3340
Rakina Zata Amnid605d462022-06-01 10:17:033341 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3342 pending_entry_ && pending_entry_->IsRestored());
3343 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3344 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3345 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3346 pending_entry_index_);
3347 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3348 last_committed_entry_index_);
3349 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3350 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3351 pending_entry_ && pending_entry_->IsInitialEntry());
3352 SCOPED_CRASH_KEY_BOOL(
3353 "nav_reentrancy", "pending_entry_initial2",
3354 pending_entry_ &&
3355 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3356 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3357 IsInitialNavigation());
3358 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3359 IsInitialBlankNavigation());
3360 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3361 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3362 (int)pending_reload_);
3363
clamy3cb9bea92018-07-10 12:42:023364 // This call does not support re-entrancy. See http://crbug.com/347742.
3365 CHECK(!in_navigate_to_pending_entry_);
3366 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303367
Rakina Zata Amnid605d462022-06-01 10:17:033368 // If the navigation-reentrancy is caused by calling
3369 // NavigateToExistingPendingEntry twice, this will note the previous call's
3370 // pending entry's ID.
3371 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3372 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3373
arthursonzogni66f711c2019-10-08 14:40:363374 // It is not possible to delete the pending NavigationEntry while navigating
3375 // to it. Grab a reference to delay potential deletion until the end of this
3376 // function.
3377 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3378
Nate Chapin154b14b2023-02-17 18:28:163379 // If there is a main-frame same-document history navigation, we may defer
3380 // the subframe history navigations in order to give JS in the main frame the
3381 // opportunity to cancel the entire traverse via the navigate event. In that
3382 // case, we need to stash the main frame request's navigation token on the
3383 // subframes, so they can look up the main frame request and defer themselves
3384 // until it completes.
3385 if (!same_document_loads.empty() &&
3386 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3387 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3388 // The token will only be returned in cases where deferring the navigation
3389 // is necessary.
3390 if (auto main_frame_same_document_token =
3391 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3392 for (auto& item : same_document_loads) {
3393 if (item.get() != main_frame_request) {
3394 item->set_main_frame_same_document_history_token(
3395 main_frame_same_document_token);
3396 }
3397 }
3398 for (auto& item : different_document_loads) {
3399 item->set_main_frame_same_document_history_token(
3400 main_frame_same_document_token);
3401 }
3402 }
3403 }
3404
William Liu122754942024-01-18 22:34:393405 if (!initiator_rfh) {
3406 // A browser-initiated navigation won't have a `initiator_rfh`.
3407 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3408 different_document_loads, same_document_loads);
3409 }
3410
William Liuec04e382024-05-23 18:03:273411 base::WeakPtr<NavigationRequest> primary_main_frame_request;
creis4e2ecb72015-06-20 00:46:303412 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023413 for (auto& item : same_document_loads) {
3414 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273415 // The request could be destroyed before `navigator().Navigate()` returns.
3416 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053417 frame->navigator().Navigate(std::move(item), reload_type);
William Liuec04e382024-05-23 18:03:273418 if (request && request->IsInPrimaryMainFrame()) {
3419 // Only one primary main frame `NavigationRequest` should occur.
3420 CHECK(!primary_main_frame_request);
3421 primary_main_frame_request = request;
3422 }
creis4e2ecb72015-06-20 00:46:303423 }
clamy3cb9bea92018-07-10 12:42:023424 for (auto& item : different_document_loads) {
3425 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273426 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053427 frame->navigator().Navigate(std::move(item), reload_type);
William Liuec04e382024-05-23 18:03:273428 if (request && request->IsInPrimaryMainFrame()) {
3429 // Only one primary main frame `NavigationRequest` should occur.
3430 CHECK(!primary_main_frame_request);
3431 primary_main_frame_request = request;
3432 }
creis4e2ecb72015-06-20 00:46:303433 }
clamy3cb9bea92018-07-10 12:42:023434
3435 in_navigate_to_pending_entry_ = false;
William Liuec04e382024-05-23 18:03:273436
3437 return primary_main_frame_request;
creis4e2ecb72015-06-20 00:46:303438}
3439
Alex Moshchuk3a4e77a2020-05-29 21:32:573440NavigationControllerImpl::HistoryNavigationAction
3441NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303442 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573443 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423444 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583445 // Only active and prerendered documents are allowed to navigate in their
3446 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423447 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013448 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583449 // - If the document is in pending deletion, the browser already committed
3450 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3451 // - If the document is in back-forward cache, it's not allowed to navigate
3452 // as it should remain frozen. Ignore the request and evict the document
3453 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423454 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583455 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423456 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113457 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3458 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423459 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113460 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423461 }
arthursonzogni03f76152019-02-12 10:35:203462
Alex Moshchuk3a4e77a2020-05-29 21:32:573463 // Reloads should result in a different-document load. Note that reloads may
3464 // also happen via the |needs_reload_| mechanism where the reload_type is
3465 // NONE, so detect this by comparing whether we're going to the same
3466 // entry that we're currently on. Similarly to above, only main frames
3467 // should reach this. Note that subframes support reloads, but that's done
3468 // via a different path that doesn't involve FindFramesToNavigate (see
3469 // RenderFrameHost::Reload()).
3470 if (reload_type != ReloadType::NONE ||
3471 pending_entry_index_ == last_committed_entry_index_) {
3472 DCHECK(frame->IsMainFrame());
3473 return HistoryNavigationAction::kDifferentDocument;
3474 }
3475
Alex Moshchuk47d1a4bd2020-06-01 22:15:343476 // If there is no new FrameNavigationEntry for the frame, ignore the
3477 // load. For example, this may happen when going back to an entry before a
3478 // frame was created. Suppose we commit a same-document navigation that also
3479 // results in adding a new subframe somewhere in the tree. If we go back,
3480 // the new subframe will be missing a FrameNavigationEntry in the previous
3481 // NavigationEntry, but we shouldn't delete or change what's loaded in
3482 // it.
3483 //
Alex Moshchuke65c39272020-06-03 17:55:373484 // Note that in this case, there is no need to keep looking for navigations
3485 // in subframes, which would be missing FrameNavigationEntries as well.
3486 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343487 // It's important to check this before checking |old_item| below, since both
3488 // might be null, and in that case we still shouldn't change what's loaded in
3489 // this frame. Note that scheduling any loads assumes that |new_item| is
3490 // non-null. See https://crbug.com/1088354.
3491 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3492 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373493 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343494
Charlie Reisa474fb62022-03-17 02:31:363495 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3496 // which history item it is currently on, since this may be different than the
3497 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3498 // (e.g., if a history navigation is targeting multiple frames and only some
3499 // have committed so far).
creis4e2ecb72015-06-20 00:46:303500 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363501 frame->current_frame_host()->last_committed_frame_entry();
3502 if (!old_item) {
3503 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3504 // fall back to the last committed NavigationEntry's record for this frame.
3505 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583506 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363507 // accurate FrameNavigationEntry and eliminate this case.
3508 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3509 }
3510 // If neither approach finds a FrameNavigationEntry, schedule a
3511 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583512 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573513 if (!old_item)
3514 return HistoryNavigationAction::kDifferentDocument;
3515
Alex Moshchuk3a4e77a2020-05-29 21:32:573516 // If the new item is not in the same SiteInstance, schedule a
3517 // different-document load. Newly restored items may not have a SiteInstance
3518 // yet, in which case it will be assigned on first commit.
3519 if (new_item->site_instance() &&
3520 new_item->site_instance() != old_item->site_instance())
3521 return HistoryNavigationAction::kDifferentDocument;
3522
3523 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313524 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3525 // that we do this even if the history navigation would not be modifying this
3526 // frame were it live.
3527 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573528 return HistoryNavigationAction::kDifferentDocument;
3529
3530 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313531 // Starting a navigation after a crash early-promotes the speculative
3532 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3533 // committed yet, so we can not possibly perform a same-document history
3534 // navigation. The frame would need to be reloaded with a cross-document
3535 // navigation.
3536 if (!frame->current_frame_host()->has_committed_any_navigation())
3537 return HistoryNavigationAction::kDifferentDocument;
3538
creis54131692016-08-12 18:32:253539 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493540 // sequence number but different item sequence number.
3541 if (new_item->document_sequence_number() ==
3542 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573543 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493544 }
avib48cb312016-05-05 21:35:003545
Alex Moshchuk3a4e77a2020-05-29 21:32:573546 // Otherwise, if both item and document sequence numbers differ, this
3547 // should be a different document load.
3548 return HistoryNavigationAction::kDifferentDocument;
3549 }
3550
3551 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373552 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573553 DCHECK_EQ(new_item->document_sequence_number(),
3554 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373555 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573556}
3557
3558void NavigationControllerImpl::FindFramesToNavigate(
3559 FrameTreeNode* frame,
3560 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373561 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333562 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373563 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133564 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573565 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3566 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3567 DCHECK(pending_entry_);
3568 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3569
3570 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3571
3572 if (action == HistoryNavigationAction::kSameDocument) {
3573 std::unique_ptr<NavigationRequest> navigation_request =
3574 CreateNavigationRequestFromEntry(
3575 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133576 /*is_same_document_history_load=*/true,
3577 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333578 initiator_frame_token, initiator_process_id,
3579 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573580 if (navigation_request) {
3581 // Only add the request if was properly created. It's possible for the
3582 // creation to fail in certain cases, e.g. when the URL is invalid.
3583 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303584 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573585 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473586 std::unique_ptr<NavigationRequest> navigation_request =
3587 CreateNavigationRequestFromEntry(
3588 frame, pending_entry_, new_item, reload_type,
3589 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433590 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333591 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473592 if (navigation_request) {
3593 // Only add the request if was properly created. It's possible for the
3594 // creation to fail in certain cases, e.g. when the URL is invalid.
3595 different_document_loads->push_back(std::move(navigation_request));
3596 }
3597 // For a different document, the subframes will be destroyed, so there's
3598 // no need to consider them.
3599 return;
Alex Moshchuke65c39272020-06-03 17:55:373600 } else if (action == HistoryNavigationAction::kStopLooking) {
3601 return;
creis4e2ecb72015-06-20 00:46:303602 }
3603
Yoav Weiss8c573952022-11-17 17:35:133604 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3605 // we currently only support soft navigation heuristics for the top level
3606 // frame.
creis4e2ecb72015-06-20 00:46:303607 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333608 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3609 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373610 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433611 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303612 }
3613}
3614
Harkiran Bolariaba823e42021-05-21 18:30:363615base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243616 const LoadURLParams& params) {
3617 // Find the appropriate FrameTreeNode.
3618 FrameTreeNode* node = nullptr;
3619 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3620 !params.frame_name.empty()) {
3621 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033622 ? frame_tree_->FindByID(params.frame_tree_node_id)
3623 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503624 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243625 }
3626
3627 // If no FrameTreeNode was specified, navigate the main frame.
3628 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033629 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243630
Camille Lamy5193caa2018-10-12 11:59:423631 // Compute overrides to the LoadURLParams for |override_user_agent|,
3632 // |should_replace_current_entry| and |has_user_gesture| that will be used
3633 // both in the creation of the NavigationEntry and the NavigationRequest.
3634 // Ideally, the LoadURLParams themselves would be updated, but since they are
3635 // passed as a const reference, this is not possible.
3636 // TODO(clamy): When we only create a NavigationRequest, move this to
3637 // CreateNavigationRequestFromLoadURLParams.
3638 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3639 GetLastCommittedEntry());
3640
Rakina Zata Amnie2d31312022-11-18 03:38:453641 // An entry replacement must happen if the current browsing context should
3642 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333643 bool should_replace_current_entry =
3644 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453645 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423646
clamy21718cc22018-06-13 13:34:243647 // Javascript URLs should not create NavigationEntries. All other navigations
3648 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243649 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373650 std::unique_ptr<NavigationEntryImpl> entry =
3651 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3652 should_replace_current_entry,
3653 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243654 DiscardPendingEntry(false);
3655 SetPendingEntry(std::move(entry));
3656 }
3657
Tim Judkins59548192023-05-17 17:51:203658 // Renderer-debug URLs are sent to the current renderer process immediately
3659 // for processing and don't need to create a NavigationRequest. Note: this
3660 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243661 // renderer-debug URLs.
3662 // Note: we intentionally leave the pending entry in place for renderer debug
3663 // URLs, unlike the cases below where we clear it if the navigation doesn't
3664 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303665 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483666 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3667 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153668 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203669 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483670 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363671 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483672 }
3673
clamy21718cc22018-06-13 13:34:243674 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363675 return nullptr;
clamy21718cc22018-06-13 13:34:243676 }
3677
Antonio Sartori78a749f2020-11-30 12:03:393678 DCHECK(pending_entry_);
3679
clamy21718cc22018-06-13 13:34:243680 // Convert navigations to the current URL to a reload.
3681 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3682 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3683 // DevTools sometimes issues navigations to main frames that they do not
3684 // expect to see treated as reload, and it only works because they pass a
3685 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3686 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543687 ReloadType reload_type = params.reload_type;
3688 if (reload_type == ReloadType::NONE &&
3689 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043690 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243691 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243692 params.load_type ==
3693 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543694 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243695 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473696 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393697
3698 // If this is a reload of an existing FrameNavigationEntry and we had a
3699 // policy container for it, then we should copy it into the pending entry,
3700 // so that it is copied to the navigation request in
3701 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453702 FrameNavigationEntry* previous_frame_entry =
3703 GetLastCommittedEntry()->GetFrameEntry(node);
3704 if (previous_frame_entry &&
3705 previous_frame_entry->policy_container_policies()) {
3706 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3707 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393708 }
3709 }
3710
3711 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173712 // document, then we should copy the document polices from RenderFrameHost's
3713 // PolicyContainerHost. The NavigationRequest will create a new
3714 // PolicyContainerHost with the document policies from the |pending_entry_|,
3715 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3716 // the navigation. This way, we ensure that we keep enforcing the right
3717 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453718 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393719 if (node->current_frame_host() &&
3720 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193721 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163722 node->current_frame_host()
3723 ->policy_container_host()
3724 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233725 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393726 }
clamy21718cc22018-06-13 13:34:243727 }
3728
3729 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263730 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243731
Tsuyoshi Horo167ca6432022-03-09 05:16:393732 // This will be used to set the Navigation Timing API navigationStart
3733 // parameter for browser navigations in new tabs (intents, tabs opened through
3734 // "Open link in new tab"). If the navigation must wait on the current
3735 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3736 // will be updated when the BeforeUnload ack is received.
3737 const auto navigation_start_time = base::TimeTicks::Now();
3738
Camille Lamy5193caa2018-10-12 11:59:423739 std::unique_ptr<NavigationRequest> request =
3740 CreateNavigationRequestFromLoadParams(
3741 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143742 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393743 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3744 navigation_start_time);
clamy21718cc22018-06-13 13:34:243745
3746 // If the navigation couldn't start, return immediately and discard the
3747 // pending NavigationEntry.
3748 if (!request) {
3749 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363750 return nullptr;
clamy21718cc22018-06-13 13:34:243751 }
3752
Camille Lamy5193caa2018-10-12 11:59:423753#if DCHECK_IS_ON()
3754 // Safety check that NavigationRequest and NavigationEntry match.
3755 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3756#endif
3757
clamy21718cc22018-06-13 13:34:243758 // This call does not support re-entrancy. See http://crbug.com/347742.
3759 CHECK(!in_navigate_to_pending_entry_);
3760 in_navigate_to_pending_entry_ = true;
3761
arthursonzogni66f711c2019-10-08 14:40:363762 // It is not possible to delete the pending NavigationEntry while navigating
3763 // to it. Grab a reference to delay potential deletion until the end of this
3764 // function.
3765 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3766
Harkiran Bolariaba823e42021-05-21 18:30:363767 base::WeakPtr<NavigationHandle> created_navigation_handle(
3768 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053769 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243770
3771 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363772 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243773}
3774
clamyea99ea12018-05-28 13:54:233775void NavigationControllerImpl::HandleRendererDebugURL(
3776 FrameTreeNode* frame_tree_node,
3777 const GURL& url) {
3778 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243779 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3780 // the renderer process is not live, unless it is the initial navigation
3781 // of the tab.
clamyea99ea12018-05-28 13:54:233782 if (!IsInitialNavigation()) {
3783 DiscardNonCommittedEntries();
3784 return;
3785 }
Fergal Dalyecd3b0202020-06-25 01:57:373786 // The current frame is always a main frame. If IsInitialNavigation() is
3787 // true then there have been no navigations and any frames of this tab must
3788 // be in the same renderer process. If that has crashed then the only frame
3789 // that can be revived is the main frame.
3790 frame_tree_node->render_manager()
3791 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233792 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223793
3794 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3795 // notification, so set is loading to true here to properly surface it when
3796 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313797 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223798 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223799 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223800 }
clamyea99ea12018-05-28 13:54:233801 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3802}
3803
clamy21718cc22018-06-13 13:34:243804std::unique_ptr<NavigationEntryImpl>
3805NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3806 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423807 const LoadURLParams& params,
3808 bool override_user_agent,
3809 bool should_replace_current_entry,
3810 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393811 // Browser initiated navigations might not have a blob_url_loader_factory set
3812 // in params even if the navigation is to a blob URL. If that happens, lookup
3813 // the correct url loader factory to use here.
3814 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483815 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473816 // Resolve the blob URL in the storage partition associated with the target
3817 // frame. This is the storage partition the URL will be loaded in, and only
3818 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393819 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473820 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393821 }
3822
clamy21718cc22018-06-13 13:34:243823 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443824 // extra_headers in params are \n separated; navigation entries want \r\n.
3825 std::string extra_headers_crlf;
3826 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243827
3828 // For subframes, create a pending entry with a corresponding frame entry.
3829 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453830 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243831 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083832 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243833 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373834 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213835 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3836 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393837 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163838 // a conversion of a new navigation into a reload, we will set the right
3839 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193840 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243841 } else {
3842 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173843 // If `node` is the outermost main frame, it rewrites a virtual url in order
3844 // to adjust the original input url if needed. For inner frames such as
3845 // fenced frames or subframes, they don't rewrite urls as the urls are not
3846 // input urls by users.
3847 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323848 scoped_refptr<SiteInstance> source_site_instance =
3849 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373850 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323851 if (source_site_instance && source_site_instance->HasProcess()) {
3852 source_process_site_url =
3853 source_site_instance->GetProcess()->GetProcessLock().site_url();
3854 }
clamy21718cc22018-06-13 13:34:243855 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063856 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323857 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213858 params.transition_type, params.is_renderer_initiated,
3859 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3860 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243861 entry->set_source_site_instance(
3862 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3863 entry->SetRedirectChain(params.redirect_chain);
3864 }
3865
3866 // Set the FTN ID (only used in non-site-per-process, for tests).
3867 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243868 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423869 entry->SetIsOverridingUserAgent(override_user_agent);
3870 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543871 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243872
clamy21718cc22018-06-13 13:34:243873 switch (params.load_type) {
3874 case LOAD_TYPE_DEFAULT:
3875 break;
3876 case LOAD_TYPE_HTTP_POST:
3877 entry->SetHasPostData(true);
3878 entry->SetPostData(params.post_data);
3879 break;
3880 case LOAD_TYPE_DATA:
3881 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3882 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283883#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243884 entry->SetDataURLAsString(params.data_url_as_string);
3885#endif
3886 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3887 break;
clamy21718cc22018-06-13 13:34:243888 }
3889
3890 // TODO(clamy): NavigationEntry is meant for information that will be kept
3891 // after the navigation ended and therefore is not appropriate for
3892 // started_from_context_menu. Move started_from_context_menu to
3893 // NavigationUIData.
3894 entry->set_started_from_context_menu(params.started_from_context_menu);
3895
3896 return entry;
3897}
3898
clamyea99ea12018-05-28 13:54:233899std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423900NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3901 FrameTreeNode* node,
3902 const LoadURLParams& params,
3903 bool override_user_agent,
3904 bool should_replace_current_entry,
3905 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143906 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423907 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573908 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393909 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223910 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493911 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453912 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583913 bool is_container_initiated,
Arthur Sonzognic686e8f2024-01-11 08:36:373914 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573915 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283916 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533917 // All renderer-initiated navigations must have an initiator_origin.
3918 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513919
Camille Lamy5193caa2018-10-12 11:59:423920 GURL url_to_load;
3921 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323922
Camille Lamy2baa8022018-10-19 16:43:173923 // For main frames, rewrite the URL if necessary and compute the virtual URL
3924 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263925 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423926 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173927 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423928 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423929
Camille Lamy2baa8022018-10-19 16:43:173930 // For DATA loads, override the virtual URL.
3931 if (params.load_type == LOAD_TYPE_DATA)
3932 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423933
Camille Lamy2baa8022018-10-19 16:43:173934 if (virtual_url.is_empty())
3935 virtual_url = url_to_load;
3936
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573937 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283938
Aran Gilman249eb122019-12-02 23:32:463939 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3940 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3941 // return different results, leading to a different URL in the
3942 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3943 // pending NavigationEntry, as we'll only make one call to
3944 // RewriteUrlForNavigation.
3945 VLOG_IF(1, (url_to_load != frame_entry->url()))
3946 << "NavigationRequest and FrameEntry have different URLs: "
3947 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283948
Camille Lamy2baa8022018-10-19 16:43:173949 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423950 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173951 // NavigationRequest.
3952 } else {
3953 url_to_load = params.url;
3954 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243955 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173956 }
Camille Lamy5193caa2018-10-12 11:59:423957
Ehsan Karamad44fc72112019-02-26 18:15:473958 if (node->render_manager()->is_attaching_inner_delegate()) {
3959 // Avoid starting any new navigations since this node is now preparing for
3960 // attaching an inner delegate.
3961 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203962 }
Camille Lamy5193caa2018-10-12 11:59:423963
Alex Moshchuk99242832023-05-22 17:21:443964 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:423965 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:443966 }
Camille Lamy5193caa2018-10-12 11:59:423967
danakjd83d706d2020-11-25 22:11:123968 // Look for a pending commit that is to another document in this
3969 // FrameTreeNode. If one exists, then the last committed URL will not be the
3970 // current URL by the time this navigation commits.
3971 bool has_pending_cross_document_commit =
3972 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213973 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123974
Minggang Wangb9f3fa92021-07-01 15:30:313975 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493976 /*old_url=*/node->current_url(),
3977 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3978 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133979 /*is_same_document_history_load=*/false,
3980 is_embedder_initiated_fenced_frame_navigation,
3981 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423982
3983 // Create the NavigationParams based on |params|.
3984
Hiroki Nakagawa4ed61282021-06-18 05:37:233985 bool is_view_source_mode = entry->IsViewSourceMode();
3986 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293987
Antonio Sartori6984c742021-08-26 08:03:413988 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293989
Hiroki Nakagawa4ed61282021-06-18 05:37:233990 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293991 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253992 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293993
Minggang Wangb9f3fa92021-07-01 15:30:313994 blink::mojom::CommonNavigationParamsPtr common_params =
3995 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213996 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513997 blink::mojom::Referrer::New(params.referrer.url,
3998 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213999 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514000 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:394001 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514002 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144003 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414004 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274005 false /* has_text_fragment_token */,
4006 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4007 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514008 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054009 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424010
Minggang Wangb9f3fa92021-07-01 15:30:314011 blink::mojom::CommitNavigationParamsPtr commit_params =
4012 blink::mojom::CommitNavigationParams::New(
Arthur Sonzognic686e8f2024-01-11 08:36:374013 std::nullopt,
Ari Chivukulac7533522024-05-14 21:52:344014 // The correct storage key will be computed before committing the
4015 // navigation.
4016 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324017 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504018 std::vector<net::RedirectInfo>(), params.post_content_type,
4019 common_params->url, common_params->method,
4020 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:314021 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:134022 entry->GetSubframeUniqueNames(node),
4023 /*intended_as_new_entry=*/true,
4024 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144025 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4026 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134027 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314028 params.should_clear_history_list,
4029 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224030 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134031 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514032 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284033#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134034 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144035#endif
Yoav Weiss8c573952022-11-17 17:35:134036 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:134037 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074038 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134039 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4040 /*origin_agent_cluster=*/false,
4041 /*origin_agent_cluster_left_as_default=*/true,
4042 /*enabled_client_hints=*/
4043 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264044 /*is_cross_site_cross_browsing_context_group=*/false,
4045 /*should_have_sticky_user_activation=*/false,
4046 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134047 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014048 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134049 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584050 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134051 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134052 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284053 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134054 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444055 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424056 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374057 /*view_transition_state=*/std::nullopt,
4058 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054059 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464060 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374061 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054062 /*not_restored_reasons=*/nullptr,
Arthur Hemeryd51484b2023-06-02 15:50:004063 /*load_with_storage_access=*/false,
Arthur Sonzognic686e8f2024-01-11 08:36:374064 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374065 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484066 /*cookie_deprecation_label=*/std::nullopt,
4067 /*visited_link_salt=*/std::nullopt);
Xiaohan Wang7f8052e02022-01-14 18:44:284068#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424069 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564070 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424071 }
4072#endif
4073
Lucas Furukawa Gadania9c45682019-07-31 22:05:144074 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074075 commit_params->navigation_timing->system_entropy_at_navigation_start =
4076 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4077 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424078
Camille Lamy5193caa2018-10-12 11:59:424079 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4080 std::string extra_headers_crlf;
4081 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094082
Alex Moshchuk9321e6a2022-12-07 21:58:314083 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144084 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084085 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094086 params.initiator_frame_token, params.initiator_process_id,
4087 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214088 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294089 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454090 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584091 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094092 navigation_request->set_from_download_cross_origin_redirect(
4093 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554094 navigation_request->set_force_new_browsing_instance(
4095 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094096 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424097}
4098
4099std::unique_ptr<NavigationRequest>
4100NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234101 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574102 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234103 FrameNavigationEntry* frame_entry,
4104 ReloadType reload_type,
4105 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434106 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374107 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334108 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374109 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134110 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344111 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234112 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434113 // We should never navigate to an existing initial NavigationEntry that is the
4114 // initial NavigationEntry for the initial empty document that hasn't been
4115 // overridden by the synchronous about:blank commit, to preserve previous
4116 // behavior where trying to reload when the main frame is on the initial empty
4117 // document won't result in a navigation.
4118 // See also https://crbug.com/1277414.
4119 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324120
clamyea99ea12018-05-28 13:54:234121 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234122
Ehsan Karamad44fc72112019-02-26 18:15:474123 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4124 // Avoid starting any new navigations since this node is now preparing for
4125 // attaching an inner delegate.
4126 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204127 }
4128
Alex Moshchuk99242832023-05-22 17:21:444129 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4130 dest_url)) {
clamyea99ea12018-05-28 13:54:234131 return nullptr;
4132 }
4133
clamyea99ea12018-05-28 13:54:234134 // This will be used to set the Navigation Timing API navigationStart
4135 // parameter for browser navigations in new tabs (intents, tabs opened through
4136 // "Open link in new tab"). If the navigation must wait on the current
4137 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4138 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074139
clamyea99ea12018-05-28 13:54:234140 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074141 const auto navigation_start_system_entropy =
4142 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4143 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234144
danakjd83d706d2020-11-25 22:11:124145 // Look for a pending commit that is to another document in this
4146 // FrameTreeNode. If one exists, then the last committed URL will not be the
4147 // current URL by the time this navigation commits.
4148 bool has_pending_cross_document_commit =
4149 frame_tree_node->render_manager()
4150 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494151 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214152 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124153
Minggang Wangb9f3fa92021-07-01 15:30:314154 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124155 /*old_url=*/frame_tree_node->current_url(),
4156 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494157 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494158 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134159 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494160 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424161
4162 // A form submission may happen here if the navigation is a
4163 // back/forward/reload navigation that does a form resubmission.
4164 scoped_refptr<network::ResourceRequestBody> request_body;
4165 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394166 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504167 // entry. This way, it could be directly retrieved here. Right now, it is only
4168 // partially recovered when request.method == "POST" and request.body exists.
4169 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424170 if (frame_entry->method() == "POST") {
4171 request_body = frame_entry->GetPostData(&post_content_type);
4172 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304173 post_content_type = std::string(
4174 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504175 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424176 }
4177
4178 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314179 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514180 entry->ConstructCommonNavigationParams(
4181 *frame_entry, request_body, dest_url,
4182 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384183 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534184 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514185 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554186 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424187
4188 // TODO(clamy): |intended_as_new_entry| below should always be false once
4189 // Reload no longer leads to this being called for a pending NavigationEntry
4190 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314191 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144192 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404193 *frame_entry, common_params->url, common_params->method,
4194 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144195 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534196 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484197 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134198 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074199 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144200 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074201 commit_params->navigation_timing->system_entropy_at_navigation_start =
4202 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4203 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424204
W. James MacLeanb7d6092682022-10-05 15:23:264205 if (common_params->url.IsAboutSrcdoc()) {
4206 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4207 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594208 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264209 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334210 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314211 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144212 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434213 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334214 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4215 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374216 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294217 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4218 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474219 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234220}
4221
[email protected]d202a7c2012-01-04 07:53:474222void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214223 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274224 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404225
Takashi Toyoshimaea534ef22021-07-21 03:27:594226 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404227 // location bar will have up-to-date information about the security style
4228 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134229 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404230
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374231 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574232 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294233}
4234
initial.commit09911bf2008-07-26 23:55:294235// static
[email protected]d202a7c2012-01-04 07:53:474236size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234237 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154238 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214239 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234240}
4241
[email protected]d202a7c2012-01-04 07:53:474242void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224243 if (is_active && needs_reload_)
4244 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294245}
4246
[email protected]d202a7c2012-01-04 07:53:474247void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034248 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4249 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294250 if (!needs_reload_)
4251 return;
4252
Bo Liucdfa4b12018-11-06 00:21:444253 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4254 needs_reload_type_);
4255
initial.commit09911bf2008-07-26 23:55:294256 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004257 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294258 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004259 if (entry_replaced_by_post_commit_error_) {
4260 // If the current entry is a post commit error, we reload the entry it
4261 // replaced instead. We leave the error entry in place until a commit
4262 // replaces it, but the pending entry points to the original entry in the
4263 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4264 // case that pending_entry_ != entries_[pending_entry_index_].
4265 // Note that this handling is similar to
4266 // `NavigationControllerImpl::Reload()`.
4267 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4268 pending_entry_index_ = GetCurrentEntryIndex();
4269 NavigateToExistingPendingEntry(
4270 ReloadType::NONE,
4271 /*initiator_rfh=*/nullptr,
4272 /*soft_navigation_heuristics_task_id=*/std::nullopt,
4273 /*navigation_api_key=*/nullptr);
4274 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134275 NavigateToExistingPendingEntry(
4276 ReloadType::NONE,
4277 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374278 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134279 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454280 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434281 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274282 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344283 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134284 NavigateToExistingPendingEntry(
4285 ReloadType::NONE,
4286 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374287 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134288 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344289 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434290 // We should never navigate to an existing initial NavigationEntry that is
4291 // the initial NavigationEntry for the initial empty document that hasn't
4292 // been overridden by the synchronous about:blank commit, to preserve
4293 // legacy behavior where trying to reload when the main frame is on the
4294 // initial empty document won't result in a navigation. See also
4295 // https://crbug.com/1277414. If there is something to reload, the
4296 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4297 // it here.
avicc872d7242015-08-19 21:26:344298 needs_reload_ = false;
4299 }
initial.commit09911bf2008-07-26 23:55:294300}
4301
Kevin McNeeccca6172021-10-19 17:11:144302base::WeakPtr<NavigationHandle>
4303NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364304 RenderFrameHost* render_frame_host,
4305 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364306 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134307 RenderFrameHostImpl* rfhi =
4308 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584309
4310 // Only active documents can load post-commit error pages:
4311 // - If the document is in pending deletion, the browser already committed to
4312 // destroying this RenderFrameHost so ignore loading the error page.
4313 // - If the document is in back-forward cache, it's not allowed to navigate as
4314 // it should remain frozen. Ignore the request and evict the document from
4315 // back-forward cache.
4316 // - If the document is prerendering, it can navigate but when loading error
4317 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114318 if (rfhi->IsInactiveAndDisallowActivation(
4319 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144320 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114321 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584322
Rakina Zata Amni919b7922020-12-11 09:03:134323 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414324
Minggang Wangb9f3fa92021-07-01 15:30:314325 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434326 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594327 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4328 // the frame actually committed (e.g. iframe with "src" set to a
4329 // slow-responding URL). We should rewrite the URL to about:blank in this
4330 // case, as the renderer will only think a page is an error page if it has a
4331 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134332 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314333 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434334 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334335 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414336
Mike Jacksone2aa7af2023-05-17 06:45:074337 commit_params->navigation_timing->system_entropy_at_navigation_start =
4338 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4339 node, blink::mojom::SystemEntropy::kNormal);
4340
arthursonzogni70ac7302020-05-28 08:49:054341 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4342 // error pages.
Liam Brady34639ec92023-10-13 19:50:454343 commit_params->frame_policy = node->pending_frame_policy();
arthursonzogni70ac7302020-05-28 08:49:054344
John Delaney131ad362019-08-08 21:57:414345 std::unique_ptr<NavigationRequest> navigation_request =
4346 NavigationRequest::CreateBrowserInitiated(
4347 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094348 false /* was_opener_suppressed */, "" /* extra_headers */,
4349 nullptr /* frame_entry */, nullptr /* entry */,
4350 false /* is_form_submission */, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374351 std::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364352 navigation_request->set_post_commit_error_page_html(error_page_html);
Lei Zhanga4770832023-07-19 18:02:364353 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
Charlie Reis09952ee2022-12-08 16:35:074354 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414355 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144356
4357 // Calling BeginNavigation may destroy the NavigationRequest.
4358 base::WeakPtr<NavigationRequest> created_navigation_request(
4359 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414360 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144361 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414362}
4363
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574364void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214365 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094366 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154367 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144368 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294369}
4370
[email protected]d202a7c2012-01-04 07:53:474371void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364372 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584373 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474374 // represent a no-committed-entry state.
4375 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364376 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584377 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474378 // if `entries_` contains pre-existing entries from the NavigationController
4379 // before restore, which would not be removed and will be at the front of the
4380 // entries list, causing the index to be off by the amount of pre-existing
4381 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294382 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294383}
[email protected]765b35502008-08-21 00:51:204384
arthursonzogni69a6a1b2019-09-17 09:23:004385void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004386 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4387}
4388
4389void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4390 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474391 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104392 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4393 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294394 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474395 return;
Michael Thiessenc5676d22019-09-25 22:32:104396 }
avi45a72532015-04-07 21:01:454397 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314398
4399 if (!delegate_)
4400 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374401 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484402}
4403
avi7c6f35e2015-05-08 17:52:384404int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4405 int nav_entry_id) const {
4406 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4407 if (entries_[i]->GetUniqueID() == nav_entry_id)
4408 return i;
4409 }
4410 return -1;
4411}
4412
[email protected]d202a7c2012-01-04 07:53:474413void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574414 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254415 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574416 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594417 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254418 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374419 // Normally, cloning a NavigationEntryImpl results in sharing
4420 // FrameNavigationEntries between the original and the clone. However, when
4421 // cloning from a different NavigationControllerImpl, we want to fork the
4422 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374423 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594424 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254425 }
Rakina Zata Amnie2d31312022-11-18 03:38:454426 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274427 DCHECK(pending_entry_index_ == -1 ||
4428 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254429}
[email protected]c5b88d82012-10-06 17:03:334430
4431void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184432 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334433 get_timestamp_callback_ = get_timestamp_callback;
4434}
[email protected]8ff00d72012-10-23 19:12:214435
Shivani Sharmaffb32b82019-04-09 16:58:474436// History manipulation intervention:
4437void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474438 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564439 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404440 bool is_renderer_initiated,
4441 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564442 // Note that for a subframe,
4443 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454444 // gesture happened in any subframe (propagated to main frame) or in the main
4445 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564446 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274447 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474448 return;
4449 }
4450 if (last_committed_entry_index_ == -1)
4451 return;
4452
Shivani Sharmac4cc8922019-04-18 03:11:174453 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474454
Alexander Timine3ec4192020-04-20 16:39:404455 // Log UKM with the URL we are navigating away from.
4456 ukm::builders::HistoryManipulationIntervention(
4457 previous_page_load_ukm_source_id)
4458 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474459}
4460
Shivani Sharmac4cc8922019-04-18 03:11:174461void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4462 int reference_index,
4463 bool skippable) {
4464 auto* reference_entry = GetEntryAtIndex(reference_index);
4465 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4466
4467 int64_t document_sequence_number =
4468 reference_entry->root_node()->frame_entry->document_sequence_number();
4469 for (int index = 0; index < GetEntryCount(); index++) {
4470 auto* entry = GetEntryAtIndex(index);
4471 if (entry->root_node()->frame_entry->document_sequence_number() ==
4472 document_sequence_number) {
4473 entry->set_should_skip_on_back_forward_ui(skippable);
4474 }
4475 }
4476}
4477
arthursonzogni66f711c2019-10-08 14:40:364478std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4479NavigationControllerImpl::ReferencePendingEntry() {
4480 DCHECK(pending_entry_);
4481 auto pending_entry_ref =
4482 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4483 pending_entry_refs_.insert(pending_entry_ref.get());
4484 return pending_entry_ref;
4485}
4486
4487void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4488 // Ignore refs that don't correspond to the current pending entry.
4489 auto it = pending_entry_refs_.find(ref);
4490 if (it == pending_entry_refs_.end())
4491 return;
4492 pending_entry_refs_.erase(it);
4493
4494 if (!pending_entry_refs_.empty())
4495 return;
4496
4497 // The pending entry may be deleted before the last PendingEntryRef.
4498 if (!pending_entry_)
4499 return;
4500
4501 // We usually clear the pending entry when the matching NavigationRequest
4502 // fails, so that an arbitrary URL isn't left visible above a committed page.
4503 //
4504 // However, we do preserve the pending entry in some cases, such as on the
4505 // initial navigation of an unmodified blank tab. We also allow the delegate
4506 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4507 // user edit the URL and try again. This may be useful in cases that the
4508 // committed page cannot be attacker-controlled. In these cases, we still
4509 // allow the view to clear the pending entry and typed URL if the user
4510 // requests (e.g., hitting Escape with focus in the address bar).
4511 //
4512 // Do not leave the pending entry visible if it has an invalid URL, since this
4513 // might be formatted in an unexpected or unsafe way.
4514 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364515 bool should_preserve_entry =
4516 (pending_entry_ == GetVisibleEntry()) &&
4517 pending_entry_->GetURL().is_valid() &&
4518 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4519 if (should_preserve_entry)
4520 return;
4521
4522 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374523 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364524}
4525
Titouan Rigoudy6ec70402021-02-02 15:42:194526std::unique_ptr<PolicyContainerPolicies>
4527NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394528 RenderFrameHostImpl* rfh,
4529 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174530 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394531 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454532 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394533 FrameNavigationEntry* previous_frame_entry =
4534 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4535
Alison Gale770f3fc2024-04-27 00:39:584536 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394537 // ensure we always have a FrameNavigationEntry here.
4538 if (!previous_frame_entry)
4539 return nullptr;
4540
Titouan Rigoudy6ec70402021-02-02 15:42:194541 const PolicyContainerPolicies* previous_policies =
4542 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394543
Titouan Rigoudy6ec70402021-02-02 15:42:194544 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394545 return nullptr;
4546
4547 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234548 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394549 }
4550
Titouan Rigoudy72f892d2022-05-02 18:21:234551 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394552}
4553
Hayato Ito2c8c08d02021-06-23 03:38:434554void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504555 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434556 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4557 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4558 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504559
4560 auto callback = base::BindRepeating(
4561 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4562 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4563 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4564 }
4565 },
Hayato Ito2c8c08d02021-06-23 03:38:434566 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034567 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504568}
4569
4570void NavigationControllerImpl::DidAccessInitialMainDocument() {
4571 // We may have left a failed browser-initiated navigation in the address bar
4572 // to let the user edit it and try again. Clear it now that content might
4573 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034574 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504575 DiscardPendingEntry(false);
4576
4577 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374578 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504579}
4580
4581void NavigationControllerImpl::UpdateStateForFrame(
4582 RenderFrameHostImpl* rfhi,
4583 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564584 OPTIONAL_TRACE_EVENT1("content",
4585 "NavigationControllerImpl::UpdateStateForFrame",
4586 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504587 // The state update affects the last NavigationEntry associated with the given
4588 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4589 // in the case of an UpdateState from a frame being swapped out). We track
4590 // which entry this is in the RenderFrameHost's nav_entry_id.
4591 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4592 if (!entry)
4593 return;
4594
4595 FrameNavigationEntry* frame_entry =
4596 entry->GetFrameEntry(rfhi->frame_tree_node());
4597 if (!frame_entry)
4598 return;
4599
4600 // The SiteInstance might not match if we do a cross-process navigation with
4601 // replacement (e.g., auto-subframe), in which case the swap out of the old
4602 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4603 // has already been replaced and destroyed.
4604 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4605 return;
4606
4607 if (page_state == frame_entry->page_state())
4608 return; // Nothing to update.
4609
4610 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4611
4612 // The document_sequence_number and item_sequence_number recorded in the
4613 // FrameNavigationEntry should not differ from the one coming with the update,
4614 // since it must come from the same document. Do not update it if a difference
4615 // is detected, as this indicates that |frame_entry| is not the correct one.
4616 blink::ExplodedPageState exploded_state;
4617 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4618 return;
4619
4620 if (exploded_state.top.document_sequence_number !=
4621 frame_entry->document_sequence_number() ||
4622 exploded_state.top.item_sequence_number !=
4623 frame_entry->item_sequence_number()) {
4624 return;
4625 }
4626
4627 frame_entry->SetPageState(page_state);
4628 NotifyEntryChanged(entry);
4629}
4630
Nate Chapina2c881f52023-11-07 17:02:094631namespace {
4632
4633// The caller is responsible for ensuring the entry is same-origin to the
4634// origin to be committed.
4635blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4636 FrameNavigationEntry* frame_entry,
4637 int64_t pending_document_sequence_number) {
4638 blink::ExplodedPageState exploded_state;
4639 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4640 &exploded_state)) {
4641 return nullptr;
4642 }
4643 blink::ExplodedFrameState frame_state = exploded_state.top;
4644
4645 // If the document represented by this FNE hid its full url from appearing in
4646 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4647 // in the navigation API as well (unless we're navigating to that document).
4648 std::u16string url;
4649 if (pending_document_sequence_number ==
4650 frame_entry->document_sequence_number() ||
4651 !frame_entry->protect_url_in_navigation_api()) {
4652 url = frame_state.url_string.value_or(std::u16string());
4653 }
4654
4655 return blink::mojom::NavigationApiHistoryEntry::New(
4656 frame_state.navigation_api_key.value_or(std::u16string()),
4657 frame_state.navigation_api_id.value_or(std::u16string()), url,
4658 frame_state.item_sequence_number, frame_state.document_sequence_number,
4659 frame_state.navigation_api_state);
4660}
4661
4662} // namespace
4663
Domenic Denicolacd30f5f82022-03-16 21:48:014664std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4665NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574666 Direction direction,
4667 int entry_index,
4668 const url::Origin& pending_origin,
4669 FrameTreeNode* node,
4670 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304671 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094672 int64_t pending_document_sequence_number,
4673 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014674 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454675 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174676 // Don't process the initial entry.
4677 DCHECK_EQ(GetEntryCount(), 1);
4678 return entries;
4679 }
Nate Chapind1fe3612021-04-16 20:45:574680 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304681 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574682 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4683 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094684 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574685 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414686 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574687 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014688 // An entry should only appear in the navigation API entries if it is for
4689 // the same origin as the document being committed. Check the committed
4690 // origin, or if that is not available (during restore), check against the
4691 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584692 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094693 // once we can be sure that entries with the same ISN will never be
4694 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414695 url::Origin frame_entry_origin =
4696 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4697 frame_entry->url(),
4698 frame_entry->initiator_origin().value_or(url::Origin())));
4699 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574700 break;
4701 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4702 continue;
Nate Chapina2c881f52023-11-07 17:02:094703 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4704 ToNavigationApiHistoryEntry(frame_entry,
4705 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304706 DCHECK(entry->url.empty() ||
4707 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574708 entries.push_back(std::move(entry));
4709 previous_item_sequence_number = frame_entry->item_sequence_number();
4710 }
4711 }
4712 // If |entries| was constructed by iterating backwards from
4713 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4714 // earliest-at-the-front. Reverse it.
4715 if (direction == Direction::kBack)
4716 std::reverse(entries.begin(), entries.end());
4717 return entries;
4718}
4719
Domenic Denicolacd30f5f82022-03-16 21:48:014720blink::mojom::NavigationApiHistoryEntryArraysPtr
4721NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554722 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574723 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404724 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444725 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404726 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574727
Nate Chapind1fe3612021-04-16 20:45:574728 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554729 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574730
Nate Chapine82339d02022-05-03 23:48:254731 // NOTE: |entry_index| is the index where this entry will commit if no
4732 // modifications are made between now and DidCommitNavigation. This is used to
4733 // walk |entries_| and determine which entries should be exposed by the
4734 // navigation API. It is important to calculate this correctly, because blink
4735 // will cancel a same-document history commit if it's not present in the
4736 // entries blink knows about.
4737 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574738 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304739 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254740 bool will_create_new_entry = false;
4741 if (GetPendingEntryIndex() != -1) {
4742 entry_index = GetPendingEntryIndex();
4743 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4744 pending_item_sequence_number = frame_entry->item_sequence_number();
4745 pending_document_sequence_number =
4746 frame_entry->document_sequence_number();
4747 }
4748 } else if (request &&
4749 !NavigationTypeUtils::IsReload(
4750 request->common_params().navigation_type) &&
4751 !NavigationTypeUtils::IsHistory(
4752 request->common_params().navigation_type) &&
4753 !request->common_params().should_replace_current_entry &&
4754 !request->common_params()
4755 .is_history_navigation_in_new_child_frame) {
4756 will_create_new_entry = true;
4757 entry_index = GetLastCommittedEntryIndex() + 1;
4758 // Don't set pending_item_sequence_number or
4759 // pending_document_sequence_number in this case - a new unique isn/dsn will
4760 // be calculated in the renderer later.
4761 } else if (GetLastCommittedEntryIndex() != -1) {
4762 entry_index = GetLastCommittedEntryIndex();
4763 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574764 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304765 pending_document_sequence_number =
4766 frame_entry->document_sequence_number();
4767 }
Nate Chapind1fe3612021-04-16 20:45:574768 }
4769
Domenic Denicolacd30f5f82022-03-16 21:48:014770 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254771 if (entry_index == -1) {
4772 // TODO(rakina): Exit early when there is no last committed entry.
4773 // Remove when InitialNavigationEntry ships.
4774 return entry_arrays;
4775 }
4776
Nate Chapina2c881f52023-11-07 17:02:094777 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014778 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574779 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094780 pending_item_sequence_number, pending_document_sequence_number,
4781 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574782
4783 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094784 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574785 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014786 entry_arrays->forward_entries =
4787 PopulateSingleNavigationApiHistoryEntryVector(
4788 Direction::kForward, entry_index, pending_origin, node,
4789 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094790 pending_document_sequence_number, forwardmost_index);
4791 }
4792
4793 // If the previous entry is within the block of contiguous entries being
4794 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254795 FrameNavigationEntry* previous_entry = nullptr;
4796 if (frame_tree_->is_prerendering()) {
4797 int initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4798 .initiator_frame_tree_node_id();
4799 if (initiator_id != RenderFrameHost::kNoFrameTreeNodeId) {
4800 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4801 previous_entry = initiator_node->frame_tree()
4802 .controller()
4803 .GetLastCommittedEntry()
4804 ->GetFrameEntry(initiator_node);
4805 }
4806 } else if (GetLastCommittedEntryIndex() != -1 &&
4807 GetLastCommittedEntryIndex() >= backmost_index &&
4808 GetLastCommittedEntryIndex() <= forwardmost_index) {
4809 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4810 }
4811 if (previous_entry) {
4812 url::Origin previous_entry_origin =
4813 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4814 previous_entry->url(),
4815 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:584816 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:254817 // once we can be sure that entries with the same ISN will never be
4818 // cross-origin.
4819 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4820 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4821 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094822 }
Nate Chapind1fe3612021-04-16 20:45:574823 }
Nate Chapinc06cf80a2023-11-18 01:12:254824
Nate Chapin4e657a472022-02-06 03:38:374825 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574826}
4827
Nate Chapinfbfe5af2021-06-10 17:22:084828NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574829NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084830 FrameNavigationEntry* current_entry,
4831 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574832 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084833 if (!target_entry || !target_entry->committed_origin())
4834 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084835 if (!current_entry->committed_origin()->IsSameOriginWith(
4836 *target_entry->committed_origin())) {
4837 return HistoryNavigationAction::kStopLooking;
4838 }
4839
4840 // NOTE: We don't actually care between kSameDocument and
4841 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574842 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084843 return HistoryNavigationAction::kDifferentDocument;
4844 return HistoryNavigationAction::kKeepLooking;
4845}
4846
Domenic Denicolacc094fb2022-03-16 23:40:574847void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204848 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374849 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144850 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574851 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204852 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084853 FrameNavigationEntry* current_entry =
4854 GetLastCommittedEntry()->GetFrameEntry(node);
4855 if (!current_entry)
4856 return;
4857
Alison Gale47d1537d2024-04-19 21:31:464858 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:134859 // when `navigation.traverseTo()` is called.
4860
Nate Chapinfbfe5af2021-06-10 17:22:084861 // We want to find the nearest matching entry that is contiguously
4862 // same-instance and same-origin. Check back first, then forward.
4863 // TODO(japhet): Link spec here once it exists.
4864 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574865 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084866 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4867 if (result == HistoryNavigationAction::kStopLooking)
4868 break;
4869 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144870 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084871 return;
4872 }
4873 }
4874 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574875 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084876 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4877 if (result == HistoryNavigationAction::kStopLooking)
4878 break;
4879 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144880 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084881 return;
4882 }
4883 }
Nate Chapinbf682fa32022-09-26 22:41:204884
4885 // If we fall through to here, a matching NavigationEntry couldn't be found.
4886 // Notify the renderer that the navigation was cancelled.
4887 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4888 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084889}
4890
Domenic Denicolacc094fb2022-03-16 23:40:574891bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304892 network::mojom::ReferrerPolicy referrer_policy) {
4893 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4894 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4895}
4896
shivanigithubf405bf0d2021-11-05 17:58:334897bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4898 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:314899 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:334900 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544901 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:464902 // The preview mode appears as prerendered page in renderers, and
4903 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:034904 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:514905 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:334906 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544907}
4908
Julie Jeongeun Kim0e242242022-11-30 10:45:094909void NavigationControllerImpl::DidChangeReferrerPolicy(
4910 FrameTreeNode* node,
4911 network::mojom::ReferrerPolicy referrer_policy) {
4912 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4913 if (!entry)
4914 return;
4915
4916 // The FrameNavigationEntry may want to change whether to protect its url
4917 // in the navigation API when the referrer policy changes.
4918 entry->set_protect_url_in_navigation_api(
4919 ShouldProtectUrlInNavigationApi(referrer_policy));
4920}
4921
[email protected]8ff00d72012-10-23 19:12:214922} // namespace content