blob: 8ddb973f78adb9d7d09689fcea7012924268eed0 [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"
Rakina Zata Amni84a859df2024-06-07 15:56:3283#include "content/common/content_navigation_policy.h"
Nate Chapind1fe3612021-04-16 20:45:5784#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5185#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1186#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1987#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1188#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4689#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0090#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4791#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5892#include "content/public/browser/render_widget_host.h"
93#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1094#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3495#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1996#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3897#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1098#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4799#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43100#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59101#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36102#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57103#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18104#include "services/metrics/public/cpp/ukm_builders.h"
105#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17106#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37107#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44108#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58109#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39110#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30111#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21112#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06113#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43114#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50115#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31116#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51117#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46118#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26119#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29120
[email protected]8ff00d72012-10-23 19:12:21121namespace content {
[email protected]e9ba4472008-09-14 15:42:43122namespace {
123
124// Invoked when entries have been pruned, or removed. For example, if the
125// current entries are [google, digg, yahoo], with the current entry google,
126// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47127void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50128 int index,
[email protected]c12bf1a12008-09-17 16:28:49129 int count) {
[email protected]8ff00d72012-10-23 19:12:21130 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50131 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49132 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14133 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43134}
135
[email protected]e9ba4472008-09-14 15:42:43136// Configure all the NavigationEntries in entries for restore. This resets
137// the transition type to reload and makes sure the content state isn't empty.
138void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57139 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48140 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47141 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43142 // Use a transition type of reload so that we don't incorrectly increase
143 // the typed count.
Lei Zhang96031532019-10-10 19:05:47144 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
145 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43146 }
147}
148
[email protected]bf70edce2012-06-20 22:32:22149// Determines whether or not we should be carrying over a user agent override
150// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57151bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22152 return last_entry && last_entry->GetIsOverridingUserAgent();
153}
154
Camille Lamy5193caa2018-10-12 11:59:42155// Determines whether to override user agent for a navigation.
156bool ShouldOverrideUserAgent(
157 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57158 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42159 switch (override_user_agent) {
160 case NavigationController::UA_OVERRIDE_INHERIT:
161 return ShouldKeepOverride(last_committed_entry);
162 case NavigationController::UA_OVERRIDE_TRUE:
163 return true;
164 case NavigationController::UA_OVERRIDE_FALSE:
165 return false;
Camille Lamy5193caa2018-10-12 11:59:42166 }
Peter Boström8472105d2024-05-15 04:36:02167 NOTREACHED_IN_MIGRATION();
Camille Lamy5193caa2018-10-12 11:59:42168 return false;
169}
170
Rakina Zata Amni312822d72021-06-04 16:13:37171// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28172// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37173// link which results in a navigation to the last committed URL (but wasn't
174// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04175// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
176// |base_url_for_data_url|, |transition_type| correspond to the new navigation
177// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
178// navigation that committed.
179bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
180 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57181 const GURL& virtual_url,
182 const GURL& base_url_for_data_url,
183 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57184 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37185 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57186 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37187 // Navigations intended to do a replacement shouldn't be converted to do a
188 // reload.
189 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28190 return false;
clamy0a656e42018-02-06 18:18:28191 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45192 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55193 return false;
194
arthursonzogni7a8243682017-12-14 16:41:42195 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28196 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42197 return false;
198
ananta3bdd8ae2016-12-22 17:11:55199 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
200 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
201 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28202 bool transition_type_can_be_converted = false;
203 if (ui::PageTransitionCoreTypeIs(transition_type,
204 ui::PAGE_TRANSITION_RELOAD) &&
205 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
206 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55207 }
clamy0a656e42018-02-06 18:18:28208 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55209 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28210 transition_type_can_be_converted = true;
211 }
212 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
213 transition_type_can_be_converted = true;
214 if (!transition_type_can_be_converted)
215 return false;
216
217 // This check is required for cases like view-source:, etc. Here the URL of
218 // the navigation entry would contain the url of the page, while the virtual
219 // URL contains the full URL including the view-source prefix.
220 if (virtual_url != last_committed_entry->GetVirtualURL())
221 return false;
222
Fergal Daly766177d2020-07-07 07:54:04223 // Check that the URLs match.
224 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
225 // If there's no frame entry then by definition the URLs don't match.
226 if (!frame_entry)
227 return false;
228
229 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28230 return false;
231
232 // This check is required for Android WebView loadDataWithBaseURL. Apps
233 // can pass in anything in the base URL and we need to ensure that these
234 // match before classifying it as a reload.
235 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
236 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
237 return false;
ananta3bdd8ae2016-12-22 17:11:55238 }
239
clamy0a656e42018-02-06 18:18:28240 // Skip entries with SSL errors.
241 if (last_committed_entry->ssl_error())
242 return false;
243
244 // Don't convert to a reload when the last navigation was a POST or the new
245 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04246 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28247 return false;
248
249 return true;
ananta3bdd8ae2016-12-22 17:11:55250}
251
Arthur Sonzognic686e8f2024-01-11 08:36:37252std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12253 const mojom::DidCommitProvisionalLoadParams& params,
254 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32255 // Error pages commit in an opaque origin, yet have the real URL that resulted
256 // in an error as the |params.url|. Since successful reload of an error page
257 // should commit in the correct origin, setting the opaque origin on the
258 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17259 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37260 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32261
Arthur Sonzognic686e8f2024-01-11 08:36:37262 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32263}
264
Alex Moshchuk99242832023-05-22 17:21:44265bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42266 const GURL& virtual_url,
267 const GURL& dest_url) {
268 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44269 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
270 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42271 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
272 << virtual_url.possibly_invalid_spec();
273 return false;
274 }
275
276 // Don't attempt to navigate to non-empty invalid URLs.
277 if (!dest_url.is_valid() && !dest_url.is_empty()) {
278 LOG(WARNING) << "Refusing to load invalid URL: "
279 << dest_url.possibly_invalid_spec();
280 return false;
281 }
282
283 // The renderer will reject IPC messages with URLs longer than
284 // this limit, so don't attempt to navigate with a longer URL.
285 if (dest_url.spec().size() > url::kMaxURLChars) {
286 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
287 << " characters.";
288 return false;
289 }
290
Aaron Colwell33109c592020-04-21 21:31:19291 // Reject renderer debug URLs because they should have been handled before
292 // we get to this point. This check handles renderer debug URLs
293 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
294 // provides defense-in-depth if a renderer debug URL manages to get here via
295 // some other path. We want to reject the navigation here so it doesn't
296 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30297 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19298 LOG(WARNING) << "Refusing to load renderer debug URL: "
299 << dest_url.possibly_invalid_spec();
300 return false;
301 }
302
Alex Moshchuk99242832023-05-22 17:21:44303 // Guests only support navigations to known-safe schemes. This check already
304 // exists in the extensions layer, where it also dispatches proper events to
305 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
306 // for defense-in-depth to ensure that no other places in the codebase
307 // accidentally navigate guests to schemes such as WebUI, which is not
308 // supported. See https://crbug.com/1444221.
309 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
310 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
311 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
312 !dest_url.SchemeIs(url::kAboutScheme)) {
313 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
314 << dest_url.possibly_invalid_spec();
315 return false;
316 }
317 }
318
Camille Lamy5193caa2018-10-12 11:59:42319 return true;
320}
321
Mikel Astizba9cf2fd2017-12-17 10:38:10322// See replaced_navigation_entry_data.h for details: this information is meant
323// to ensure |*output_entry| keeps track of its original URL (landing page in
324// case of server redirects) as it gets replaced (e.g. history.replaceState()),
325// without overwriting it later, for main frames.
326void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57327 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10328 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17329 if (output_entry->GetReplacedEntryData().has_value() ||
330 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10331 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17332 }
Mikel Astizba9cf2fd2017-12-17 10:38:10333
334 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57335 data.first_committed_url = replaced_entry->GetURL();
336 data.first_timestamp = replaced_entry->GetTimestamp();
337 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29338 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10339}
340
Minggang Wangb9f3fa92021-07-01 15:30:31341blink::mojom::NavigationType GetNavigationType(
342 const GURL& old_url,
343 const GURL& new_url,
344 ReloadType reload_type,
345 NavigationEntryImpl* entry,
346 const FrameNavigationEntry& frame_entry,
347 bool has_pending_cross_document_commit,
348 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49349 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13350 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49351 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23352 // Reload navigations
353 switch (reload_type) {
354 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31355 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23356 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31357 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23358 case ReloadType::NONE:
359 break; // Fall through to rest of function.
360 }
361
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08362 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31363 return entry->GetHasPostData()
364 ? blink::mojom::NavigationType::RESTORE_WITH_POST
365 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23366 }
367
danakjb952ef12021-01-14 19:58:49368 const bool can_be_same_document =
369 // A pending cross-document commit means this navigation will not occur in
370 // the current document, as that document would end up being replaced in
371 // the meantime.
372 !has_pending_cross_document_commit &&
373 // If the current document is an error page, we should always treat it as
374 // a different-document navigation so that we'll attempt to load the
375 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49376 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13377 // If the navigation is an embedder-initiated navigation of a fenced
378 // frame root (i.e. enters a fenced frame tree from outside),
379 // same-document navigations should be disabled because we don't want to
380 // allow information to be joined across multiple embedder-initiated
381 // fenced frame navigations (which may contain separate cross-site data).
382 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49383 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
384 // same-document navigations should be disabled because we want to force
385 // the creation of a new browsing context group.
386 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12387
clamyea99ea12018-05-28 13:54:23388 // History navigations.
389 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12390 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31391 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
392 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23393 }
394 DCHECK(!is_same_document_history_load);
395
396 // A same-document fragment-navigation happens when the only part of the url
397 // that is modified is after the '#' character.
398 //
399 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12400 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23401 //
402 // Note: this check is only valid for navigations that are not history
403 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
404 // history navigation from 'A#foo' to 'A#bar' is not a same-document
405 // navigation, but a different-document one. This is why history navigation
406 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47407 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
408 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12409
410 // The one case where we do the wrong thing here and incorrectly choose
411 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
412 // the renderer is a frameset. All frameset navigations should be
413 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
414 // navigation would do the right thing, as it would send it to the browser and
415 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
416 // into this method). But since we can't tell that case here for browser-
417 // initiated navigations, we have to get the renderer involved. In that case
418 // the navigation would be restarted due to the renderer spending a reply of
419 // mojom::CommitResult::RestartCrossDocument.
420
421 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31422 ? blink::mojom::NavigationType::SAME_DOCUMENT
423 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23424}
425
Camille Lamy5193caa2018-10-12 11:59:42426// Adjusts the original input URL if needed, to get the URL to actually load and
427// the virtual URL, which may differ.
428void RewriteUrlForNavigation(const GURL& original_url,
429 BrowserContext* browser_context,
430 GURL* url_to_load,
431 GURL* virtual_url,
432 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42433 // Allow the browser URL handler to rewrite the URL. This will, for example,
434 // remove "view-source:" from the beginning of the URL to get the URL that
435 // will actually be loaded. This real URL won't be shown to the user, just
436 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31437 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42438 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
439 url_to_load, browser_context, reverse_on_redirect);
440}
441
442#if DCHECK_IS_ON()
443// Helper sanity check function used in debug mode.
444void ValidateRequestMatchesEntry(NavigationRequest* request,
445 NavigationEntryImpl* entry) {
446 if (request->frame_tree_node()->IsMainFrame()) {
447 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
448 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31449 ui::PageTransitionFromInt(request->common_params().transition),
450 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42451 }
Nasko Oskovc36327d2019-01-03 23:23:04452 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42453 entry->should_clear_history_list());
454 DCHECK_EQ(request->common_params().has_user_gesture,
455 entry->has_user_gesture());
456 DCHECK_EQ(request->common_params().base_url_for_data_url,
457 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04458 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42459 entry->GetCanLoadLocalResources());
460 DCHECK_EQ(request->common_params().started_from_context_menu,
461 entry->has_started_from_context_menu());
462
463 FrameNavigationEntry* frame_entry =
464 entry->GetFrameEntry(request->frame_tree_node());
465 if (!frame_entry) {
Peter Boström8472105d2024-05-15 04:36:02466 NOTREACHED_IN_MIGRATION();
Camille Lamy5193caa2018-10-12 11:59:42467 return;
468 }
469
Camille Lamy5193caa2018-10-12 11:59:42470 DCHECK_EQ(request->common_params().method, frame_entry->method());
471
Nasko Oskovc36327d2019-01-03 23:23:04472 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42473 if (redirect_size == frame_entry->redirect_chain().size()) {
474 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04475 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42476 frame_entry->redirect_chain()[i]);
477 }
478 } else {
Peter Boström8472105d2024-05-15 04:36:02479 NOTREACHED_IN_MIGRATION();
Camille Lamy5193caa2018-10-12 11:59:42480 }
481}
482#endif // DCHECK_IS_ON()
483
Dave Tapuska8bfd84c2019-03-26 20:47:16484// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20485// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16486bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20487 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16488 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20489 DCHECK(sandboxed_initiator_rfh);
490 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
491 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16492 for (auto& item : navigations) {
493 bool within_subtree = false;
494 // Check whether this NavigationRequest affects a frame within the
495 // sandboxed frame's subtree by walking up the tree looking for the
496 // sandboxed frame.
497 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03498 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20499 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16500 within_subtree = true;
501 break;
502 }
503 }
504 if (!within_subtree)
505 return false;
506 }
507 return true;
508}
509
William Liu122754942024-01-18 22:34:39510// Used for "Navigation.SessionHistoryCount" histogram.
511enum class HistoryNavTypeForHistogram {
512 // A same-doc or cross-doc navigation of the main frame. We can only have one
513 // main frame request per `NavigationController::GoToIndex()`.
514 kMainFrame = 0,
515 // `NavigationController::GoToIndex()` creates one main frame request and
516 // one or more subframe requests.
517 kMainFrameAndSubframe,
518 // `NavigationController::GoToIndex()` creates one or more subframe requests.
519 kSubframe,
520 // Used for histogram boundary.
521 kCount
522};
523
524void CountRequests(
525 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
526 int& mutable_main_frame_cnt,
527 int& mutable_subframe_cnt) {
528 for (const auto& req : requests) {
529 if (req->IsInPrimaryMainFrame()) {
530 // We can only have one main frame navigation at a time.
531 CHECK_EQ(mutable_main_frame_cnt, 0);
532 ++mutable_main_frame_cnt;
533 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
534 ++mutable_subframe_cnt;
535 }
536 }
537}
538
539// Record the number of different types of navigations as histograms. See
540// `HistoryNavTypeForHistogram` for the types.
541void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
542 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
543 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
544 // We must have one request.
545 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
546
547 int main_frame_cnt = 0;
548 int subframe_cnt = 0;
549 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
550 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
551
552 std::optional<HistoryNavTypeForHistogram> history_nav_type;
553 if (main_frame_cnt > 0) {
554 if (subframe_cnt == 0) {
555 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
556 } else {
557 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
558 }
559 } else if (subframe_cnt > 0) {
560 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
561 }
562 if (history_nav_type.has_value()) {
563 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
564 history_nav_type.value(),
565 HistoryNavTypeForHistogram::kCount);
566 }
567}
568
[email protected]e9ba4472008-09-14 15:42:43569} // namespace
570
arthursonzogni66f711c2019-10-08 14:40:36571// NavigationControllerImpl::PendingEntryRef------------------------------------
572
573NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
574 base::WeakPtr<NavigationControllerImpl> controller)
575 : controller_(controller) {}
576
577NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
578 if (!controller_) // Can be null with interstitials.
579 return;
580
581 controller_->PendingEntryRefDeleted(this);
582}
583
[email protected]d202a7c2012-01-04 07:53:47584// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29585
[email protected]23a918b2014-07-15 09:51:36586const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23587
[email protected]765b35502008-08-21 00:51:20588// static
[email protected]d202a7c2012-01-04 07:53:47589size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23590 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20591
[email protected]e6fec472013-05-14 05:29:02592// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20593// when testing.
594static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29595
[email protected]71fde352011-12-29 03:29:56596// static
dcheng9bfa5162016-04-09 01:00:57597std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
598 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10599 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37600 std::optional<url::Origin> initiator_origin,
601 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10602 ui::PageTransition transition,
603 bool is_renderer_initiated,
604 const std::string& extra_headers,
605 BrowserContext* browser_context,
606 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
607 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21608 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37609 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32610 is_renderer_initiated, extra_headers, browser_context,
611 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10612}
613
614// static
615std::unique_ptr<NavigationEntryImpl>
616NavigationControllerImpl::CreateNavigationEntry(
617 const GURL& url,
618 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37619 std::optional<url::Origin> initiator_origin,
620 std::optional<GURL> initiator_base_url,
621 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57622 ui::PageTransition transition,
623 bool is_renderer_initiated,
624 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09625 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17626 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
627 bool rewrite_virtual_urls) {
628 GURL url_to_load = url;
629 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56630 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17631 if (rewrite_virtual_urls) {
632 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
633 &reverse_on_redirect);
634 }
Lukasz Anforowicz641234d52019-11-07 21:07:10635 // Let the NTP override the navigation params and pretend that this is a
636 // browser-initiated, bookmark-like navigation.
637 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32638 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21639 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10640
Patrick Monettef507e982019-06-19 20:18:06641 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28642 nullptr, // The site instance for tabs is sent on navigation
643 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21644 url_to_load, referrer, initiator_origin, initiator_base_url,
645 std::u16string(), transition, is_renderer_initiated,
646 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17647 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42648 entry->SetVirtualURL(virtual_url);
649 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56650 entry->set_update_virtual_url_with_url(reverse_on_redirect);
651 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06652 return entry;
[email protected]71fde352011-12-29 03:29:56653}
654
[email protected]cdcb1dee2012-01-04 00:46:20655// static
656void NavigationController::DisablePromptOnRepost() {
657 g_check_for_repost = false;
658}
659
[email protected]c5b88d82012-10-06 17:03:33660base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
661 base::Time t) {
662 // If |t| is between the water marks, we're in a run of duplicates
663 // or just getting out of it, so increase the high-water mark to get
664 // a time that probably hasn't been used before and return it.
665 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35666 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33667 return high_water_mark_;
668 }
669
670 // Otherwise, we're clear of the last duplicate run, so reset the
671 // water marks.
672 low_water_mark_ = high_water_mark_ = t;
673 return t;
674}
675
ckitagawa0faa5e42020-06-17 17:30:54676NavigationControllerImpl::ScopedShowRepostDialogForTesting::
677 ScopedShowRepostDialogForTesting()
678 : was_disallowed_(g_check_for_repost) {
679 g_check_for_repost = true;
680}
681
682NavigationControllerImpl::ScopedShowRepostDialogForTesting::
683 ~ScopedShowRepostDialogForTesting() {
684 g_check_for_repost = was_disallowed_;
685}
686
Nate Chapin9eb16be72022-09-23 22:54:31687NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
688 base::SafeRef<NavigationControllerImpl> controller)
689 : controller_(controller) {
690 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
691 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
692 frame_tree_node_id_to_keys_.insert(
693 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
694 if (auto* frame_entry = frame_tree_node->current_frame_host()
695 ->last_committed_frame_entry()) {
696 frame_tree_node_id_to_doc_seq_nos_.insert(
697 {frame_tree_node->frame_tree_node_id(),
698 frame_entry->document_sequence_number()});
699 }
700 }
701 PopulateKeySet(Direction::kBack);
702 PopulateKeySet(Direction::kForward);
703}
704
705void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
706 Direction direction) {
707 // Keep track of which FrameTreeNodes may still have relevant API keys in
708 // additional FrameNavigationEntries.
709 std::set<FrameTreeNode*> nodes_to_process;
710 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
711 nodes_to_process.insert(node);
712 }
713
714 const int offset = direction == Direction::kForward ? 1 : -1;
715 const int start = direction == Direction::kForward
716 ? controller_->GetLastCommittedEntryIndex()
717 : controller_->GetLastCommittedEntryIndex() - 1;
718 for (int i = start;
719 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
720 i += offset) {
721 std::set<FrameTreeNode*> nodes_to_continue_processing;
722
723 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
724 entry->ForEachFrameEntry([this, &nodes_to_process,
725 &nodes_to_continue_processing,
726 &entry](FrameNavigationEntry* frame_entry) {
727 // Find the |node| that matches |frame_entry|, if any.
728 FrameTreeNode* node = nullptr;
729 if (frame_entry == entry->root_node()->frame_entry) {
730 node = controller_->frame_tree().root();
731 } else {
732 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
733 if (it == names_to_nodes_.end())
734 return;
735 node = it->second;
736 }
737
738 // Skip this node if a previous step determine there are no longer
739 // relevant navigation API keys in this direction.
740 if (nodes_to_process.find(node) == nodes_to_process.end())
741 return;
742
743 // Stop processing |node| if we reach a point where it's cross-origin.
744 // See also PopulateSingleNavigationApiHistoryEntryVector().
745 url::Origin frame_entry_origin =
746 frame_entry->committed_origin().value_or(url::Origin::Resolve(
747 frame_entry->url(),
748 frame_entry->initiator_origin().value_or(url::Origin())));
749 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
750 return;
751
752 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
753 frame_entry->navigation_api_key());
754 // Mark |node| as needing more processing for the next entry.
755 nodes_to_continue_processing.insert(node);
756
757 // Check whether |node| went cross-document. If so, its children are
758 // no longer the same conceptual iframe as the current one, and
759 // should no longer be processed. This check is intentionally done
760 // after processing the current |node|, which may still have relevant
761 // discarded API keys.
762 if (frame_entry->document_sequence_number() !=
763 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50764 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31765 nodes_to_process.erase(descendant);
766 }
767 });
768
769 nodes_to_process.swap(nodes_to_continue_processing);
770 }
771}
772
773NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
774 std::set<std::string> all_keys;
775 // Find all remaining navigation API keys after some entries have been
776 // removed.
777 for (auto& entry : controller_->entries_) {
778 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
779 all_keys.insert(frame_entry->navigation_api_key());
780 });
781 }
782
783 // Notify each frame in the renderer of any disposed navigation API keys.
784 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
785 std::vector<std::string> disposed_keys;
786 for (const auto& key : id_to_keys.second) {
787 if (all_keys.find(key) == all_keys.end())
788 disposed_keys.push_back(key);
789 }
790 if (disposed_keys.empty())
791 continue;
792
793 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
794 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
795 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
796 }
797}
798
[email protected]d202a7c2012-01-04 07:53:47799NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00800 BrowserContext* browser_context,
801 FrameTree& frame_tree,
802 NavigationControllerDelegate* delegate)
803 : frame_tree_(frame_tree),
804 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57805 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22806 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37807 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
808 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37809 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29810}
811
[email protected]d202a7c2012-01-04 07:53:47812NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00813 // The NavigationControllerImpl might be called inside its delegate
814 // destructor. Calling it is not valid anymore.
815 delegate_ = nullptr;
816 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29817}
818
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57819BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55820 return browser_context_;
821}
822
[email protected]d202a7c2012-01-04 07:53:47823void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30824 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36825 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57826 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47827 // Note that it's possible for `entries_` to contain multiple entries at this
828 // point, as Restore() might be called on a NavigationController that is
829 // already used (e.g. due to WebView's restoreState() API), not only for fresh
830 // NavigationControllers. These entries are not cleared to preserve legacy
831 // behavior and also because `pending_entry_` might point to one of the
832 // pre-existing entries. An exception for this is when `entries_` contains
833 // only the initial NavigationEntry, which must be removed.
834
835 // Do not proceed if selected_navigation will be out of bounds for the updated
836 // entries_ list, since it will be assigned to last_committed_entry_index_ and
837 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58838 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47839 // is empty, since there should be no work to do (rather than marking the
840 // existing entries as needing reload). Also consider returning early if the
841 // selected index is -1, which represents a no-committed-entry state.
842 if (selected_navigation < -1 ||
843 selected_navigation >=
844 base::checked_cast<int>(entries->size() + entries_.size())) {
845 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24846 }
Charlie Reis23c26da2022-01-29 00:57:47847
Rakina Zata Amni46087a12022-11-11 08:28:38848 // There will always be at least one entry (new NavigationControllers will
849 // have the initial NavigationEntry).
850 if (selected_navigation == -1)
851 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47852
Rakina Zata Amni46087a12022-11-11 08:28:38853 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
854 // If we are on the initial NavigationEntry, it must be the only entry in
855 // the list. Since it's impossible to do a history navigation to the
856 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
857 // `pending_entry` might be set for a new non-history navigation).
858 // Note that we should not clear `entries_` if `entries` is empty (when
859 // InitialNavigationEntry mode is enabled), since that would leave us
860 // without any NavigationEntry.
861 CHECK_EQ(1, GetEntryCount());
862 CHECK_EQ(-1, pending_entry_index_);
863 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47864 }
[email protected]ce3fa3c2009-04-20 19:55:57865
[email protected]ce3fa3c2009-04-20 19:55:57866 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44867 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03868 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47869 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43870 if (entry->GetURL().is_empty()) {
871 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01872 // persisting the initial NavigationEntry [which is no longer possible but
873 // some old persisted sessions might still contain it] or when the
874 // serializer failed to write the URL because it's too long). Trying to
875 // restore and navigate to an entry with an empty URL will result in
876 // crashes, so change the URL to about:blank. See also
877 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43878 entry->SetURL(GURL(url::kAboutBlankURL));
879 }
dcheng36b6aec92015-12-26 06:16:36880 entries_.push_back(
881 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47882 }
avif16f85a72015-11-13 18:25:03883
884 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
885 // cleared out safely.
886 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57887
888 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36889 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57890}
891
toyoshim6142d96f2016-12-19 09:07:25892void NavigationControllerImpl::Reload(ReloadType reload_type,
893 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03894 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
895 (int)reload_type);
896 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
897 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28898 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28899 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32900 int current_index = -1;
901
Carlos IL42b416592019-10-07 23:10:36902 if (entry_replaced_by_post_commit_error_) {
903 // If there is an entry that was replaced by a currently active post-commit
904 // error navigation, this can't be the initial navigation.
905 DCHECK(!IsInitialNavigation());
906 // If the current entry is a post commit error, we reload the entry it
907 // replaced instead. We leave the error entry in place until a commit
908 // replaces it, but the pending entry points to the original entry in the
909 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
910 // case that pending_entry_ != entries_[pending_entry_index_].
911 entry = entry_replaced_by_post_commit_error_.get();
912 current_index = GetCurrentEntryIndex();
913 } else if (IsInitialNavigation() && pending_entry_) {
914 // If we are reloading the initial navigation, just use the current
915 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32916 entry = pending_entry_;
917 // The pending entry might be in entries_ (e.g., after a Clone), so we
918 // should also update the current_index.
919 current_index = pending_entry_index_;
920 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00921 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32922 current_index = GetCurrentEntryIndex();
923 if (current_index != -1) {
creis3da03872015-02-20 21:12:32924 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32925 }
[email protected]979a4bc2013-04-24 01:27:15926 }
[email protected]241db352013-04-22 18:04:05927
[email protected]59167c22013-06-03 18:07:32928 // If we are no where, then we can't reload. TODO(darin): We should add a
929 // CanReload method.
930 if (!entry)
931 return;
932
Rakina Zata Amnif297a802022-01-18 03:53:43933 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
934 // We should never navigate to an existing initial NavigationEntry that is
935 // the initial NavigationEntry for the initial empty document that hasn't
936 // been overridden by the synchronous about:blank commit, to preserve
937 // legacy behavior where trying to reload when the main frame is on the
938 // initial empty document won't result in a navigation. See also
939 // https://crbug.com/1277414.
940 return;
941 }
942
Aran Gilman37d11632019-10-08 23:07:15943 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30944 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07945 // they really want to do this. If they do, the dialog will call us back
946 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57947 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02948
[email protected]106a0812010-03-18 00:15:12949 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57950 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47951 return;
initial.commit09911bf2008-07-26 23:55:29952 }
Lei Zhang96031532019-10-10 19:05:47953
Wang Huia25efabc2022-09-24 17:27:22954 // Set ReloadType for |entry|.
955 entry->set_reload_type(reload_type);
956
Lei Zhang96031532019-10-10 19:05:47957 if (!IsInitialNavigation())
958 DiscardNonCommittedEntries();
959
960 pending_entry_ = entry;
961 pending_entry_index_ = current_index;
962 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
963
Nate Chapin45f620582021-09-30 17:45:43964 // location.reload() goes through BeginNavigation, so all reloads triggered
965 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13966 NavigateToExistingPendingEntry(
967 reload_type,
968 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:37969 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:13970 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29971}
972
[email protected]d202a7c2012-01-04 07:53:47973void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48974 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12975}
976
[email protected]d202a7c2012-01-04 07:53:47977void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49978 // If the pending reload type has been cleared by another navigation
979 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48980 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49981 return;
[email protected]106a0812010-03-18 00:15:12982 }
Wang Hui96ab1012022-10-11 02:05:49983 Reload(pending_reload_, false);
984 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12985}
986
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57987bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09988 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11989}
990
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57991bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38992 // Check that we're on the initial NavigationEntry and that this is not a
993 // cloned tab.
994 return IsInitialNavigation() && GetEntryCount() == 1 &&
995 GetLastCommittedEntry()->IsInitialEntry() &&
996 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40997}
998
Aran Gilman37d11632019-10-08 23:07:15999NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1000 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581001 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031002 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581003}
1004
Adithya Srinivasan9b0c99c2021-08-10 15:19:451005NavigationEntryImpl*
1006NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1007 int nav_entry_id) const {
1008 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1009 if (entry)
1010 return entry;
1011 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521012 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451013 : nullptr;
1014}
1015
W. James MacLeanc07dc41b2022-07-25 18:52:161016void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571017 const url::Origin& origin) {
1018 for (int i = 0; i < GetEntryCount(); i++) {
1019 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161020 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571021 }
1022 if (entry_replaced_by_post_commit_error_) {
1023 // It's possible we could come back to this entry if the error
1024 // page/interstitial goes away.
1025 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161026 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571027 }
W. James MacLean1c40862c2020-04-27 21:05:571028}
1029
avi25764702015-06-23 15:43:371030void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571031 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001032 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371033 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271034 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201035}
1036
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571037NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471038 if (pending_entry_)
1039 return pending_entry_;
1040 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201041}
1042
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571043NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321044 // The pending entry is safe to return for new (non-history), browser-
1045 // initiated navigations. Most renderer-initiated navigations should not
1046 // show the pending entry, to prevent URL spoof attacks.
1047 //
1048 // We make an exception for renderer-initiated navigations in new tabs, as
1049 // long as no other page has tried to access the initial empty document in
1050 // the new tab. If another page modifies this blank page, a URL spoof is
1051 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321052 bool safe_to_show_pending =
1053 pending_entry_ &&
1054 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091055 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321056 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461057 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321058
1059 // Also allow showing the pending entry for history navigations in a new tab,
1060 // such as Ctrl+Back. In this case, no existing page is visible and no one
1061 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151062 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1063 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321064 safe_to_show_pending = true;
1065
1066 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191067 return pending_entry_;
1068 return GetLastCommittedEntry();
1069}
1070
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571071int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201072 if (pending_entry_index_ != -1)
1073 return pending_entry_index_;
1074 return last_committed_entry_index_;
1075}
1076
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571077NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381078 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031079 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201080}
1081
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571082bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351083 const std::string& mime_type = frame_tree_->root()
1084 ->current_frame_host()
1085 ->GetPage()
1086 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531087 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1088 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271089 NavigationEntry* visible_entry = GetVisibleEntry();
1090 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391091 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161092}
1093
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571094int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271095 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451096 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271097 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551098 return last_committed_entry_index_;
1099}
1100
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571101int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451102 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291103 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551104 return static_cast<int>(entries_.size());
1105}
1106
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571107NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371108 if (index < 0 || index >= GetEntryCount())
1109 return nullptr;
1110
avif16f85a72015-11-13 18:25:031111 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251112}
1113
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571114NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471115 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201116}
1117
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571118int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461119 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031120}
1121
Arthur Sonzognic686e8f2024-01-11 08:36:371122std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031123 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591124 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1125 return index;
1126 }
Shivani Sharma298d12852019-01-22 20:04:031127 }
Arthur Sonzognic686e8f2024-01-11 08:36:371128 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591129}
1130
1131bool NavigationControllerImpl::CanGoBack() {
1132 return GetIndexForGoBack().has_value();
1133}
1134
Arthur Sonzognic686e8f2024-01-11 08:36:371135std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591136 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1137 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1138 return index;
1139 }
1140 }
Arthur Sonzognic686e8f2024-01-11 08:36:371141 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201142}
1143
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571144bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591145 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201146}
1147
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571148bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031149 int index = GetIndexForOffset(offset);
1150 return index >= 0 && index < GetEntryCount();
1151}
1152
Xiaohan Wang7f8052e02022-01-14 18:44:281153#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151154bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151155 if (offset == 0)
1156 return true;
1157 int increment = offset > 0 ? 1 : -1;
1158 int non_skippable_entries = 0;
1159 for (int index = GetIndexForOffset(increment);
1160 index >= 0 && index < GetEntryCount(); index += increment) {
1161 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1162 non_skippable_entries++;
1163
1164 if (non_skippable_entries == std::abs(offset))
1165 return true;
1166 }
1167 return false;
1168}
1169#endif
1170
[email protected]d202a7c2012-01-04 07:53:471171void NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371172 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061173
Kevin McNeeedc481c2023-04-27 22:30:581174 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211175
Kevin McNee3b3a56192023-03-17 14:40:591176 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201177}
1178
[email protected]d202a7c2012-01-04 07:53:471179void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161180 // Note that at least one entry (the last one) will be non-skippable since
1181 // entries are marked skippable only when they add another entry because of
1182 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371183 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591184
Kevin McNeeedc481c2023-04-27 22:30:581185 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591186
1187 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201188}
1189
[email protected]d202a7c2012-01-04 07:53:471190void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131191 GoToIndex(index, /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371192 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:131193 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161194}
1195
William Liu1ea335752024-08-06 15:03:301196std::vector<base::WeakPtr<NavigationRequest>>
1197NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201198 int index,
1199 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371200 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131201 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201202 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441203 TRACE_EVENT0("browser,navigation,benchmark",
1204 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501205 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1206 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1207 entries_.size());
1208 // Indices should have have been validated by the caller.
1209 CHECK_GE(index, 0);
1210 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201211
Rakina Zata Amnif297a802022-01-18 03:53:431212 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1213 // We should never navigate to an existing initial NavigationEntry that is
1214 // the initial NavigationEntry for the initial empty document that hasn't
1215 // been overridden by the synchronous about:blank commit, to preserve
1216 // legacy behavior where trying to reload when the main frame is on the
1217 // initial empty document won't result in a navigation. See also
1218 // https://crbug.com/1277414.
William Liu1ea335752024-08-06 15:03:301219 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431220 }
1221
[email protected]cbab76d2008-10-13 22:42:471222 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201223
arthursonzogni5c4c202d2017-04-25 23:41:271224 DCHECK_EQ(nullptr, pending_entry_);
1225 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431226
arthursonzogni5c4c202d2017-04-25 23:41:271227 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201228 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271229 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1230 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
William Liuec04e382024-05-23 18:03:271231 return NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
1232 soft_navigation_heuristics_task_id,
1233 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201234}
1235
[email protected]d202a7c2012-01-04 07:53:471236void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121237 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031238 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201239 return;
1240
[email protected]9ba14052012-06-22 23:50:031241 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201242}
1243
Nate Chapinbf682fa32022-09-26 22:41:201244void NavigationControllerImpl::GoToOffsetFromRenderer(
1245 int offset,
Yoav Weiss8c573952022-11-17 17:35:131246 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371247 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131248 soft_navigation_heuristics_task_id) {
Nate Chapinbb74c5a52023-07-21 23:13:351249 // Note: This is actually reached in unit tests.
1250 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431251 return;
1252
Nate Chapinbf682fa32022-09-26 22:41:201253 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131254 soft_navigation_heuristics_task_id,
1255 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431256}
1257
William Liu1ea335752024-08-06 15:03:301258std::vector<base::WeakPtr<NavigationRequest>>
1259NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271260 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1261 /*soft_navigation_heuristics_task_id=*/std::nullopt,
1262 /*navigation_api_key=*/nullptr);
1263}
1264
Xiaohan Wang7f8052e02022-01-14 18:44:281265#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151266void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1267 // Note: This is actually reached in unit tests.
1268 if (!CanGoToOffsetWithSkipping(offset))
1269 return;
1270
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421271 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151272 GoToIndex(GetIndexForOffset(offset));
1273 return;
1274 }
1275 int increment = offset > 0 ? 1 : -1;
1276 // Find the offset without counting skippable entries.
1277 int target_index = GetIndexForOffset(increment);
1278 int non_skippable_entries = 0;
1279 for (int index = target_index; index >= 0 && index < GetEntryCount();
1280 index += increment) {
1281 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1282 non_skippable_entries++;
1283
1284 if (non_skippable_entries == std::abs(offset)) {
1285 target_index = index;
1286 break;
1287 }
1288 }
1289
1290 GoToIndex(target_index);
1291}
1292#endif
1293
[email protected]41374f12013-07-24 02:49:281294bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151295 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281296 return false;
[email protected]6a13a6c2011-12-20 21:47:121297
[email protected]43032342011-03-21 14:10:311298 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281299 return true;
[email protected]cbab76d2008-10-13 22:42:471300}
1301
Michael Thiessen9b14d512019-09-23 21:19:471302void NavigationControllerImpl::PruneForwardEntries() {
1303 DiscardNonCommittedEntries();
1304 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471305 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471306 if (num_removed <= 0)
1307 return;
Nate Chapin9eb16be72022-09-23 22:54:311308 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471309 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1310 NotifyPrunedEntries(this, remove_start_index /* start index */,
1311 num_removed /* count */);
1312}
1313
Aran Gilman37d11632019-10-08 23:07:151314void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1315 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321316 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311317 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511318 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1319 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321320 }
1321}
1322
Harkiran Bolariaba823e42021-05-21 18:30:361323base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1324 const GURL& url,
1325 const Referrer& referrer,
1326 ui::PageTransition transition,
1327 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471328 LoadURLParams params(url);
1329 params.referrer = referrer;
1330 params.transition_type = transition;
1331 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361332 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471333}
1334
Harkiran Bolariaba823e42021-05-21 18:30:361335base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1336 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061337 if (params.is_renderer_initiated)
1338 DCHECK(params.initiator_origin.has_value());
1339
naskob8744d22014-08-28 17:07:431340 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151341 "NavigationControllerImpl::LoadURLWithParams", "url",
1342 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291343 bool is_explicit_navigation =
1344 GetContentClient()->browser()->IsExplicitNavigation(
1345 params.transition_type);
1346 if (HandleDebugURL(params.url, params.transition_type,
1347 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431348 // If Telemetry is running, allow the URL load to proceed as if it's
1349 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491350 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431351 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361352 return nullptr;
[email protected]47752982014-07-29 08:01:431353 }
[email protected]8bf1048012012-02-08 01:22:181354
[email protected]cf002332012-08-14 19:17:471355 // Checks based on params.load_type.
1356 switch (params.load_type) {
1357 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431358 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541359#if BUILDFLAG(IS_ANDROID)
1360 case LOAD_TYPE_PDF_ANDROID:
1361#endif
[email protected]cf002332012-08-14 19:17:471362 break;
1363 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261364 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boström8472105d2024-05-15 04:36:021365 NOTREACHED_IN_MIGRATION() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361366 return nullptr;
[email protected]cf002332012-08-14 19:17:471367 }
1368 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461369 }
[email protected]e47ae9472011-10-13 19:48:341370
[email protected]e47ae9472011-10-13 19:48:341371 // The user initiated a load, we don't need to reload anymore.
1372 needs_reload_ = false;
1373
Harkiran Bolariaba823e42021-05-21 18:30:361374 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441375}
1376
Charlie Reis4c53a962023-06-21 23:17:531377void NavigationControllerImpl::LoadOriginalRequestURL() {
1378 // If the original request URL is not valid, matches the current URL, or
1379 // involves POST data, then simply reload. The POST check avoids issues with
1380 // sending data to the wrong page.
1381 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1382 const GURL& original_request_url =
1383 GetLastCommittedEntry()->GetOriginalRequestURL();
1384 if (!original_request_url.is_valid() ||
1385 original_request_url == last_committed_url ||
1386 GetLastCommittedEntry()->GetHasPostData()) {
1387 Reload(ReloadType::NORMAL, true);
1388 return;
1389 }
1390
1391 // Otherwise, attempt to load the original request URL without any of the
1392 // other data from the current NavigationEntry, replacing the current entry.
1393 // Loading the original URL is useful in cases such as modifying the user
1394 // agent.
1395 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1396 std::make_unique<NavigationController::LoadURLParams>(
1397 original_request_url);
1398 load_params->should_replace_current_entry = true;
1399 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1400 LoadURLWithParams(*load_params.get());
1401}
1402
Mohamed Abdelhalim833de902019-09-16 17:41:451403bool NavigationControllerImpl::PendingEntryMatchesRequest(
1404 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191405 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451406 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191407}
1408
[email protected]d202a7c2012-01-04 07:53:471409bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321410 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071411 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331412 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441413 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251414 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561415 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131416 NavigationRequest* navigation_request) {
1417 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331418
1419 // Note: validation checks and renderer kills due to invalid commit messages
1420 // must happen before getting here, in
1421 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1422 // effects of the navigation have already occurred.
1423
[email protected]cd2e15742013-03-08 04:08:311424 is_initial_navigation_ = false;
1425
Wang Hui96ab1012022-10-11 02:05:491426 // Any pending request to repost a form submission is no longer valid, since a
1427 // different NavigationEntry is committing.
1428 pending_reload_ = ReloadType::NONE;
1429
[email protected]0e8db942008-09-24 21:21:481430 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431431 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451432 if (entry_replaced_by_post_commit_error_) {
1433 // Same document navigation events with a post-commit error should already
1434 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1435 // reaching here.
1436 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331437
Xinghui Lub9e86a352024-05-17 16:29:421438 if (pending_entry_) {
1439 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1440 // `pending_entry_` isn't pointing to the last committed entry.
1441 // Instead, all reload approaches (e.g., in `Reload` and
1442 // `LoadIfNecessary`) should attempt to load the
1443 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1444 // entry itself.
1445 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1446 << "Incorrectly reloading the post commit error page entry.";
1447 }
Xinghui Lue4e50be2024-05-15 21:46:001448
Rakina Zata Amnie2d31312022-11-18 03:38:451449 // Any commit while a post-commit error page is showing should put the
1450 // original entry back, replacing the error page's entry. This includes
1451 // reloads, where the original entry was used as the pending entry and
1452 // should now be at the correct index at commit time.
1453 entries_[last_committed_entry_index_] =
1454 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481455 }
Rakina Zata Amnie2d31312022-11-18 03:38:451456 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1457 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001458 // Must honor user agent overrides in the |navigation_request|, such as
1459 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1460 // result, besides comparing |pending_entry_|'s user agent against
1461 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1462 // agent against LastCommittedEntry's.
1463 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541464 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1465 (PendingEntryMatchesRequest(navigation_request) &&
1466 pending_entry_->GetIsOverridingUserAgent() !=
1467 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001468 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451469 }
[email protected]ecd9d8702008-08-28 22:10:171470
Dave Tapuskaa2ab4f252021-07-08 21:31:281471 bool is_main_frame_navigation = !rfh->GetParent();
1472
Alexander Timind2f2e4f22019-04-02 20:04:531473 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1474 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281475 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141476 // BackForwardCacheMetrics to be associated with the new navigation's
1477 // NavigationEntry, by either creating a new object or reusing the previous
1478 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281479 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211480 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141481 back_forward_cache_metrics = BackForwardCacheMetrics::
1482 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281483 GetLastCommittedEntry(), is_main_frame_navigation,
1484 params.document_sequence_number);
1485 }
Yuzu Saijo29f96ca92022-12-08 04:54:121486
Alexander Timind2f2e4f22019-04-02 20:04:531487 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281488 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451489 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1490 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531491 }
1492 }
1493
Rakina Zata Amnifd8370b2022-11-14 13:32:251494 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1495 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091496 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251497 details->did_replace_entry =
1498 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091499
fdegans9caf66a2015-07-30 21:10:421500 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111501 // except for restored entries. This should be true even if the current commit
1502 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291503 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481504 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081505 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111506
1507 // Only make changes based on the pending entry if the NavigationRequest
1508 // matches it. Otherwise, the pending entry may be for a different request
1509 // (e.g., if a slow history navigation is pending while an auto-subframe
1510 // commit occurs).
1511 if (PendingEntryMatchesRequest(navigation_request)) {
1512 // It is no longer necessary to consider the pending entry as restored.
1513 if (pending_entry_->IsRestored()) {
1514 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1515 was_restored = true;
1516 }
[email protected]e9ba4472008-09-14 15:42:431517
Charlie Reisf8cde712022-10-20 16:25:091518 // If the SiteInstance has changed from the matching pending entry, this
1519 // must be treated as a new navigation with replacement. Set the replacement
1520 // bit here and ClassifyNavigation will identify this case and return
1521 // NEW_ENTRY.
1522 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1523 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1524 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251525 // TODO(nasko,creis,rakina): Move this to happen before committing the
1526 // navigation. This is a bit complicated because we don't currently
1527 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091528 details->did_replace_entry = true;
1529 }
Nasko Oskovaee2f862018-06-15 00:05:521530 }
[email protected]bcd904482012-02-01 01:54:221531
[email protected]e9ba4472008-09-14 15:42:431532 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101533 NavigationType navigation_type =
1534 ClassifyNavigation(rfh, params, navigation_request);
1535 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451536
Rakina Zata Amnie2d31312022-11-18 03:38:451537 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451538 // Ensure that this navigation does not add a navigation entry, since
1539 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1540 // beyond the last committed one. Therefore, `should_replace_current_entry`
1541 // should be set, which replaces the current entry, or this should be a
1542 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251543 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331544 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451545 }
1546
Rakina Zata Amnie2d31312022-11-18 03:38:451547 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551548 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241549 // This is a subframe navigation on the initial empty document, which used
1550 // to not have a NavigationEntry to attach to. Now it can attach to the
1551 // initial NavigationEntry, and we must ensure that its NavigationEntry
1552 // will keep the "initial NavigationEntry" status and won't append a new
1553 // NavigationEntry (it should always do replacement instead).
1554 // See also https://crbug.com/1277414.
1555 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551556 // Subframe navigation on initial NavigationEntry must not append a new
1557 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1558 // means every subframe navigation that happens while we're on the initial
1559 // NavigationEntry will always reuse the existing NavigationEntry and
1560 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101561 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1562 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551563 // This is a navigation that modifies the initial NavigationEntry, either
1564 // for a replacement or a reload. The initial NavigationEntry should
1565 // retain its "initial NavigationEntry" status in this case.
1566 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241567 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251568 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1569 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241570 // This is a synchronous about:blank navigation on the main frame, which
1571 // used to not create a NavigationEntry when we have no NavigationEntry on
1572 // FrameTree creation. We now have the initial NavigationEntry and are on
1573 // the initial NavigationEntry. To preserve old behavior, we should still
1574 // keep the "initial" status for the new NavigationEntry that we will
1575 // create for this navigation, so that subframe navigations under the
1576 // synchronously committed about:blank document will never append new
1577 // NavigationEntry, and instead will just reuse the initial
1578 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1579 // See also https://crbug.com/1277414.
1580 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551581 }
1582 }
1583 DCHECK(!details->should_stay_as_initial_entry ||
1584 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201585
eugenebutee08663a2017-04-27 17:43:121586 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441587 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121588
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071589 details->is_prerender_activation =
1590 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241591 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1592 ->GetOutermostMainFrame()
1593 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071594
Peter Boströmd7592132019-01-30 04:50:311595 // Make sure we do not discard the pending entry for a different ongoing
1596 // navigation when a same document commit comes in unexpectedly from the
1597 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1598 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581599 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061600 bool keep_pending_entry =
1601 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101602 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061603 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311604
Miyoung Shin3299cbf2022-11-22 01:41:101605 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061606 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491607 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051608 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561609 previous_document_had_history_intervention_activation,
1610 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431611 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061612 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491613 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1614 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001615 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431616 break;
[email protected]8ff00d72012-10-23 19:12:211617 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471618 RendererDidNavigateNewSubframe(
1619 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561620 previous_document_had_history_intervention_activation,
1621 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431622 break;
[email protected]8ff00d72012-10-23 19:12:211623 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391624 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251625 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001626 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081627 // We don't send a notification about auto-subframe PageState during
1628 // UpdateStateForFrame, since it looks like nothing has changed. Send
1629 // it here at commit time instead.
1630 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431631 return false;
creis59d5a47cb2016-08-24 23:57:191632 }
[email protected]e9ba4472008-09-14 15:42:431633 break;
Aran Gilman37d11632019-10-08 23:07:151634 case NAVIGATION_TYPE_UNKNOWN:
Peter Boström8472105d2024-05-15 04:36:021635 NOTREACHED_IN_MIGRATION();
Aran Gilman37d11632019-10-08 23:07:151636 break;
[email protected]765b35502008-08-21 00:51:201637 }
1638
[email protected]688aa65c62012-09-28 04:32:221639 // At this point, we know that the navigation has just completed, so
1640 // record the time.
1641 //
1642 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261643 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331644 base::Time timestamp =
1645 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1646 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131647 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221648
Peter Boströmd7592132019-01-30 04:50:311649 // If we aren't keeping the pending entry, there shouldn't be one at this
1650 // point. Clear it again in case any error cases above forgot to do so.
1651 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1652 // been cleared instead of protecting against it.
1653 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551654 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141655
[email protected]e9ba4472008-09-14 15:42:431656 // All committed entries should have nonempty content state so WebKit doesn't
1657 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471658 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321659 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221660 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441661 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141662
Alexander Timind2f2e4f22019-04-02 20:04:531663 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1664 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281665 if (back_forward_cache_metrics &&
1666 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531667 active_entry->set_back_forward_cache_metrics(
1668 std::move(back_forward_cache_metrics));
1669 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281670
1671 // `back_forward_cache_metrics()` may return null as we do not record
1672 // back-forward cache metrics for navigations in non-primary frame trees.
1673 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581674 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141675 // These are both only available from details at this point, so we capture
1676 // them here.
1677 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101678 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141679 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1680 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281681 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1682 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321683 IsBackForwardCacheEnabled() &&
1684 rfh->delegate()->IsBackForwardCacheSupported() &&
1685 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281686 }
naskoc7533512016-05-06 17:01:121687
Charles Reisc0507202017-09-21 00:40:021688 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1689 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1690 // A mismatch can occur if the renderer lies or due to a unique name collision
1691 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121692 FrameNavigationEntry* frame_entry =
1693 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021694 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1695 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031696 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081697 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1698 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031699 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201700
1701 // Remember the bindings the renderer process has at this point, so that
1702 // we do not grant this entry additional bindings if we come back to it.
1703 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301704 }
[email protected]132e281a2012-07-31 18:32:441705
[email protected]97d8f0d2013-10-29 16:49:211706 // Once it is committed, we no longer need to track several pieces of state on
1707 // the entry.
naskoc7533512016-05-06 17:01:121708 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131709
[email protected]49bd30e62011-03-22 20:12:591710 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221711 // TODO(creis): This check won't pass for subframes until we create entries
1712 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001713 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421714 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591715
[email protected]e9ba4472008-09-14 15:42:431716 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001717 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001718 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311719 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531720
arthursonzogni7ddc6542021-04-09 09:16:501721 active_entry->SetIsOverridingUserAgent(
1722 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031723
[email protected]93f230e02011-06-01 14:40:001724 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291725
aelias100c9192017-01-13 00:01:431726 if (overriding_user_agent_changed)
1727 delegate_->UpdateOverridingUserAgent();
1728
creis03b48002015-11-04 00:54:561729 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1730 // one knows the latest NavigationEntry it is showing (whether it has
1731 // committed anything in this navigation or not). This allows things like
1732 // state and title updates from RenderFrames to apply to the latest relevant
1733 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381734 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031735 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381736 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431737
1738 if (navigation_request->IsPrerenderedPageActivation()) {
1739 BroadcastHistoryOffsetAndLength();
Alison Gale47d1537d2024-04-19 21:31:461740 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431741 // is activated. As a result, a "prerenderingchange" event listener sees the
1742 // history.length which is not updated yet. We should guarantee that
1743 // history's length and offset should be updated before a
1744 // "prerenderingchange" event listener runs. One possible approach is to use
1745 // the same IPC which "prerenderingchange" uses, and propagate history's
1746 // length and offset together with that.
1747 }
1748
[email protected]e9ba4472008-09-14 15:42:431749 return true;
initial.commit09911bf2008-07-26 23:55:291750}
1751
[email protected]8ff00d72012-10-23 19:12:211752NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321753 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101754 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241755 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591756 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511757 "ClassifyNavigation");
1758
avi7c6f35e2015-05-08 17:52:381759 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241760 // A new entry. We may or may not have a corresponding pending entry, and
1761 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001762 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491763 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061764 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381765 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241766 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511767 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381768 return NAVIGATION_TYPE_NEW_SUBFRAME;
1769 }
1770
Charlie Reisc0f17d2d2021-01-12 18:52:491771 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381772 DCHECK(!params.history_list_was_cleared);
1773
avi39c1edd32015-06-04 20:06:001774 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381775 // All manual subframes would be did_create_new_entry and handled above, so
1776 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081777 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1778 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381779 }
1780
Rakina Zata Amnif6950d552020-11-24 03:26:101781 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1782 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381783 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1784 // create a new page.
1785
Hayato Ito2ae49442021-07-02 02:59:251786 // This main frame navigation is not a history navigation (since
1787 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1788 // reload or a replacement navigation, which will modify the existing entry.
1789 //
Nasko Oskov332593c2018-08-16 17:21:341790 // TODO(nasko): With error page isolation, reloading an existing session
1791 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491792 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341793 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511794 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491795 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061796 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381797 }
1798
Charlie Reisf8cde712022-10-20 16:25:091799 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521800 // If the SiteInstance of the |pending_entry_| does not match the
1801 // SiteInstance that got committed, treat this as a new navigation with
1802 // replacement. This can happen if back/forward/reload encounters a server
1803 // redirect to a different site or an isolated error page gets successfully
1804 // reloaded into a different SiteInstance.
1805 if (pending_entry_->site_instance() &&
1806 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491807 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061808 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521809 }
creis77c9aa32015-09-25 19:59:421810
Nasko Oskovaee2f862018-06-15 00:05:521811 if (pending_entry_index_ == -1) {
1812 // In this case, we have a pending entry for a load of a new URL but Blink
1813 // didn't do a new navigation (params.did_create_new_entry). First check
1814 // to make sure Blink didn't treat a new cross-process navigation as
1815 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161816 // we must treat it as NEW rather than the converted reload case below,
1817 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451818 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161819 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061820 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521821 }
1822
1823 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161824 // We will create a pending entry, but NavigateWithoutEntry will convert
1825 // it to a reload since it's the same page and not create a new entry for
1826 // it. (The user doesn't want to have a new back/forward entry when they
1827 // do this.) Therefore we want to just ignore the pending entry and go
1828 // back to where we were (the "existing entry").
1829 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061830 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521831 }
avi7c6f35e2015-05-08 17:52:381832 }
1833
Rakina Zata Amni153d5702021-09-13 22:48:001834 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381835 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491836 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1837 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161838 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061839 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381840 }
1841
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121842 if (navigation_request->DidEncounterError() &&
1843 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101844 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381845 // If the renderer was going to a new pending entry that got cleared because
1846 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491847 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381848 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511849 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491850 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061851 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381852 }
1853
Charlie Reisc0f17d2d2021-01-12 18:52:491854 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101855 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511856 trace_return.traced_value()->SetInteger("existing_entry_index",
1857 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381858 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441859 // The renderer has committed a navigation to an entry that no longer
1860 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491861 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061862 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381863 }
1864
avi7c6f35e2015-05-08 17:52:381865 // Since we weeded out "new" navigations above, we know this is an existing
1866 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491867 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061868 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381869}
1870
Rakina Zata Amni3460d382021-10-29 00:43:371871void NavigationControllerImpl::UpdateNavigationEntryDetails(
1872 NavigationEntryImpl* entry,
1873 RenderFrameHostImpl* rfh,
1874 const mojom::DidCommitProvisionalLoadParams& params,
1875 NavigationRequest* request,
1876 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001877 bool is_new_entry,
1878 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371879 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171880 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371881 entry->AddOrUpdateFrameEntry(
1882 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571883 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371884 rfh->GetSiteInstance(), nullptr, params.url,
1885 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171886 Referrer(*params.referrer),
1887 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371888 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171889 request ? request->GetRedirectChain() : redirects, params.page_state,
1890 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371891 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171892 rfh, request && request->IsSameDocument(),
1893 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371894
1895 if (rfh->GetParent()) {
1896 // Only modify the NavigationEntry for main frame navigations.
1897 return;
1898 }
1899 if (entry->update_virtual_url_with_url())
1900 UpdateVirtualURLToURL(entry, params.url);
1901 // Don't use the page type from the pending entry. Some interstitial page
1902 // may have set the type to interstitial. Once we commit, however, the page
1903 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171904 entry->set_page_type((request && request->DidEncounterError())
1905 ? PAGE_TYPE_ERROR
1906 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431907 if (commit_details && commit_details->should_stay_as_initial_entry) {
1908 // Retain the "initial NavigationEntry" status.
1909 if (request->IsSameDocument()) {
1910 // If this is for a same-document navigation, the NavigationEntry must be
1911 // reused and should already be marked as the initial NavigationEntry.
1912 DCHECK(entry->IsInitialEntry());
1913 } else {
1914 // If this is for a cross-document navigation, it can be caused by a
1915 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1916 // "for synchronous about:blank" in the latter case, and also when it is
1917 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1918 // is not for a synchronous about:blank commit.
1919 NavigationEntryImpl::InitialNavigationEntryState new_state =
1920 NavigationEntryImpl::InitialNavigationEntryState::
1921 kInitialNotForSynchronousAboutBlank;
1922 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1923 request->is_synchronous_renderer_commit()) {
1924 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1925 kInitialForSynchronousAboutBlank;
1926 }
1927 entry->set_initial_navigation_entry_state(new_state);
1928 }
1929 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1930 // Remove the "initial NavigationEntry" status.
1931 entry->set_initial_navigation_entry_state(
1932 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001933 }
Rakina Zata Amniddf10502022-01-15 02:56:551934
Rakina Zata Amni3460d382021-10-29 00:43:371935 if (is_new_entry) {
1936 // Some properties of the NavigationEntry are only set when the entry is
1937 // new (we aren't reusing it).
1938 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171939 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:401940 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:011941 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
1942 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:371943 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1944 } else {
1945 // We are reusing the NavigationEntry. The site instance will normally be
1946 // the same except for a few cases:
1947 // 1) session restore, when no site instance will be assigned or
1948 // 2) redirect, when the site instance is reset.
1949 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1950 entry->site_instance() == rfh->GetSiteInstance());
1951 }
1952}
1953
Rakina Zata Amniafd3c6582021-11-30 06:19:171954void NavigationControllerImpl::CreateInitialEntry() {
1955 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031956 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171957 auto params = mojom::DidCommitProvisionalLoadParams::New();
1958 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1959 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1960 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:401961 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:171962 params->http_status_code = 0;
1963 params->url_is_unreachable = false;
1964 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171965 params->post_id = -1;
1966 params->embedding_token = base::UnguessableToken::Create();
1967 params->navigation_token = base::UnguessableToken::Create();
1968 params->did_create_new_entry = true;
1969 params->origin = rfh->GetLastCommittedOrigin();
1970 params->should_update_history = true;
1971 params->item_sequence_number = 0;
1972 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151973 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171974 params->transition = is_in_fenced_frame_tree
1975 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1976 : ui::PAGE_TRANSITION_LINK;
1977 params->referrer = blink::mojom::Referrer::New();
1978
Rakina Zata Amniafd3c6582021-11-30 06:19:171979 auto new_entry = std::make_unique<NavigationEntryImpl>(
1980 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381981 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211982 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1983 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1984 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171985 UpdateNavigationEntryDetails(
1986 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001987 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1988 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171989
1990 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1991 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001992 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171993}
1994
Charlie Reisc0f17d2d2021-01-12 18:52:491995void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321996 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071997 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361998 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441999 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562000 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002001 NavigationRequest* request,
2002 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572003 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372004 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452005 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372006 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522007 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2008 initiator_base_url = request->common_params().initiator_base_url;
2009 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062010
creisf49dfc92016-07-26 17:05:182011 // First check if this is an in-page navigation. If so, clone the current
2012 // entry instead of looking at the pending entry, because the pending entry
2013 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452014 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302015 FrameNavigationEntry* previous_frame_entry =
2016 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452017 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482018 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572019 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082020 rfh->GetSiteInstance(), nullptr, params.url,
2021 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212022 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092023 request->GetRedirectChain(), params.page_state, params.method,
2024 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392025 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302026 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572027 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302028 // FrameNavigationEntry.
2029 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572030 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032031
creisf49dfc92016-07-26 17:05:182032 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032033 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522034 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2035 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572036 // TODO(jam): we had one report of this with a URL that was redirecting to
2037 // only tildes. Until we understand that better, don't copy the cert in
2038 // this case.
2039 new_entry->GetSSL() = SSLStatus();
2040 }
creisf49dfc92016-07-26 17:05:182041
Patrick Monette50e8bd82019-06-13 22:40:452042 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2043 // that |frame_entry| should now have a reference count of exactly 2: one
2044 // due to the local variable |frame_entry|, and another due to |new_entry|
2045 // also retaining one. This should never fail, because it's the main frame.
2046 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182047 }
2048
Harkiran Bolaria59290d62021-03-17 01:53:012049 // If this is an activation navigation from a prerendered page, transfer the
2050 // new entry from an entry already created and stored in the
2051 // NavigationRequest. |new_entry| will not have been set prior to this as
2052 // |is_same_document| is mutually exclusive with
2053 // |IsPrerenderedPageActivation|.
2054 if (request->IsPrerenderedPageActivation()) {
2055 DCHECK(!is_same_document);
2056 DCHECK(!new_entry);
2057 new_entry = request->TakePrerenderNavigationEntry();
2058 DCHECK(new_entry);
2059 }
2060
Charlie Reisc0f17d2d2021-01-12 18:52:492061 // Only make a copy of the pending entry if it is appropriate for the new
2062 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452063 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042064 // 1. The SiteInstance hasn't been assigned to something else.
2065 // 2. The pending entry was intended as a new entry, rather than being a
2066 // history navigation that was interrupted by an unrelated,
2067 // renderer-initiated navigation.
2068 // TODO(csharrison): Investigate whether we can remove some of the coarser
2069 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452070 if (!new_entry && PendingEntryMatchesRequest(request) &&
2071 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342072 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432073 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352074 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432075
Camille Lamy62b826012019-02-26 09:15:472076 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452077 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182078 }
2079
Charlie Reisc0f17d2d2021-01-12 18:52:492080 // For cross-document commits with no matching pending entry, create a new
2081 // entry.
creisf49dfc92016-07-26 17:05:182082 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062083 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072084 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212085 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582086 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452087 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172088 nullptr, // blob_url_loader_factory
2089 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242090
2091 // Find out whether the new entry needs to update its virtual URL on URL
2092 // change and set up the entry accordingly. This is needed to correctly
2093 // update the virtual URL when replaceState is called after a pushState.
2094 GURL url = params.url;
2095 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492096 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412097 // update the virtual URL based on the new URL. For example, this is needed
2098 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2099 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372100 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2101 &url, browser_context_, &needs_update);
2102 new_entry->set_update_virtual_url_with_url(needs_update);
2103
Camille Lamy62b826012019-02-26 09:15:472104 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452105 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432106 }
2107
Alison Gale770f3fc2024-04-27 00:39:582108 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2109 // set for prerendered contents, if any. This is because
2110 // prerendering/activation technically won't be creating a new document.
2111 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2112 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012113 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372114 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2115 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002116 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082117
Harkiran Bolaria59290d62021-03-17 01:53:012118 // history.pushState() is classified as a navigation to a new page, but sets
2119 // is_same_document to true. In this case, we already have the title and
2120 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452121 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012122 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2123 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2124 }
[email protected]3a868f212014-08-09 10:41:192125 }
[email protected]ff64b3e2014-05-31 04:07:332126
[email protected]60d6cca2013-04-30 08:47:132127 DCHECK(!params.history_list_was_cleared || !replace_entry);
2128 // The browser requested to clear the session history when it initiated the
2129 // navigation. Now we know that the renderer has updated its state accordingly
2130 // and it is safe to also clear the browser side history.
2131 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552132 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132133 entries_.clear();
2134 last_committed_entry_index_ = -1;
2135 }
2136
Nasko Oskovaee2f862018-06-15 00:05:522137 // If this is a new navigation with replacement and there is a
2138 // pending_entry_ which matches the navigation reported by the renderer
2139 // process, then it should be the one replaced, so update the
2140 // last_committed_entry_index_ to use it.
2141 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092142 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522143 last_committed_entry_index_ = pending_entry_index_;
2144 }
2145
Alexander Timine3ec4192020-04-20 16:39:402146 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562147 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402148 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052149
Yuzu Saijoa725585f2022-11-28 04:14:032150 // If this is a history navigation and the old entry has an existing
2151 // back/forward cache metrics object, keep using the old one so that the
2152 // reasons logged from the last time the page navigated gets preserved.
2153 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2154 request)) {
2155 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2156 // because some tests do not have a pending entry.
2157 NavigationEntryImpl* entry =
2158 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2159 if (entry && entry->back_forward_cache_metrics()) {
2160 scoped_refptr<BackForwardCacheMetrics> metrics =
2161 entry->TakeBackForwardCacheMetrics();
2162 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2163 }
2164 }
2165
Carlos IL42b416592019-10-07 23:10:362166 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312167 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152168 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432169}
2170
Charlie Reisc0f17d2d2021-01-12 18:52:492171void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322172 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072173 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362174 bool is_same_document,
jam48cea9082017-02-15 06:13:292175 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452176 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002177 bool keep_pending_entry,
2178 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562179 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2180 << "that a last committed entry exists.";
2181
[email protected]e9ba4472008-09-14 15:42:432182 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002183 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432184
Charlie Reis7e2cb6d2021-01-26 01:27:162185 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002186 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162187 // We're guaranteed to have a last committed entry if intended_as_new_entry
2188 // is true.
avicbdc4c12015-07-01 16:07:112189 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162190
2191 // If the NavigationRequest matches a new pending entry and is classified as
2192 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2193 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092194 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162195 // Note: The pending entry will usually have a real ReloadType here, but
2196 // it can still be ReloadType::NONE in cases that
2197 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2198
2199 // If we classified this correctly, the SiteInstance should not have
2200 // changed.
2201 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2202
2203 // For converted reloads, we assign the entry's unique ID to be that of
2204 // the new one. Since this is always the result of a user action, we want
2205 // to dismiss infobars, etc. like a regular user-initiated navigation.
2206 entry->set_unique_id(pending_entry_->GetUniqueID());
2207
2208 // The extra headers may have changed due to reloading with different
2209 // headers.
2210 entry->set_extra_headers(pending_entry_->extra_headers());
2211 }
2212 // Otherwise, this was intended as a new entry but the pending entry was
2213 // lost in the meantime and no new entry was created. We are stuck at the
2214 // last committed entry.
2215
2216 // Even if this is a converted reload from pressing enter in the omnibox,
2217 // the server could redirect, requiring an update to the SSL status. If this
2218 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452219 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162220 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472221 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452222 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162223 }
Rakina Zata Amnif6950d552020-11-24 03:26:102224 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112225 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102226 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b90ce2016-09-01 16:58:162227
eugenebut604866f2017-05-10 21:35:362228 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452229 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362230 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2231 // this was a restored same document navigation entry, then it won't have
2232 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2233 // navigated it.
jam48cea9082017-02-15 06:13:292234 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522235 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2236 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292237 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2238 was_restored) {
2239 entry->GetSSL() = last_entry->GetSSL();
2240 }
2241 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452242 // In rapid back/forward navigations |request| sometimes won't have a cert
2243 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192244 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452245 if (request->GetSSLInfo().has_value() &&
2246 request->GetSSLInfo()->is_valid()) {
2247 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522248 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2249 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192250 entry->GetSSL() = SSLStatus();
2251 }
jam48cea9082017-02-15 06:13:292252 }
avicbdc4c12015-07-01 16:07:112253 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272254 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572255 // navigations that are EXISTING_ENTRY are same-document navigations that
2256 // result in replacement (e.g. history.replaceState(), location.replace(),
2257 // forced replacements for trivial session history contexts). For these
2258 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112259 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102260
Alison Gale81f4f2c72024-04-22 19:33:312261 // TODO(crbug.com/40532777): Set page transition type to
2262 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2263 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2264 // well as to fix the inconsistency with what we report to observers
2265 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102266
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572267 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102268
eugenebut604866f2017-05-10 21:35:362269 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452270 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362271 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472272 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452273 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112274 }
2275 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432276
Rakina Zata Amni3460d382021-10-29 00:43:372277 UpdateNavigationEntryDetails(entry, rfh, params, request,
2278 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002279 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302280
[email protected]5ccd4dc2012-10-24 02:28:142281 // The redirected to page should not inherit the favicon from the previous
2282 // page.
eugenebut604866f2017-05-10 21:35:362283 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482284 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142285
Charlie Reis951f43372023-05-05 00:30:072286 // Update the last committed index to reflect the committed entry. Do this
2287 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2288 // delegate sees the correct committed index when notified of navigation
2289 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2290 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212291 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072292
Peter Boströmd7592132019-01-30 04:50:312293 // We should also usually discard the pending entry if it corresponds to a
2294 // different navigation, since that one is now likely canceled. In rare
2295 // cases, we leave the pending entry for another navigation in place when we
2296 // know it is still ongoing, to avoid a flicker in the omnibox (see
2297 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432298 //
2299 // Note that we need to use the "internal" version since we don't want to
2300 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312301 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002302 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432303}
2304
[email protected]d202a7c2012-01-04 07:53:472305void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322306 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072307 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362308 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472309 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562310 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002311 NavigationRequest* request,
2312 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262313 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2314 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552315 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2316 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112317
[email protected]e9ba4472008-09-14 15:42:432318 // Manual subframe navigations just get the current entry cloned so the user
2319 // can go back or forward to it. The actual subframe information will be
2320 // stored in the page state for each of those entries. This happens out of
2321 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092322 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2323 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382324
Mikel Astizba9cf2fd2017-12-17 10:38:102325 // The DCHECK below documents the fact that we don't know of any situation
2326 // where |replace_entry| is true for subframe navigations. This simplifies
2327 // reasoning about the replacement struct for subframes (see
2328 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2329 DCHECK(!replace_entry);
2330
Patrick Monette50e8bd82019-06-13 22:40:452331 // This FrameNavigationEntry might not end up being used in the
2332 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372333 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452334 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372335 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522336 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2337 initiator_base_url = request->common_params().initiator_base_url;
2338 }
Nate Chapin63db0d12022-01-20 22:03:302339 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2340 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2341 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572342 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302343 if (is_same_document) {
2344 FrameNavigationEntry* previous_frame_entry =
2345 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572346 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302347 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572348 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302349 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572350 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302351 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572352 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302353 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572354 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302355 policy_container_policies->referrer_policy);
2356 }
2357
Patrick Monette50e8bd82019-06-13 22:40:452358 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482359 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572360 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082361 rfh->GetSiteInstance(), nullptr, params.url,
2362 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212363 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2364 request->GetRedirectChain(), params.page_state, params.method,
2365 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572366 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032367
creisce0ef3572017-01-26 17:53:082368 std::unique_ptr<NavigationEntryImpl> new_entry =
2369 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452370 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032371 frame_tree_->root());
creise062d542015-08-25 02:01:552372
Alexander Timine3ec4192020-04-20 16:39:402373 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562374 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402375 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472376
creisce0ef3572017-01-26 17:53:082377 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452378 // to replace, which can happen due to a unique name change. See
2379 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2380 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382381
Dave Tapuska87696ae2021-11-18 18:48:312382 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152383 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432384}
2385
[email protected]d202a7c2012-01-04 07:53:472386bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322387 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072388 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392389 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252390 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002391 NavigationRequest* request,
2392 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292393 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2394 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2395
[email protected]e9ba4472008-09-14 15:42:432396 // We're guaranteed to have a previously committed entry, and we now need to
2397 // handle navigation inside of a subframe in it without creating a new entry.
2398 DCHECK(GetLastCommittedEntry());
2399
creis913c63ce2016-07-16 19:52:522400 // For newly created subframes, we don't need to send a commit notification.
2401 // This is only necessary for history navigations in subframes.
2402 bool send_commit_notification = false;
2403
Rakina Zata Amnif6950d552020-11-24 03:26:102404 // If |nav_entry_id| is non-zero and matches an existing entry, this
2405 // is a history navigation. Update the last committed index accordingly. If
2406 // we don't recognize the |nav_entry_id|, it might be a recently
2407 // pruned entry. We'll handle it below.
2408 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2409 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472410 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062411 // Make sure that a subframe commit isn't changing the main frame's
2412 // origin. Otherwise the renderer process may be confused, leading to a
2413 // URL spoof. We can't check the path since that may change
2414 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572415 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2416 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242417 // We should use checks similar to RenderFrameHostImpl's
2418 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2419 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572420 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2421 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2422 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2423 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522424 current_top_url.DeprecatedGetOriginAsURL() !=
2425 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442426 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512427 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062428 }
creis3cdc3b02015-05-29 23:00:472429
creis913c63ce2016-07-16 19:52:522430 // We only need to discard the pending entry in this history navigation
2431 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062432 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002433 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522434
2435 // History navigations should send a commit notification.
2436 send_commit_notification = true;
avi98405c22015-05-21 20:47:062437 }
[email protected]e9ba4472008-09-14 15:42:432438 }
[email protected]f233e4232013-02-23 00:55:142439
creisce0ef3572017-01-26 17:53:082440 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2441 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372442 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2443 // exists), or we may want to clobber it and create a new one. We update in
2444 // cases where the corresponding FrameNavigationEntry is conceptually similar
2445 // to the document described by the commit params: same-document
2446 // navigations, history traversal to an existing entry, and reloads (including
2447 // a "soft reload" where we navigate to the same url without flagging it as a
2448 // reload). But in the case of a different document that is not logically
2449 // related to the committed FrameNavigationEntry's document (cross-document,
2450 // not same url, not a reload, not a history traversal), we replace rather
2451 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252452 //
Nate Chapin9f169072021-06-09 19:32:372453 // In the case where we update, the FrameNavigationEntry will potentially be
2454 // shared across multiple NavigationEntries, and any updates will be reflected
2455 // in all of those NavigationEntries. In the replace case, any existing
2456 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252457 //
2458 // When navigating away from the initial empty document, we also update rather
2459 // than replace. Either update or replace will overwrite the initial empty
2460 // document state for |last_committed|, but if the FrameNavigationEntry for
2461 // the initial empty document is shared across multiple NavigationEntries (due
2462 // to a navigation in another frame), we want to make sure we overwrite the
2463 // initial empty document state everywhere this FrameNavigationEntry is used,
2464 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452465 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372466 FrameNavigationEntry* last_committed_frame_entry =
2467 last_committed->GetFrameEntry(rfh->frame_tree_node());
2468 NavigationEntryImpl::UpdatePolicy update_policy =
2469 NavigationEntryImpl::UpdatePolicy::kUpdate;
2470 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312471 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372472 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252473 last_committed_frame_entry->url() != params.url &&
2474 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372475 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2476 }
2477
Rakina Zata Amni3460d382021-10-29 00:43:372478 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002479 update_policy, false /* is_new_entry */,
2480 commit_details);
creis625a0c7d2015-03-24 23:17:122481
creis913c63ce2016-07-16 19:52:522482 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432483}
2484
[email protected]d202a7c2012-01-04 07:53:472485int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232486 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032487 for (size_t i = 0; i < entries_.size(); ++i) {
2488 if (entries_[i].get() == entry)
2489 return i;
2490 }
2491 return -1;
[email protected]765b35502008-08-21 00:51:202492}
2493
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572494void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242495 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572496 NavigationControllerImpl* source =
2497 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572498 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382499 DCHECK_EQ(1, GetEntryCount());
2500 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472501 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172502 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572503
Francois Dorayeaace782017-06-21 16:37:242504 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442505 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572506 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572507
Fergal Dalya1d569972021-03-16 03:24:532508 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302509 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532510 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2511 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302512 }
[email protected]4e6419c2010-01-15 04:50:342513
Lukasz Anforowicz0de0f452020-12-02 19:57:152514 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572515}
2516
[email protected]79368982013-11-13 01:11:012517bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022518 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162519 if (last_committed_entry_index_ == -1)
2520 return false;
[email protected]9350602e2013-02-26 23:27:442521
[email protected]474f8512013-05-31 22:31:162522 // We cannot prune if there is a pending entry at an existing entry index.
2523 // It may not commit, so we have to keep the last committed entry, and thus
2524 // there is no sensible place to keep the pending entry. It is ok to have
2525 // a new pending entry, which can optionally commit as a new navigation.
2526 if (pending_entry_index_ != -1)
2527 return false;
2528
[email protected]474f8512013-05-31 22:31:162529 return true;
2530}
2531
[email protected]79368982013-11-13 01:11:012532void NavigationControllerImpl::PruneAllButLastCommitted() {
2533 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162534
avi2b177592014-12-10 02:08:022535 DCHECK_EQ(0, last_committed_entry_index_);
2536 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442537
Hayato Ito2c8c08d02021-06-23 03:38:432538 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442539}
2540
[email protected]79368982013-11-13 01:11:012541void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162542 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012543 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262544
Nate Chapin9eb16be72022-09-23 22:54:312545 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2546
[email protected]474f8512013-05-31 22:31:162547 // Erase all entries but the last committed entry. There may still be a
2548 // new pending entry after this.
2549 entries_.erase(entries_.begin(),
2550 entries_.begin() + last_committed_entry_index_);
2551 entries_.erase(entries_.begin() + 1, entries_.end());
2552 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262553}
2554
Christian Dullweber1af31e62018-02-22 11:49:482555void NavigationControllerImpl::DeleteNavigationEntries(
2556 const DeletionPredicate& deletionPredicate) {
2557 // It is up to callers to check the invariants before calling this.
2558 CHECK(CanPruneAllButLastCommitted());
2559 std::vector<int> delete_indices;
2560 for (size_t i = 0; i < entries_.size(); i++) {
2561 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572562 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482563 delete_indices.push_back(i);
2564 }
2565 }
2566 if (delete_indices.empty())
2567 return;
2568
2569 if (delete_indices.size() == GetEntryCount() - 1U) {
2570 PruneAllButLastCommitted();
2571 } else {
2572 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382573 for (const auto& index : base::Reversed(delete_indices)) {
2574 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482575 }
Hayato Ito2c8c08d02021-06-23 03:38:432576 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482577 }
2578 delegate()->NotifyNavigationEntriesDeleted();
2579}
2580
Carlos Caballero35ce710c2019-09-19 10:59:452581BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2582 return back_forward_cache_;
2583}
2584
William Liu055a3542023-04-02 17:21:192585NavigationEntryScreenshotCache*
2586NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212587 CHECK(frame_tree_->is_primary());
William Liu055a3542023-04-02 17:21:192588 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2589 nav_entry_screenshot_cache_ =
2590 std::make_unique<NavigationEntryScreenshotCache>(
2591 BrowserContextImpl::From(browser_context_)
2592 ->GetNavigationEntryScreenshotManager()
2593 ->GetSafeRef(),
2594 this);
2595 }
2596 return nav_entry_screenshot_cache_.get();
2597}
2598
clamy987a3752018-05-03 17:36:262599void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2600 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2601 // progress, since this will cause a use-after-free. (We only allow this
2602 // when the tab is being destroyed for shutdown, since it won't return to
2603 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032604 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262605
2606 if (was_failure && pending_entry_) {
2607 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2608 } else {
2609 failed_pending_entry_id_ = 0;
2610 }
2611
2612 if (pending_entry_) {
2613 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332614 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262615 pending_entry_index_ = -1;
2616 pending_entry_ = nullptr;
2617 }
arthursonzogni66f711c2019-10-08 14:40:362618
2619 // Ensure any refs to the current pending entry are ignored if they get
2620 // deleted, by clearing the set of known refs. All future pending entries will
2621 // only be affected by new refs.
2622 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262623}
2624
2625void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2626 if (pending_entry_)
2627 pending_entry_->set_ssl_error(error);
2628}
2629
Xiaohan Wang7f8052e02022-01-14 18:44:282630#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422631// static
2632bool NavigationControllerImpl::ValidateDataURLAsString(
2633 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2634 if (!data_url_as_string)
2635 return false;
2636
2637 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2638 return false;
2639
2640 // The number of characters that is enough for validating a data: URI.
2641 // From the GURL's POV, the only important part here is scheme, it doesn't
2642 // check the actual content. Thus we can take only the prefix of the url, to
2643 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562644 constexpr size_t kDataUriPrefixMaxLen = 64;
2645 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2646 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422647 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2648 return false;
2649
2650 return true;
2651}
2652#endif
2653
Shivani Sharma194877032019-03-07 17:52:472654void NavigationControllerImpl::NotifyUserActivation() {
2655 // When a user activation occurs, ensure that all adjacent entries for the
2656 // same document clear their skippable bit, so that the history manipulation
2657 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012658 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172659 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012660 // If the value of CanGoBack changes as a result of making some entries
2661 // non-skippable, then we must let the delegate know to update its UI state.
2662 // See https://crbug.com/1477784.
2663 if (!can_go_back && CanGoBack()) {
2664 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2665 }
Shivani Sharma194877032019-03-07 17:52:472666}
2667
clamy987a3752018-05-03 17:36:262668bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2669 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332670 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2671 blink::LocalFrameToken initiator_frame_token,
2672 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262673 NavigationEntryImpl* entry =
2674 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2675 if (!entry)
2676 return false;
2677
2678 FrameNavigationEntry* frame_entry =
2679 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2680 if (!frame_entry)
2681 return false;
2682
Camille Lamy5193caa2018-10-12 11:59:422683 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572684 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232685 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332686 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2687 initiator_process_id);
clamyea99ea12018-05-28 13:54:232688
2689 if (!request)
2690 return false;
2691
arthursonzognif046d4a2019-12-12 19:08:102692 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412693
Rakina Zata Amni1c83b082023-02-08 01:09:002694 SCOPED_CRASH_KEY_STRING256(
2695 "Bug1400009", "req_url",
2696 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2697 SCOPED_CRASH_KEY_NUMBER(
2698 "Bug1400009", "nav_entry_si",
2699 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2700 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2701 frame_entry->site_instance()
2702 ? ((int)frame_entry->site_instance()->GetId())
2703 : -1);
2704 bool has_sig =
2705 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2706 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2707 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2708 has_sig ? (!!frame_tree_->GetRenderViewHost(
2709 frame_entry->site_instance()->group()))
2710 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052711 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2712 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232713
2714 return true;
clamy987a3752018-05-03 17:36:262715}
2716
Tsuyoshi Horo52fd08e2020-07-07 07:03:452717bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2718 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2719 if (!entry)
2720 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432721
2722 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2723 // We should never navigate to an existing initial NavigationEntry that is
2724 // the initial NavigationEntry for the initial empty document that hasn't
2725 // been overridden by the synchronous about:blank commit, to preserve
2726 // legacy behavior where trying to reload when the main frame is on the
2727 // initial empty document won't result in a navigation. See also
2728 // https://crbug.com/1277414.
2729 return false;
2730 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452731 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2732 if (!frame_entry)
2733 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142734 ReloadType reload_type = ReloadType::NORMAL;
2735 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452736 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142737 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452738 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432739 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372740 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332741 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452742 if (!request)
2743 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052744 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452745 return true;
2746}
2747
clamy987a3752018-05-03 17:36:262748void NavigationControllerImpl::NavigateFromFrameProxy(
2749 RenderFrameHostImpl* render_frame_host,
2750 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022751 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452752 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372753 const std::optional<url::Origin>& initiator_origin,
2754 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262755 bool is_renderer_initiated,
2756 SiteInstance* source_site_instance,
2757 const Referrer& referrer,
2758 ui::PageTransition page_transition,
2759 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252760 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262761 const std::string& method,
2762 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092763 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142764 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212765 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502766 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372767 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292768 blink::mojom::NavigationInitiatorActivationAndAdStatus
2769 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222770 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492771 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462772 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452773 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582774 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032775 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342776 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372777 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582778 if (is_renderer_initiated)
2779 DCHECK(initiator_origin.has_value());
2780
clamy987a3752018-05-03 17:36:262781 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582782
Rakina Zata Amni2322f4f82022-01-24 13:24:242783 // Don't allow an entry replacement if there is no entry to replace.
2784 // http://crbug.com/457149
2785 if (GetEntryCount() == 0)
2786 should_replace_current_entry = false;
2787
clamy987a3752018-05-03 17:36:262788 // Create a NavigationEntry for the transfer, without making it the pending
2789 // entry. Subframe transfers should have a clone of the last committed entry
2790 // with a FrameNavigationEntry for the target frame. Main frame transfers
2791 // should have a new NavigationEntry.
2792 // TODO(creis): Make this unnecessary by creating (and validating) the params
2793 // directly, passing them to the destination RenderFrameHost. See
2794 // https://crbug.com/536906.
2795 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262796 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262797 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452798 DCHECK(GetLastCommittedEntry());
2799 entry = GetLastCommittedEntry()->Clone();
2800 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172801 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2802 // Renderer-initiated navigation that target a remote frame are currently
2803 // classified as browser-initiated when this one has already navigated.
2804 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372805 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2806 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2807 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2808 // same-document navigation), they will still be present in the
2809 // committed NavigationEntry that will be referenced to construct the new
2810 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262811 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082812 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582813 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372814 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212815 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152816 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262817 } else {
2818 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172819 // If `node` is the outermost main frame, it rewrites a virtual url in order
2820 // to adjust the original input url if needed. For inner frames such as
2821 // fenced frames or subframes, they don't rewrite urls as the urls are not
2822 // input urls by users.
2823 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372824 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322825 if (source_site_instance && source_site_instance->HasProcess()) {
2826 source_process_site_url =
2827 source_site_instance->GetProcess()->GetProcessLock().site_url();
2828 }
clamy987a3752018-05-03 17:36:262829 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212830 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322831 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212832 extra_headers, browser_context_, blob_url_loader_factory,
2833 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262834 entry->root_node()->frame_entry->set_source_site_instance(
2835 static_cast<SiteInstanceImpl*>(source_site_instance));
2836 entry->root_node()->frame_entry->set_method(method);
2837 }
clamy987a3752018-05-03 17:36:262838
Camille Lamy5193caa2018-10-12 11:59:422839 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452840 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262841 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422842 override_user_agent = true;
clamy987a3752018-05-03 17:36:262843 }
2844 // TODO(creis): Set user gesture and intent received timestamp on Android.
2845
2846 // We may not have successfully added the FrameNavigationEntry to |entry|
2847 // above (per https://crbug.com/608402), in which case we create it from
2848 // scratch. This works because we do not depend on |frame_entry| being inside
2849 // |entry| during NavigateToEntry. This will go away when we shortcut this
2850 // further in https://crbug.com/536906.
2851 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2852 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452853 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082854 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582855 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372856 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212857 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152858 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572859 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262860 }
2861
Camille Lamy5193caa2018-10-12 11:59:422862 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022863 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452864 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292865 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212866 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422867 params.source_site_instance = source_site_instance;
2868 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2869 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032870 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422871 params.referrer = referrer;
2872 /* params.redirect_chain: skip */
2873 params.extra_headers = extra_headers;
2874 params.is_renderer_initiated = is_renderer_initiated;
2875 params.override_user_agent = UA_OVERRIDE_INHERIT;
2876 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542877 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422878 /* params.data_url_as_string: skip */
2879 params.post_data = post_body;
2880 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582881 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422882 /* params.frame_name: skip */
2883 // TODO(clamy): See if user gesture should be propagated to this function.
2884 params.has_user_gesture = false;
2885 params.should_clear_history_list = false;
2886 params.started_from_context_menu = false;
2887 /* params.navigation_ui_data: skip */
2888 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222889 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542890 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212891 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412892 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502893 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292894 params.initiator_activation_and_ad_status =
2895 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032896 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422897
2898 std::unique_ptr<NavigationRequest> request =
2899 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032900 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142901 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392902 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492903 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582904 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:342905 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232906
2907 if (!request)
2908 return;
2909
Garrett Tanzerbb8db412022-09-27 21:59:462910 // Force the navigation to take place in a new browsing instance.
2911 // This is used by _unfencedTop in fenced frames to ensure that navigations
2912 // leaving the fenced context create a new browsing instance.
2913 if (force_new_browsing_instance) {
2914 request->coop_status().ForceBrowsingInstanceSwap();
2915 }
2916
Arthur Hemery948742762019-09-18 10:06:242917 // At this stage we are proceeding with this navigation. If this was renderer
2918 // initiated with user gesture, we need to make sure we clear up potential
2919 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2920 DiscardNonCommittedEntries();
2921
Lukasz Anforowicz9ee83c272020-12-01 20:14:052922 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262923}
2924
[email protected]d1198fd2012-08-13 22:50:192925void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252926 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212927 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192928 if (!session_storage_namespace)
2929 return;
2930
2931 // We can't overwrite an existing SessionStorage without violating spec.
2932 // Attempts to do so may give a tab access to another tab's session storage
2933 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152934 bool successful_insert =
2935 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252936 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052937 static_cast<SessionStorageNamespaceImpl*>(
2938 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302939 .second;
2940 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192941}
2942
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572943bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452944 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032945 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462946}
2947
Aran Gilman37d11632019-10-08 23:07:152948SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252949 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302950 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252951 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032952 DOMStorageContextWrapper* context_wrapper =
2953 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2954
2955 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252956 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032957 if (it != session_storage_namespace_map_.end()) {
2958 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152959 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2960 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472961
michaelnbacbcbd2016-02-09 00:32:032962 return it->second.get();
2963 }
2964
2965 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102966 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2967 SessionStorageNamespaceImpl::Create(context_wrapper);
2968 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2969 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252970 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102971 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302972
Daniel Murphy31bbb8b12018-02-07 21:44:102973 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302974}
2975
2976SessionStorageNamespace*
2977NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252978 return GetSessionStorageNamespace(
2979 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302980}
2981
2982const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572983NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302984 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552985}
[email protected]d202a7c2012-01-04 07:53:472986
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572987bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562988 return needs_reload_;
2989}
[email protected]a26023822011-12-29 00:23:552990
[email protected]46bb5e9c2013-10-03 22:16:472991void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412992 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2993}
2994
2995void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472996 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412997 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542998
2999 if (last_committed_entry_index_ != -1) {
3000 entries_[last_committed_entry_index_]->SetTransitionType(
3001 ui::PAGE_TRANSITION_RELOAD);
3002 }
[email protected]46bb5e9c2013-10-03 22:16:473003}
3004
[email protected]d202a7c2012-01-04 07:53:473005void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573006 DCHECK_LT(index, GetEntryCount());
3007 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313008 DiscardNonCommittedEntries();
3009
Nate Chapin9eb16be72022-09-23 22:54:313010 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313011 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123012 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313013 last_committed_entry_index_--;
3014}
3015
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573016NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273017 // If there is no pending_entry_, there should be no pending_entry_index_.
3018 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3019
3020 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363021 // at that index. An exception is while a reload of a post commit error page
3022 // is ongoing; in that case pending entry will point to the entry replaced
3023 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273024 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363025 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3026 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273027
[email protected]022af742011-12-28 18:37:253028 return pending_entry_;
3029}
3030
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573031int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273032 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273033 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553034 return pending_entry_index_;
3035}
3036
avi25764702015-06-23 15:43:373037void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573038 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363039 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313040 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003041 bool in_fenced_frame_tree,
3042 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313043 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3044 // set because:
3045 // 1) They don't influence the history of the outer page.
3046 // 2) They are always replace only navigation (there is always only one entry
3047 // in their history stack).
3048 // 3) Are not top level navigations and appear similar to iframes.
3049 // Navigations of the fenced frame might create a new NavigationEntry, which
3050 // will call this function. Non fenced frame navigations will never have
3051 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3052 // InsertOrReplaceEntry.
3053 DCHECK_EQ(in_fenced_frame_tree,
3054 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3055 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203056
avi5cad4912015-06-19 05:25:443057 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3058 // need to keep continuity with the pending entry, so copy the pending entry's
3059 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3060 // then the renderer navigated on its own, independent of the pending entry,
3061 // so don't copy anything.
3062 if (pending_entry_ && pending_entry_index_ == -1)
3063 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203064
Rakina Zata Amnia4e27222021-12-22 01:05:003065 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203066
creisee17e932015-07-17 17:56:223067 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453068 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103069 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573070 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363071 // If the new entry is a post-commit error page, we store the current last
3072 // committed entry to the side so that we can put it back when navigating
3073 // away from the error.
3074 if (was_post_commit_error) {
3075 DCHECK(!entry_replaced_by_post_commit_error_);
3076 entry_replaced_by_post_commit_error_ =
3077 std::move(entries_[last_committed_entry_index_]);
3078 }
dcheng36b6aec92015-12-26 06:16:363079 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223080 return;
3081 }
[email protected]765b35502008-08-21 00:51:203082
creis37979a62015-08-04 19:48:183083 // We shouldn't see replace == true when there's no committed entries.
3084 DCHECK(!replace);
3085
Michael Thiessen9b14d512019-09-23 21:19:473086 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203087
Shivani Sharmad8c8d652019-02-13 17:27:573088 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203089
dcheng36b6aec92015-12-26 06:16:363090 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203091 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293092}
3093
Shivani Sharmad8c8d652019-02-13 17:27:573094void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163095 if (entries_.size() < max_entry_count())
3096 return;
3097
3098 DCHECK_EQ(max_entry_count(), entries_.size());
3099 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573100 CHECK_EQ(pending_entry_index_, -1);
3101
3102 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423103 // Retrieve the oldest skippable entry.
3104 for (; index < GetEntryCount(); index++) {
3105 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3106 break;
Shivani Sharmad8c8d652019-02-13 17:27:573107 }
3108
3109 // If there is no skippable entry or if it is the last committed entry then
3110 // fall back to pruning the oldest entry. It is not safe to prune the last
3111 // committed entry.
3112 if (index == GetEntryCount() || index == last_committed_entry_index_)
3113 index = 0;
3114
3115 bool should_succeed = RemoveEntryAtIndex(index);
3116 DCHECK_EQ(true, should_succeed);
3117
3118 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253119}
3120
William Liu1ea335752024-08-06 15:03:303121std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273122NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163123 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203124 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373125 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133126 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203127 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503128 TRACE_EVENT0("navigation",
3129 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273130 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023131 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363132 if (pending_entry_index_ != -1) {
3133 // The pending entry may not be in entries_ if a post-commit error page is
3134 // showing.
3135 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3136 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3137 }
Gyuyoung Kim107c2a02021-04-13 01:49:303138 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573139 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013140 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033141 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573142 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133143 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3144 // the same as the top level frame being navigated.
3145 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373146 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133147 }
Arthur Sonzogni620cec62018-12-13 13:08:573148
[email protected]83c2e232011-10-07 21:36:463149 // If we were navigating to a slow-to-commit page, and the user performs
3150 // a session history navigation to the last committed page, RenderViewHost
3151 // will force the throbber to start, but WebKit will essentially ignore the
3152 // navigation, and won't send a message to stop the throbber. To prevent this
3153 // from happening, we drop the navigation here and stop the slow-to-commit
3154 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023155 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083156 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273157 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033158 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123159
[email protected]83c2e232011-10-07 21:36:463160 DiscardNonCommittedEntries();
William Liu1ea335752024-08-06 15:03:303161 return {};
[email protected]83c2e232011-10-07 21:36:463162 }
3163
Arthur Sonzognic686e8f2024-01-11 08:36:373164 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333165 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3166 if (initiator_rfh) {
3167 initiator_frame_token = initiator_rfh->GetFrameToken();
3168 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3169 DCHECK(initiator_frame_token);
3170 }
3171
creisce0ef3572017-01-26 17:53:083172 // Compare FrameNavigationEntries to see which frames in the tree need to be
3173 // navigated.
clamy3cb9bea92018-07-10 12:42:023174 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3175 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333176 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3177 initiator_process_id, soft_navigation_heuristics_task_id,
3178 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303179
3180 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573181 // We were unable to match any frames to navigate. This can happen if a
3182 // history navigation targets a subframe that no longer exists
3183 // (https://crbug.com/705550). In this case, we need to update the current
3184 // history entry to the pending one but keep the main document loaded. We
3185 // also need to ensure that observers are informed about the updated
3186 // current history entry (e.g., for greying out back/forward buttons), and
3187 // that renderer processes update their history offsets. The easiest way
3188 // to do all that is to schedule a "redundant" same-document navigation in
3189 // the main frame.
3190 //
3191 // Note that we don't want to remove this history entry, as it might still
3192 // be valid later, since a frame that it's targeting may be recreated.
3193 //
3194 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3195 // need to repeat history navigations until finding the one that works.
3196 // Consider changing this behavior to keep looking for the first valid
3197 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023198 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423199 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573200 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573201 ReloadType::NONE /* reload_type */,
3202 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433203 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333204 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023205 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573206 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023207 DiscardPendingEntry(false);
William Liu1ea335752024-08-06 15:03:303208 return {};
clamy3cb9bea92018-07-10 12:42:023209 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573210 same_document_loads.push_back(std::move(navigation_request));
3211
3212 // Sanity check that we never take this branch for any kinds of reloads,
3213 // as those should've queued a different-document load in the main frame.
3214 DCHECK(!is_forced_reload);
3215 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303216 }
3217
Nate Chapinbf682fa32022-09-26 22:41:203218 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163219 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203220 if (initiator_rfh && initiator_rfh->IsSandboxed(
3221 network::mojom::WebSandboxFlags::kTopNavigation)) {
3222 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3223 initiator_rfh, same_document_loads) &&
3224 DoesSandboxNavigationStayWithinSubtree(
3225 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503226 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163227 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203228 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3229 initiator_rfh,
3230 navigates_inside_tree
3231 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3232 : blink::mojom::WebFeature::
3233 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523234
3235 // If the navigation occurred outside the tree discard it because
3236 // the sandboxed frame didn't have permission to navigate outside
3237 // its tree. If it is possible that the navigation is both inside and
3238 // outside the frame tree and we discard it entirely because we don't
3239 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143240 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203241 // If a |navigation_api_key| was provided, this navigation originated from
3242 // the navigation API. Notify the renderer that the navigation was
3243 // cancelled so the navigation API can fire an error event and reject the
3244 // relevant promise.
3245 if (navigation_api_key) {
3246 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3247 *navigation_api_key,
3248 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3249 }
Dave Tapuska855c1e12019-08-23 20:45:523250 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133251
3252 for (auto& unused_request : same_document_loads) {
3253 unused_request->set_navigation_discard_reason(
3254 NavigationDiscardReason::kNeverStarted);
3255 }
3256 for (auto& unused_request : different_document_loads) {
3257 unused_request->set_navigation_discard_reason(
3258 NavigationDiscardReason::kNeverStarted);
3259 }
William Liu1ea335752024-08-06 15:03:303260 return {};
Dave Tapuska855c1e12019-08-23 20:45:523261 }
Dave Tapuska8bfd84c2019-03-26 20:47:163262 }
3263
Nate Chapin6c43c022023-02-13 23:32:423264 // If it is possible that this traverse may involve a same-document navigation
3265 // in the initiator and there is a Navigation API key involved, then we may
3266 // need to notify the initiator if it fails. (The early returns above either
3267 // do not involve these cases or already notify the initiator.)
3268 // The event only needs to fire for the initiator, and only if the initiator
3269 // itself is performing a same-document navigation (because the event will not
3270 // fire if it navigates cross-document).
3271 if (navigation_api_key) {
3272 for (auto& item : same_document_loads) {
3273 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3274 item->set_pending_navigation_api_key(*navigation_api_key);
3275 break;
3276 }
3277 }
3278 }
3279
Carlos Caballero539a421c2020-07-06 10:25:573280 // BackForwardCache:
3281 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563282 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573283 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3284 DCHECK_EQ(reload_type, ReloadType::NONE);
3285 auto navigation_request = CreateNavigationRequestFromEntry(
3286 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3287 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333288 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3289 initiator_process_id);
William Liuec04e382024-05-23 18:03:273290 base::WeakPtr<NavigationRequest> request = navigation_request->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053291 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Rakina Zata Amni58681c62024-06-25 06:32:133292
3293 for (auto& unused_request : same_document_loads) {
3294 unused_request->set_navigation_discard_reason(
3295 NavigationDiscardReason::kNeverStarted);
3296 }
3297 for (auto& unused_request : different_document_loads) {
3298 unused_request->set_navigation_discard_reason(
3299 NavigationDiscardReason::kNeverStarted);
3300 }
3301
William Liu1ea335752024-08-06 15:03:303302 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_request;
3303 if (request) {
3304 bf_cache_request.push_back(std::move(request));
3305 }
3306 return bf_cache_request;
Carlos Caballero539a421c2020-07-06 10:25:573307 }
3308
3309 // History navigation might try to reuse a specific BrowsingInstance, already
3310 // used by a page in the cache. To avoid having two different main frames that
3311 // live in the same BrowsingInstance, evict the all pages with this
3312 // BrowsingInstance from the cache.
3313 //
3314 // For example, take the following scenario:
3315 //
3316 // A1 = Some page on a.com
3317 // A2 = Some other page on a.com
3318 // B3 = An uncacheable page on b.com
3319 //
3320 // Then the following navigations occur:
3321 // A1->A2->B3->A1
3322 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3323 // take its place) and A1 will be created in the same BrowsingInstance (and
3324 // SiteInstance), as A2.
3325 //
3326 // If we didn't do anything, both A1 and A2 would remain alive in the same
3327 // BrowsingInstance/SiteInstance, which is unsupported by
3328 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3329 // A2 from the cache.
3330 if (pending_entry_->site_instance()) {
3331 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3332 pending_entry_->site_instance());
3333 }
3334
Rakina Zata Amnid605d462022-06-01 10:17:033335 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3336 pending_entry_ && pending_entry_->IsRestored());
3337 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3338 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3339 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3340 pending_entry_index_);
3341 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3342 last_committed_entry_index_);
3343 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3344 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3345 pending_entry_ && pending_entry_->IsInitialEntry());
3346 SCOPED_CRASH_KEY_BOOL(
3347 "nav_reentrancy", "pending_entry_initial2",
3348 pending_entry_ &&
3349 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3350 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3351 IsInitialNavigation());
3352 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3353 IsInitialBlankNavigation());
3354 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3355 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3356 (int)pending_reload_);
3357
clamy3cb9bea92018-07-10 12:42:023358 // This call does not support re-entrancy. See http://crbug.com/347742.
3359 CHECK(!in_navigate_to_pending_entry_);
3360 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303361
Rakina Zata Amnid605d462022-06-01 10:17:033362 // If the navigation-reentrancy is caused by calling
3363 // NavigateToExistingPendingEntry twice, this will note the previous call's
3364 // pending entry's ID.
3365 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3366 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3367
arthursonzogni66f711c2019-10-08 14:40:363368 // It is not possible to delete the pending NavigationEntry while navigating
3369 // to it. Grab a reference to delay potential deletion until the end of this
3370 // function.
3371 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3372
Nate Chapin154b14b2023-02-17 18:28:163373 // If there is a main-frame same-document history navigation, we may defer
3374 // the subframe history navigations in order to give JS in the main frame the
3375 // opportunity to cancel the entire traverse via the navigate event. In that
3376 // case, we need to stash the main frame request's navigation token on the
3377 // subframes, so they can look up the main frame request and defer themselves
3378 // until it completes.
3379 if (!same_document_loads.empty() &&
3380 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3381 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3382 // The token will only be returned in cases where deferring the navigation
3383 // is necessary.
3384 if (auto main_frame_same_document_token =
3385 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3386 for (auto& item : same_document_loads) {
3387 if (item.get() != main_frame_request) {
3388 item->set_main_frame_same_document_history_token(
3389 main_frame_same_document_token);
3390 }
3391 }
3392 for (auto& item : different_document_loads) {
3393 item->set_main_frame_same_document_history_token(
3394 main_frame_same_document_token);
3395 }
3396 }
3397 }
3398
William Liu122754942024-01-18 22:34:393399 if (!initiator_rfh) {
3400 // A browser-initiated navigation won't have a `initiator_rfh`.
3401 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3402 different_document_loads, same_document_loads);
3403 }
3404
William Liu1ea335752024-08-06 15:03:303405 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3406 all_requests.reserve(same_document_loads.size() +
3407 different_document_loads.size());
3408 bool seen_primary_main_frame_request = false;
3409
creis4e2ecb72015-06-20 00:46:303410 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023411 for (auto& item : same_document_loads) {
3412 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273413 // The request could be destroyed before `navigator().Navigate()` returns.
3414 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053415 frame->navigator().Navigate(std::move(item), reload_type);
William Liu1ea335752024-08-06 15:03:303416 if (request) {
3417 // Can only have one primary main frame request.
3418 CHECK(!seen_primary_main_frame_request ||
3419 !request->IsInPrimaryMainFrame());
3420 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3421 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273422 }
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 Liu1ea335752024-08-06 15:03:303428 if (request) {
3429 // Can only have one primary main frame request.
3430 CHECK(!seen_primary_main_frame_request ||
3431 !request->IsInPrimaryMainFrame());
3432 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3433 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273434 }
creis4e2ecb72015-06-20 00:46:303435 }
clamy3cb9bea92018-07-10 12:42:023436
3437 in_navigate_to_pending_entry_ = false;
William Liuec04e382024-05-23 18:03:273438
William Liu1ea335752024-08-06 15:03:303439 return all_requests;
creis4e2ecb72015-06-20 00:46:303440}
3441
Alex Moshchuk3a4e77a2020-05-29 21:32:573442NavigationControllerImpl::HistoryNavigationAction
3443NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303444 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573445 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423446 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583447 // Only active and prerendered documents are allowed to navigate in their
3448 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423449 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013450 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583451 // - If the document is in pending deletion, the browser already committed
3452 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3453 // - If the document is in back-forward cache, it's not allowed to navigate
3454 // as it should remain frozen. Ignore the request and evict the document
3455 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423456 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583457 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423458 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113459 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3460 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423461 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113462 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423463 }
arthursonzogni03f76152019-02-12 10:35:203464
Alex Moshchuk3a4e77a2020-05-29 21:32:573465 // Reloads should result in a different-document load. Note that reloads may
3466 // also happen via the |needs_reload_| mechanism where the reload_type is
3467 // NONE, so detect this by comparing whether we're going to the same
3468 // entry that we're currently on. Similarly to above, only main frames
3469 // should reach this. Note that subframes support reloads, but that's done
3470 // via a different path that doesn't involve FindFramesToNavigate (see
3471 // RenderFrameHost::Reload()).
3472 if (reload_type != ReloadType::NONE ||
3473 pending_entry_index_ == last_committed_entry_index_) {
3474 DCHECK(frame->IsMainFrame());
3475 return HistoryNavigationAction::kDifferentDocument;
3476 }
3477
Alex Moshchuk47d1a4bd2020-06-01 22:15:343478 // If there is no new FrameNavigationEntry for the frame, ignore the
3479 // load. For example, this may happen when going back to an entry before a
3480 // frame was created. Suppose we commit a same-document navigation that also
3481 // results in adding a new subframe somewhere in the tree. If we go back,
3482 // the new subframe will be missing a FrameNavigationEntry in the previous
3483 // NavigationEntry, but we shouldn't delete or change what's loaded in
3484 // it.
3485 //
Alex Moshchuke65c39272020-06-03 17:55:373486 // Note that in this case, there is no need to keep looking for navigations
3487 // in subframes, which would be missing FrameNavigationEntries as well.
3488 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343489 // It's important to check this before checking |old_item| below, since both
3490 // might be null, and in that case we still shouldn't change what's loaded in
3491 // this frame. Note that scheduling any loads assumes that |new_item| is
3492 // non-null. See https://crbug.com/1088354.
3493 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3494 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373495 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343496
Charlie Reisa474fb62022-03-17 02:31:363497 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3498 // which history item it is currently on, since this may be different than the
3499 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3500 // (e.g., if a history navigation is targeting multiple frames and only some
3501 // have committed so far).
creis4e2ecb72015-06-20 00:46:303502 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363503 frame->current_frame_host()->last_committed_frame_entry();
3504 if (!old_item) {
3505 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3506 // fall back to the last committed NavigationEntry's record for this frame.
3507 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583508 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363509 // accurate FrameNavigationEntry and eliminate this case.
3510 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3511 }
3512 // If neither approach finds a FrameNavigationEntry, schedule a
3513 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583514 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573515 if (!old_item)
3516 return HistoryNavigationAction::kDifferentDocument;
3517
Alex Moshchuk3a4e77a2020-05-29 21:32:573518 // If the new item is not in the same SiteInstance, schedule a
3519 // different-document load. Newly restored items may not have a SiteInstance
3520 // yet, in which case it will be assigned on first commit.
3521 if (new_item->site_instance() &&
3522 new_item->site_instance() != old_item->site_instance())
3523 return HistoryNavigationAction::kDifferentDocument;
3524
3525 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313526 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3527 // that we do this even if the history navigation would not be modifying this
3528 // frame were it live.
3529 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573530 return HistoryNavigationAction::kDifferentDocument;
3531
3532 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313533 // Starting a navigation after a crash early-promotes the speculative
3534 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3535 // committed yet, so we can not possibly perform a same-document history
3536 // navigation. The frame would need to be reloaded with a cross-document
3537 // navigation.
3538 if (!frame->current_frame_host()->has_committed_any_navigation())
3539 return HistoryNavigationAction::kDifferentDocument;
3540
creis54131692016-08-12 18:32:253541 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493542 // sequence number but different item sequence number.
3543 if (new_item->document_sequence_number() ==
3544 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573545 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493546 }
avib48cb312016-05-05 21:35:003547
Alex Moshchuk3a4e77a2020-05-29 21:32:573548 // Otherwise, if both item and document sequence numbers differ, this
3549 // should be a different document load.
3550 return HistoryNavigationAction::kDifferentDocument;
3551 }
3552
3553 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373554 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573555 DCHECK_EQ(new_item->document_sequence_number(),
3556 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373557 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573558}
3559
3560void NavigationControllerImpl::FindFramesToNavigate(
3561 FrameTreeNode* frame,
3562 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373563 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333564 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373565 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133566 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573567 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3568 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3569 DCHECK(pending_entry_);
3570 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3571
3572 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3573
3574 if (action == HistoryNavigationAction::kSameDocument) {
3575 std::unique_ptr<NavigationRequest> navigation_request =
3576 CreateNavigationRequestFromEntry(
3577 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133578 /*is_same_document_history_load=*/true,
3579 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333580 initiator_frame_token, initiator_process_id,
3581 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573582 if (navigation_request) {
3583 // Only add the request if was properly created. It's possible for the
3584 // creation to fail in certain cases, e.g. when the URL is invalid.
3585 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303586 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573587 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473588 std::unique_ptr<NavigationRequest> navigation_request =
3589 CreateNavigationRequestFromEntry(
3590 frame, pending_entry_, new_item, reload_type,
3591 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433592 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333593 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473594 if (navigation_request) {
3595 // Only add the request if was properly created. It's possible for the
3596 // creation to fail in certain cases, e.g. when the URL is invalid.
3597 different_document_loads->push_back(std::move(navigation_request));
3598 }
3599 // For a different document, the subframes will be destroyed, so there's
3600 // no need to consider them.
3601 return;
Alex Moshchuke65c39272020-06-03 17:55:373602 } else if (action == HistoryNavigationAction::kStopLooking) {
3603 return;
creis4e2ecb72015-06-20 00:46:303604 }
3605
Yoav Weiss8c573952022-11-17 17:35:133606 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3607 // we currently only support soft navigation heuristics for the top level
3608 // frame.
creis4e2ecb72015-06-20 00:46:303609 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333610 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3611 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373612 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433613 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303614 }
3615}
3616
Harkiran Bolariaba823e42021-05-21 18:30:363617base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243618 const LoadURLParams& params) {
3619 // Find the appropriate FrameTreeNode.
3620 FrameTreeNode* node = nullptr;
3621 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3622 !params.frame_name.empty()) {
3623 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033624 ? frame_tree_->FindByID(params.frame_tree_node_id)
3625 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503626 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243627 }
3628
3629 // If no FrameTreeNode was specified, navigate the main frame.
3630 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033631 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243632
Camille Lamy5193caa2018-10-12 11:59:423633 // Compute overrides to the LoadURLParams for |override_user_agent|,
3634 // |should_replace_current_entry| and |has_user_gesture| that will be used
3635 // both in the creation of the NavigationEntry and the NavigationRequest.
3636 // Ideally, the LoadURLParams themselves would be updated, but since they are
3637 // passed as a const reference, this is not possible.
3638 // TODO(clamy): When we only create a NavigationRequest, move this to
3639 // CreateNavigationRequestFromLoadURLParams.
3640 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3641 GetLastCommittedEntry());
3642
Rakina Zata Amnie2d31312022-11-18 03:38:453643 // An entry replacement must happen if the current browsing context should
3644 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333645 bool should_replace_current_entry =
3646 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453647 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423648
clamy21718cc22018-06-13 13:34:243649 // Javascript URLs should not create NavigationEntries. All other navigations
3650 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243651 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373652 std::unique_ptr<NavigationEntryImpl> entry =
3653 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3654 should_replace_current_entry,
3655 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243656 DiscardPendingEntry(false);
3657 SetPendingEntry(std::move(entry));
3658 }
3659
Tim Judkins59548192023-05-17 17:51:203660 // Renderer-debug URLs are sent to the current renderer process immediately
3661 // for processing and don't need to create a NavigationRequest. Note: this
3662 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243663 // renderer-debug URLs.
3664 // Note: we intentionally leave the pending entry in place for renderer debug
3665 // URLs, unlike the cases below where we clear it if the navigation doesn't
3666 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303667 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483668 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3669 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153670 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203671 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483672 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363673 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483674 }
3675
clamy21718cc22018-06-13 13:34:243676 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363677 return nullptr;
clamy21718cc22018-06-13 13:34:243678 }
3679
Antonio Sartori78a749f2020-11-30 12:03:393680 DCHECK(pending_entry_);
3681
clamy21718cc22018-06-13 13:34:243682 // Convert navigations to the current URL to a reload.
3683 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3684 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3685 // DevTools sometimes issues navigations to main frames that they do not
3686 // expect to see treated as reload, and it only works because they pass a
3687 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3688 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543689 ReloadType reload_type = params.reload_type;
3690 if (reload_type == ReloadType::NONE &&
3691 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043692 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243693 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243694 params.load_type ==
3695 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543696 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243697 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473698 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393699
3700 // If this is a reload of an existing FrameNavigationEntry and we had a
3701 // policy container for it, then we should copy it into the pending entry,
3702 // so that it is copied to the navigation request in
3703 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453704 FrameNavigationEntry* previous_frame_entry =
3705 GetLastCommittedEntry()->GetFrameEntry(node);
3706 if (previous_frame_entry &&
3707 previous_frame_entry->policy_container_policies()) {
3708 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3709 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393710 }
3711 }
3712
3713 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173714 // document, then we should copy the document polices from RenderFrameHost's
3715 // PolicyContainerHost. The NavigationRequest will create a new
3716 // PolicyContainerHost with the document policies from the |pending_entry_|,
3717 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3718 // the navigation. This way, we ensure that we keep enforcing the right
3719 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453720 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393721 if (node->current_frame_host() &&
3722 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193723 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163724 node->current_frame_host()
3725 ->policy_container_host()
3726 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233727 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393728 }
clamy21718cc22018-06-13 13:34:243729 }
3730
3731 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263732 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243733
Tsuyoshi Horo167ca6432022-03-09 05:16:393734 // This will be used to set the Navigation Timing API navigationStart
3735 // parameter for browser navigations in new tabs (intents, tabs opened through
3736 // "Open link in new tab"). If the navigation must wait on the current
3737 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3738 // will be updated when the BeforeUnload ack is received.
3739 const auto navigation_start_time = base::TimeTicks::Now();
3740
Camille Lamy5193caa2018-10-12 11:59:423741 std::unique_ptr<NavigationRequest> request =
3742 CreateNavigationRequestFromLoadParams(
3743 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143744 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393745 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3746 navigation_start_time);
clamy21718cc22018-06-13 13:34:243747
3748 // If the navigation couldn't start, return immediately and discard the
3749 // pending NavigationEntry.
3750 if (!request) {
3751 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363752 return nullptr;
clamy21718cc22018-06-13 13:34:243753 }
3754
Camille Lamy5193caa2018-10-12 11:59:423755#if DCHECK_IS_ON()
3756 // Safety check that NavigationRequest and NavigationEntry match.
3757 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3758#endif
3759
clamy21718cc22018-06-13 13:34:243760 // This call does not support re-entrancy. See http://crbug.com/347742.
3761 CHECK(!in_navigate_to_pending_entry_);
3762 in_navigate_to_pending_entry_ = true;
3763
arthursonzogni66f711c2019-10-08 14:40:363764 // It is not possible to delete the pending NavigationEntry while navigating
3765 // to it. Grab a reference to delay potential deletion until the end of this
3766 // function.
3767 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3768
Harkiran Bolariaba823e42021-05-21 18:30:363769 base::WeakPtr<NavigationHandle> created_navigation_handle(
3770 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053771 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243772
3773 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363774 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243775}
3776
clamyea99ea12018-05-28 13:54:233777void NavigationControllerImpl::HandleRendererDebugURL(
3778 FrameTreeNode* frame_tree_node,
3779 const GURL& url) {
3780 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243781 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3782 // the renderer process is not live, unless it is the initial navigation
3783 // of the tab.
clamyea99ea12018-05-28 13:54:233784 if (!IsInitialNavigation()) {
3785 DiscardNonCommittedEntries();
3786 return;
3787 }
Fergal Dalyecd3b0202020-06-25 01:57:373788 // The current frame is always a main frame. If IsInitialNavigation() is
3789 // true then there have been no navigations and any frames of this tab must
3790 // be in the same renderer process. If that has crashed then the only frame
3791 // that can be revived is the main frame.
3792 frame_tree_node->render_manager()
3793 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233794 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223795
3796 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3797 // notification, so set is loading to true here to properly surface it when
3798 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313799 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223800 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223801 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223802 }
clamyea99ea12018-05-28 13:54:233803 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3804}
3805
clamy21718cc22018-06-13 13:34:243806std::unique_ptr<NavigationEntryImpl>
3807NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3808 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423809 const LoadURLParams& params,
3810 bool override_user_agent,
3811 bool should_replace_current_entry,
3812 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393813 // Browser initiated navigations might not have a blob_url_loader_factory set
3814 // in params even if the navigation is to a blob URL. If that happens, lookup
3815 // the correct url loader factory to use here.
3816 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483817 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473818 // Resolve the blob URL in the storage partition associated with the target
3819 // frame. This is the storage partition the URL will be loaded in, and only
3820 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393821 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473822 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393823 }
3824
clamy21718cc22018-06-13 13:34:243825 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443826 // extra_headers in params are \n separated; navigation entries want \r\n.
3827 std::string extra_headers_crlf;
3828 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243829
3830 // For subframes, create a pending entry with a corresponding frame entry.
3831 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453832 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243833 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083834 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243835 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373836 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213837 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3838 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393839 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163840 // a conversion of a new navigation into a reload, we will set the right
3841 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193842 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243843 } else {
3844 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173845 // If `node` is the outermost main frame, it rewrites a virtual url in order
3846 // to adjust the original input url if needed. For inner frames such as
3847 // fenced frames or subframes, they don't rewrite urls as the urls are not
3848 // input urls by users.
3849 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323850 scoped_refptr<SiteInstance> source_site_instance =
3851 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373852 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323853 if (source_site_instance && source_site_instance->HasProcess()) {
3854 source_process_site_url =
3855 source_site_instance->GetProcess()->GetProcessLock().site_url();
3856 }
clamy21718cc22018-06-13 13:34:243857 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063858 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323859 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213860 params.transition_type, params.is_renderer_initiated,
3861 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3862 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243863 entry->set_source_site_instance(
3864 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3865 entry->SetRedirectChain(params.redirect_chain);
3866 }
3867
3868 // Set the FTN ID (only used in non-site-per-process, for tests).
3869 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243870 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423871 entry->SetIsOverridingUserAgent(override_user_agent);
3872 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543873 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243874
clamy21718cc22018-06-13 13:34:243875 switch (params.load_type) {
3876 case LOAD_TYPE_DEFAULT:
3877 break;
3878 case LOAD_TYPE_HTTP_POST:
3879 entry->SetHasPostData(true);
3880 entry->SetPostData(params.post_data);
3881 break;
3882 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:543883 // LoadDataWithBaseURL is a special case that needs to assign both a base
3884 // URL and a virtual URL, while loading the actual content from a data
3885 // URL.
clamy21718cc22018-06-13 13:34:243886 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:543887 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:283888#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243889 entry->SetDataURLAsString(params.data_url_as_string);
3890#endif
3891 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3892 break;
Shu Yang112ad492024-07-25 17:11:543893#if BUILDFLAG(IS_ANDROID)
3894 case LOAD_TYPE_PDF_ANDROID:
3895 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
3896 // internal URL is used for the navigation URL.
3897 entry->SetVirtualURL(params.virtual_url_for_special_cases);
3898 break;
3899#endif
clamy21718cc22018-06-13 13:34:243900 }
3901
3902 // TODO(clamy): NavigationEntry is meant for information that will be kept
3903 // after the navigation ended and therefore is not appropriate for
3904 // started_from_context_menu. Move started_from_context_menu to
3905 // NavigationUIData.
3906 entry->set_started_from_context_menu(params.started_from_context_menu);
3907
3908 return entry;
3909}
3910
clamyea99ea12018-05-28 13:54:233911std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423912NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3913 FrameTreeNode* node,
3914 const LoadURLParams& params,
3915 bool override_user_agent,
3916 bool should_replace_current_entry,
3917 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143918 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423919 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573920 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393921 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223922 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493923 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453924 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583925 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343926 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:373927 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573928 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283929 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533930 // All renderer-initiated navigations must have an initiator_origin.
3931 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513932
Camille Lamy5193caa2018-10-12 11:59:423933 GURL url_to_load;
3934 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323935
Camille Lamy2baa8022018-10-19 16:43:173936 // For main frames, rewrite the URL if necessary and compute the virtual URL
3937 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263938 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423939 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173940 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423941 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423942
Shu Yang112ad492024-07-25 17:11:543943 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
3944 // that need to define a virtual URL to display, which differs from the
3945 // navigation URL.
3946 if (params.load_type == LOAD_TYPE_DATA) {
3947 virtual_url = params.virtual_url_for_special_cases;
3948 }
3949#if BUILDFLAG(IS_ANDROID)
3950 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
3951 virtual_url = params.virtual_url_for_special_cases;
3952 }
3953#endif
Camille Lamy5193caa2018-10-12 11:59:423954
Camille Lamy2baa8022018-10-19 16:43:173955 if (virtual_url.is_empty())
3956 virtual_url = url_to_load;
3957
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573958 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283959
Aran Gilman249eb122019-12-02 23:32:463960 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3961 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3962 // return different results, leading to a different URL in the
3963 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3964 // pending NavigationEntry, as we'll only make one call to
3965 // RewriteUrlForNavigation.
3966 VLOG_IF(1, (url_to_load != frame_entry->url()))
3967 << "NavigationRequest and FrameEntry have different URLs: "
3968 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283969
Camille Lamy2baa8022018-10-19 16:43:173970 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423971 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173972 // NavigationRequest.
3973 } else {
3974 url_to_load = params.url;
3975 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243976 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173977 }
Camille Lamy5193caa2018-10-12 11:59:423978
Ehsan Karamad44fc72112019-02-26 18:15:473979 if (node->render_manager()->is_attaching_inner_delegate()) {
3980 // Avoid starting any new navigations since this node is now preparing for
3981 // attaching an inner delegate.
3982 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203983 }
Camille Lamy5193caa2018-10-12 11:59:423984
Alex Moshchuk99242832023-05-22 17:21:443985 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:423986 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:443987 }
Camille Lamy5193caa2018-10-12 11:59:423988
danakjd83d706d2020-11-25 22:11:123989 // Look for a pending commit that is to another document in this
3990 // FrameTreeNode. If one exists, then the last committed URL will not be the
3991 // current URL by the time this navigation commits.
3992 bool has_pending_cross_document_commit =
3993 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213994 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123995
Minggang Wangb9f3fa92021-07-01 15:30:313996 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493997 /*old_url=*/node->current_url(),
3998 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3999 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134000 /*is_same_document_history_load=*/false,
4001 is_embedder_initiated_fenced_frame_navigation,
4002 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424003
4004 // Create the NavigationParams based on |params|.
4005
Hiroki Nakagawa4ed61282021-06-18 05:37:234006 bool is_view_source_mode = entry->IsViewSourceMode();
4007 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294008
Antonio Sartori6984c742021-08-26 08:03:414009 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294010
Hiroki Nakagawa4ed61282021-06-18 05:37:234011 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294012 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254013 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294014
Minggang Wangb9f3fa92021-07-01 15:30:314015 blink::mojom::CommonNavigationParamsPtr common_params =
4016 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214017 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514018 blink::mojom::Referrer::New(params.referrer.url,
4019 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214020 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514021 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:394022 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514023 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144024 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414025 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274026 false /* has_text_fragment_token */,
4027 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4028 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514029 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054030 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424031
Minggang Wangb9f3fa92021-07-01 15:30:314032 blink::mojom::CommitNavigationParamsPtr commit_params =
4033 blink::mojom::CommitNavigationParams::New(
Arthur Sonzognic686e8f2024-01-11 08:36:374034 std::nullopt,
Ari Chivukulac7533522024-05-14 21:52:344035 // The correct storage key will be computed before committing the
4036 // navigation.
4037 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324038 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504039 std::vector<net::RedirectInfo>(), params.post_content_type,
4040 common_params->url, common_params->method,
4041 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:314042 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:134043 entry->GetSubframeUniqueNames(node),
4044 /*intended_as_new_entry=*/true,
4045 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144046 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4047 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134048 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314049 params.should_clear_history_list,
4050 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224051 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134052 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514053 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284054#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134055 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144056#endif
Yoav Weiss8c573952022-11-17 17:35:134057 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:134058 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074059 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134060 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4061 /*origin_agent_cluster=*/false,
4062 /*origin_agent_cluster_left_as_default=*/true,
4063 /*enabled_client_hints=*/
4064 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264065 /*is_cross_site_cross_browsing_context_group=*/false,
4066 /*should_have_sticky_user_activation=*/false,
4067 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134068 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014069 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134070 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584071 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134072 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134073 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284074 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134075 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444076 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424077 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374078 /*view_transition_state=*/std::nullopt,
4079 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054080 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464081 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374082 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054083 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094084 /*load_with_storage_access=*/
4085 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374086 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374087 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484088 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314089 /*visited_link_salt=*/std::nullopt,
4090 /*local_surface_id=*/std::nullopt);
Xiaohan Wang7f8052e02022-01-14 18:44:284091#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424092 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564093 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424094 }
4095#endif
4096
Lucas Furukawa Gadania9c45682019-07-31 22:05:144097 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074098 commit_params->navigation_timing->system_entropy_at_navigation_start =
4099 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4100 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424101
Camille Lamy5193caa2018-10-12 11:59:424102 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4103 std::string extra_headers_crlf;
4104 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094105
Alex Moshchuk9321e6a2022-12-07 21:58:314106 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144107 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084108 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094109 params.initiator_frame_token, params.initiator_process_id,
4110 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214111 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294112 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454113 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344114 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034115 embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094116 navigation_request->set_from_download_cross_origin_redirect(
4117 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554118 navigation_request->set_force_new_browsing_instance(
4119 params.force_new_browsing_instance);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434120 if (params.force_no_https_upgrade) {
4121 navigation_request->set_force_no_https_upgrade();
4122 }
Yao Xiaodc5ed102019-06-04 19:19:094123 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424124}
4125
4126std::unique_ptr<NavigationRequest>
4127NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234128 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574129 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234130 FrameNavigationEntry* frame_entry,
4131 ReloadType reload_type,
4132 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434133 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374134 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334135 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374136 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134137 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344138 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234139 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434140 // We should never navigate to an existing initial NavigationEntry that is the
4141 // initial NavigationEntry for the initial empty document that hasn't been
4142 // overridden by the synchronous about:blank commit, to preserve previous
4143 // behavior where trying to reload when the main frame is on the initial empty
4144 // document won't result in a navigation.
4145 // See also https://crbug.com/1277414.
4146 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324147
clamyea99ea12018-05-28 13:54:234148 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234149
Ehsan Karamad44fc72112019-02-26 18:15:474150 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4151 // Avoid starting any new navigations since this node is now preparing for
4152 // attaching an inner delegate.
4153 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204154 }
4155
Alex Moshchuk99242832023-05-22 17:21:444156 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4157 dest_url)) {
clamyea99ea12018-05-28 13:54:234158 return nullptr;
4159 }
4160
clamyea99ea12018-05-28 13:54:234161 // This will be used to set the Navigation Timing API navigationStart
4162 // parameter for browser navigations in new tabs (intents, tabs opened through
4163 // "Open link in new tab"). If the navigation must wait on the current
4164 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4165 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074166
clamyea99ea12018-05-28 13:54:234167 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074168 const auto navigation_start_system_entropy =
4169 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4170 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234171
danakjd83d706d2020-11-25 22:11:124172 // Look for a pending commit that is to another document in this
4173 // FrameTreeNode. If one exists, then the last committed URL will not be the
4174 // current URL by the time this navigation commits.
4175 bool has_pending_cross_document_commit =
4176 frame_tree_node->render_manager()
4177 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494178 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214179 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124180
Minggang Wangb9f3fa92021-07-01 15:30:314181 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124182 /*old_url=*/frame_tree_node->current_url(),
4183 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494184 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494185 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134186 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494187 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424188
4189 // A form submission may happen here if the navigation is a
4190 // back/forward/reload navigation that does a form resubmission.
4191 scoped_refptr<network::ResourceRequestBody> request_body;
4192 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394193 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504194 // entry. This way, it could be directly retrieved here. Right now, it is only
4195 // partially recovered when request.method == "POST" and request.body exists.
4196 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424197 if (frame_entry->method() == "POST") {
4198 request_body = frame_entry->GetPostData(&post_content_type);
4199 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304200 post_content_type = std::string(
4201 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504202 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424203 }
4204
4205 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314206 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514207 entry->ConstructCommonNavigationParams(
4208 *frame_entry, request_body, dest_url,
4209 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384210 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534211 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514212 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554213 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424214
4215 // TODO(clamy): |intended_as_new_entry| below should always be false once
4216 // Reload no longer leads to this being called for a pending NavigationEntry
4217 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314218 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144219 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404220 *frame_entry, common_params->url, common_params->method,
4221 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144222 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534223 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484224 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134225 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074226 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144227 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074228 commit_params->navigation_timing->system_entropy_at_navigation_start =
4229 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4230 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424231
W. James MacLeanb7d6092682022-10-05 15:23:264232 if (common_params->url.IsAboutSrcdoc()) {
4233 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4234 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594235 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264236 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334237 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314238 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144239 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434240 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334241 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4242 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374243 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294244 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4245 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474246 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234247}
4248
[email protected]d202a7c2012-01-04 07:53:474249void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214250 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274251 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404252
Takashi Toyoshimaea534ef22021-07-21 03:27:594253 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404254 // location bar will have up-to-date information about the security style
4255 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134256 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404257
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374258 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574259 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294260}
4261
initial.commit09911bf2008-07-26 23:55:294262// static
[email protected]d202a7c2012-01-04 07:53:474263size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234264 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154265 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214266 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234267}
4268
[email protected]d202a7c2012-01-04 07:53:474269void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224270 if (is_active && needs_reload_)
4271 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294272}
4273
[email protected]d202a7c2012-01-04 07:53:474274void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034275 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4276 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294277 if (!needs_reload_)
4278 return;
4279
Bo Liucdfa4b12018-11-06 00:21:444280 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4281 needs_reload_type_);
4282
initial.commit09911bf2008-07-26 23:55:294283 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004284 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294285 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004286 if (entry_replaced_by_post_commit_error_) {
4287 // If the current entry is a post commit error, we reload the entry it
4288 // replaced instead. We leave the error entry in place until a commit
4289 // replaces it, but the pending entry points to the original entry in the
4290 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4291 // case that pending_entry_ != entries_[pending_entry_index_].
4292 // Note that this handling is similar to
4293 // `NavigationControllerImpl::Reload()`.
4294 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4295 pending_entry_index_ = GetCurrentEntryIndex();
4296 NavigateToExistingPendingEntry(
4297 ReloadType::NONE,
4298 /*initiator_rfh=*/nullptr,
4299 /*soft_navigation_heuristics_task_id=*/std::nullopt,
4300 /*navigation_api_key=*/nullptr);
4301 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134302 NavigateToExistingPendingEntry(
4303 ReloadType::NONE,
4304 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374305 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134306 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454307 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434308 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274309 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344310 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134311 NavigateToExistingPendingEntry(
4312 ReloadType::NONE,
4313 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374314 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134315 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344316 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434317 // We should never navigate to an existing initial NavigationEntry that is
4318 // the initial NavigationEntry for the initial empty document that hasn't
4319 // been overridden by the synchronous about:blank commit, to preserve
4320 // legacy behavior where trying to reload when the main frame is on the
4321 // initial empty document won't result in a navigation. See also
4322 // https://crbug.com/1277414. If there is something to reload, the
4323 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4324 // it here.
avicc872d7242015-08-19 21:26:344325 needs_reload_ = false;
4326 }
initial.commit09911bf2008-07-26 23:55:294327}
4328
Kevin McNeeccca6172021-10-19 17:11:144329base::WeakPtr<NavigationHandle>
4330NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364331 RenderFrameHost* render_frame_host,
4332 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364333 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134334 RenderFrameHostImpl* rfhi =
4335 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584336
4337 // Only active documents can load post-commit error pages:
4338 // - If the document is in pending deletion, the browser already committed to
4339 // destroying this RenderFrameHost so ignore loading the error page.
4340 // - If the document is in back-forward cache, it's not allowed to navigate as
4341 // it should remain frozen. Ignore the request and evict the document from
4342 // back-forward cache.
4343 // - If the document is prerendering, it can navigate but when loading error
4344 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114345 if (rfhi->IsInactiveAndDisallowActivation(
4346 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144347 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114348 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584349
Rakina Zata Amni919b7922020-12-11 09:03:134350 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414351
Minggang Wangb9f3fa92021-07-01 15:30:314352 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434353 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594354 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4355 // the frame actually committed (e.g. iframe with "src" set to a
4356 // slow-responding URL). We should rewrite the URL to about:blank in this
4357 // case, as the renderer will only think a page is an error page if it has a
4358 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134359 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314360 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434361 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334362 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414363
Mike Jacksone2aa7af2023-05-17 06:45:074364 commit_params->navigation_timing->system_entropy_at_navigation_start =
4365 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4366 node, blink::mojom::SystemEntropy::kNormal);
4367
arthursonzogni70ac7302020-05-28 08:49:054368 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4369 // error pages.
Liam Brady34639ec92023-10-13 19:50:454370 commit_params->frame_policy = node->pending_frame_policy();
arthursonzogni70ac7302020-05-28 08:49:054371
John Delaney131ad362019-08-08 21:57:414372 std::unique_ptr<NavigationRequest> navigation_request =
4373 NavigationRequest::CreateBrowserInitiated(
4374 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094375 false /* was_opener_suppressed */, "" /* extra_headers */,
4376 nullptr /* frame_entry */, nullptr /* entry */,
4377 false /* is_form_submission */, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374378 std::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364379 navigation_request->set_post_commit_error_page_html(error_page_html);
Lei Zhanga4770832023-07-19 18:02:364380 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
Charlie Reis09952ee2022-12-08 16:35:074381 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414382 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144383
4384 // Calling BeginNavigation may destroy the NavigationRequest.
4385 base::WeakPtr<NavigationRequest> created_navigation_request(
4386 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414387 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144388 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414389}
4390
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574391void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214392 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094393 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154394 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144395 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294396}
4397
[email protected]d202a7c2012-01-04 07:53:474398void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364399 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584400 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474401 // represent a no-committed-entry state.
4402 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364403 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584404 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474405 // if `entries_` contains pre-existing entries from the NavigationController
4406 // before restore, which would not be removed and will be at the front of the
4407 // entries list, causing the index to be off by the amount of pre-existing
4408 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294409 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294410}
[email protected]765b35502008-08-21 00:51:204411
arthursonzogni69a6a1b2019-09-17 09:23:004412void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004413 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4414}
4415
4416void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4417 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474418 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104419 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4420 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294421 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474422 return;
Michael Thiessenc5676d22019-09-25 22:32:104423 }
avi45a72532015-04-07 21:01:454424 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314425
4426 if (!delegate_)
4427 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374428 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484429}
4430
avi7c6f35e2015-05-08 17:52:384431int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4432 int nav_entry_id) const {
4433 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4434 if (entries_[i]->GetUniqueID() == nav_entry_id)
4435 return i;
4436 }
4437 return -1;
4438}
4439
[email protected]d202a7c2012-01-04 07:53:474440void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574441 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254442 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574443 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594444 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254445 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374446 // Normally, cloning a NavigationEntryImpl results in sharing
4447 // FrameNavigationEntries between the original and the clone. However, when
4448 // cloning from a different NavigationControllerImpl, we want to fork the
4449 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374450 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594451 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254452 }
Rakina Zata Amnie2d31312022-11-18 03:38:454453 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274454 DCHECK(pending_entry_index_ == -1 ||
4455 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254456}
[email protected]c5b88d82012-10-06 17:03:334457
4458void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184459 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334460 get_timestamp_callback_ = get_timestamp_callback;
4461}
[email protected]8ff00d72012-10-23 19:12:214462
Shivani Sharmaffb32b82019-04-09 16:58:474463// History manipulation intervention:
4464void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474465 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564466 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404467 bool is_renderer_initiated,
4468 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564469 // Note that for a subframe,
4470 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454471 // gesture happened in any subframe (propagated to main frame) or in the main
4472 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564473 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274474 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474475 return;
4476 }
4477 if (last_committed_entry_index_ == -1)
4478 return;
4479
Shivani Sharmac4cc8922019-04-18 03:11:174480 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474481
Alexander Timine3ec4192020-04-20 16:39:404482 // Log UKM with the URL we are navigating away from.
4483 ukm::builders::HistoryManipulationIntervention(
4484 previous_page_load_ukm_source_id)
4485 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474486}
4487
Shivani Sharmac4cc8922019-04-18 03:11:174488void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4489 int reference_index,
4490 bool skippable) {
4491 auto* reference_entry = GetEntryAtIndex(reference_index);
4492 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4493
4494 int64_t document_sequence_number =
4495 reference_entry->root_node()->frame_entry->document_sequence_number();
4496 for (int index = 0; index < GetEntryCount(); index++) {
4497 auto* entry = GetEntryAtIndex(index);
4498 if (entry->root_node()->frame_entry->document_sequence_number() ==
4499 document_sequence_number) {
4500 entry->set_should_skip_on_back_forward_ui(skippable);
4501 }
4502 }
4503}
4504
arthursonzogni66f711c2019-10-08 14:40:364505std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4506NavigationControllerImpl::ReferencePendingEntry() {
4507 DCHECK(pending_entry_);
4508 auto pending_entry_ref =
4509 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4510 pending_entry_refs_.insert(pending_entry_ref.get());
4511 return pending_entry_ref;
4512}
4513
4514void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4515 // Ignore refs that don't correspond to the current pending entry.
4516 auto it = pending_entry_refs_.find(ref);
4517 if (it == pending_entry_refs_.end())
4518 return;
4519 pending_entry_refs_.erase(it);
4520
4521 if (!pending_entry_refs_.empty())
4522 return;
4523
4524 // The pending entry may be deleted before the last PendingEntryRef.
4525 if (!pending_entry_)
4526 return;
4527
4528 // We usually clear the pending entry when the matching NavigationRequest
4529 // fails, so that an arbitrary URL isn't left visible above a committed page.
4530 //
4531 // However, we do preserve the pending entry in some cases, such as on the
4532 // initial navigation of an unmodified blank tab. We also allow the delegate
4533 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4534 // user edit the URL and try again. This may be useful in cases that the
4535 // committed page cannot be attacker-controlled. In these cases, we still
4536 // allow the view to clear the pending entry and typed URL if the user
4537 // requests (e.g., hitting Escape with focus in the address bar).
4538 //
4539 // Do not leave the pending entry visible if it has an invalid URL, since this
4540 // might be formatted in an unexpected or unsafe way.
4541 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364542 bool should_preserve_entry =
4543 (pending_entry_ == GetVisibleEntry()) &&
4544 pending_entry_->GetURL().is_valid() &&
4545 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4546 if (should_preserve_entry)
4547 return;
4548
4549 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374550 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364551}
4552
Titouan Rigoudy6ec70402021-02-02 15:42:194553std::unique_ptr<PolicyContainerPolicies>
4554NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394555 RenderFrameHostImpl* rfh,
4556 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174557 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394558 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454559 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394560 FrameNavigationEntry* previous_frame_entry =
4561 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4562
Alison Gale770f3fc2024-04-27 00:39:584563 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394564 // ensure we always have a FrameNavigationEntry here.
4565 if (!previous_frame_entry)
4566 return nullptr;
4567
Titouan Rigoudy6ec70402021-02-02 15:42:194568 const PolicyContainerPolicies* previous_policies =
4569 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394570
Titouan Rigoudy6ec70402021-02-02 15:42:194571 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394572 return nullptr;
4573
4574 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234575 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394576 }
4577
Titouan Rigoudy72f892d2022-05-02 18:21:234578 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394579}
4580
Hayato Ito2c8c08d02021-06-23 03:38:434581void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504582 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434583 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4584 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4585 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504586
4587 auto callback = base::BindRepeating(
4588 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4589 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4590 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4591 }
4592 },
Hayato Ito2c8c08d02021-06-23 03:38:434593 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034594 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504595}
4596
4597void NavigationControllerImpl::DidAccessInitialMainDocument() {
4598 // We may have left a failed browser-initiated navigation in the address bar
4599 // to let the user edit it and try again. Clear it now that content might
4600 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034601 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504602 DiscardPendingEntry(false);
4603
4604 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374605 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504606}
4607
4608void NavigationControllerImpl::UpdateStateForFrame(
4609 RenderFrameHostImpl* rfhi,
4610 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564611 OPTIONAL_TRACE_EVENT1("content",
4612 "NavigationControllerImpl::UpdateStateForFrame",
4613 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504614 // The state update affects the last NavigationEntry associated with the given
4615 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4616 // in the case of an UpdateState from a frame being swapped out). We track
4617 // which entry this is in the RenderFrameHost's nav_entry_id.
4618 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4619 if (!entry)
4620 return;
4621
4622 FrameNavigationEntry* frame_entry =
4623 entry->GetFrameEntry(rfhi->frame_tree_node());
4624 if (!frame_entry)
4625 return;
4626
4627 // The SiteInstance might not match if we do a cross-process navigation with
4628 // replacement (e.g., auto-subframe), in which case the swap out of the old
4629 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4630 // has already been replaced and destroyed.
4631 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4632 return;
4633
4634 if (page_state == frame_entry->page_state())
4635 return; // Nothing to update.
4636
4637 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4638
4639 // The document_sequence_number and item_sequence_number recorded in the
4640 // FrameNavigationEntry should not differ from the one coming with the update,
4641 // since it must come from the same document. Do not update it if a difference
4642 // is detected, as this indicates that |frame_entry| is not the correct one.
4643 blink::ExplodedPageState exploded_state;
4644 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4645 return;
4646
4647 if (exploded_state.top.document_sequence_number !=
4648 frame_entry->document_sequence_number() ||
4649 exploded_state.top.item_sequence_number !=
4650 frame_entry->item_sequence_number()) {
4651 return;
4652 }
4653
4654 frame_entry->SetPageState(page_state);
4655 NotifyEntryChanged(entry);
4656}
4657
Nate Chapina2c881f52023-11-07 17:02:094658namespace {
4659
4660// The caller is responsible for ensuring the entry is same-origin to the
4661// origin to be committed.
4662blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4663 FrameNavigationEntry* frame_entry,
4664 int64_t pending_document_sequence_number) {
4665 blink::ExplodedPageState exploded_state;
4666 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4667 &exploded_state)) {
4668 return nullptr;
4669 }
4670 blink::ExplodedFrameState frame_state = exploded_state.top;
4671
4672 // If the document represented by this FNE hid its full url from appearing in
4673 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4674 // in the navigation API as well (unless we're navigating to that document).
4675 std::u16string url;
4676 if (pending_document_sequence_number ==
4677 frame_entry->document_sequence_number() ||
4678 !frame_entry->protect_url_in_navigation_api()) {
4679 url = frame_state.url_string.value_or(std::u16string());
4680 }
4681
4682 return blink::mojom::NavigationApiHistoryEntry::New(
4683 frame_state.navigation_api_key.value_or(std::u16string()),
4684 frame_state.navigation_api_id.value_or(std::u16string()), url,
4685 frame_state.item_sequence_number, frame_state.document_sequence_number,
4686 frame_state.navigation_api_state);
4687}
4688
4689} // namespace
4690
Domenic Denicolacd30f5f82022-03-16 21:48:014691std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4692NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574693 Direction direction,
4694 int entry_index,
4695 const url::Origin& pending_origin,
4696 FrameTreeNode* node,
4697 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304698 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094699 int64_t pending_document_sequence_number,
4700 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014701 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454702 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174703 // Don't process the initial entry.
4704 DCHECK_EQ(GetEntryCount(), 1);
4705 return entries;
4706 }
Nate Chapind1fe3612021-04-16 20:45:574707 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304708 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574709 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4710 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094711 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574712 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414713 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574714 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014715 // An entry should only appear in the navigation API entries if it is for
4716 // the same origin as the document being committed. Check the committed
4717 // origin, or if that is not available (during restore), check against the
4718 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584719 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094720 // once we can be sure that entries with the same ISN will never be
4721 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414722 url::Origin frame_entry_origin =
4723 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4724 frame_entry->url(),
4725 frame_entry->initiator_origin().value_or(url::Origin())));
4726 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574727 break;
4728 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4729 continue;
Nate Chapina2c881f52023-11-07 17:02:094730 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4731 ToNavigationApiHistoryEntry(frame_entry,
4732 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304733 DCHECK(entry->url.empty() ||
4734 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574735 entries.push_back(std::move(entry));
4736 previous_item_sequence_number = frame_entry->item_sequence_number();
4737 }
4738 }
4739 // If |entries| was constructed by iterating backwards from
4740 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4741 // earliest-at-the-front. Reverse it.
4742 if (direction == Direction::kBack)
4743 std::reverse(entries.begin(), entries.end());
4744 return entries;
4745}
4746
Domenic Denicolacd30f5f82022-03-16 21:48:014747blink::mojom::NavigationApiHistoryEntryArraysPtr
4748NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554749 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574750 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404751 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444752 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404753 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574754
Nate Chapind1fe3612021-04-16 20:45:574755 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554756 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574757
Nate Chapine82339d02022-05-03 23:48:254758 // NOTE: |entry_index| is the index where this entry will commit if no
4759 // modifications are made between now and DidCommitNavigation. This is used to
4760 // walk |entries_| and determine which entries should be exposed by the
4761 // navigation API. It is important to calculate this correctly, because blink
4762 // will cancel a same-document history commit if it's not present in the
4763 // entries blink knows about.
4764 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574765 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304766 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254767 bool will_create_new_entry = false;
4768 if (GetPendingEntryIndex() != -1) {
4769 entry_index = GetPendingEntryIndex();
4770 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4771 pending_item_sequence_number = frame_entry->item_sequence_number();
4772 pending_document_sequence_number =
4773 frame_entry->document_sequence_number();
4774 }
4775 } else if (request &&
4776 !NavigationTypeUtils::IsReload(
4777 request->common_params().navigation_type) &&
4778 !NavigationTypeUtils::IsHistory(
4779 request->common_params().navigation_type) &&
4780 !request->common_params().should_replace_current_entry &&
4781 !request->common_params()
4782 .is_history_navigation_in_new_child_frame) {
4783 will_create_new_entry = true;
4784 entry_index = GetLastCommittedEntryIndex() + 1;
4785 // Don't set pending_item_sequence_number or
4786 // pending_document_sequence_number in this case - a new unique isn/dsn will
4787 // be calculated in the renderer later.
4788 } else if (GetLastCommittedEntryIndex() != -1) {
4789 entry_index = GetLastCommittedEntryIndex();
4790 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574791 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304792 pending_document_sequence_number =
4793 frame_entry->document_sequence_number();
4794 }
Nate Chapind1fe3612021-04-16 20:45:574795 }
4796
Domenic Denicolacd30f5f82022-03-16 21:48:014797 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254798 if (entry_index == -1) {
4799 // TODO(rakina): Exit early when there is no last committed entry.
4800 // Remove when InitialNavigationEntry ships.
4801 return entry_arrays;
4802 }
4803
Nate Chapina2c881f52023-11-07 17:02:094804 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014805 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574806 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094807 pending_item_sequence_number, pending_document_sequence_number,
4808 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574809
4810 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094811 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574812 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014813 entry_arrays->forward_entries =
4814 PopulateSingleNavigationApiHistoryEntryVector(
4815 Direction::kForward, entry_index, pending_origin, node,
4816 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094817 pending_document_sequence_number, forwardmost_index);
4818 }
4819
4820 // If the previous entry is within the block of contiguous entries being
4821 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254822 FrameNavigationEntry* previous_entry = nullptr;
4823 if (frame_tree_->is_prerendering()) {
4824 int initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4825 .initiator_frame_tree_node_id();
4826 if (initiator_id != RenderFrameHost::kNoFrameTreeNodeId) {
4827 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4828 previous_entry = initiator_node->frame_tree()
4829 .controller()
4830 .GetLastCommittedEntry()
4831 ->GetFrameEntry(initiator_node);
4832 }
4833 } else if (GetLastCommittedEntryIndex() != -1 &&
4834 GetLastCommittedEntryIndex() >= backmost_index &&
4835 GetLastCommittedEntryIndex() <= forwardmost_index) {
4836 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4837 }
4838 if (previous_entry) {
4839 url::Origin previous_entry_origin =
4840 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4841 previous_entry->url(),
4842 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:584843 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:254844 // once we can be sure that entries with the same ISN will never be
4845 // cross-origin.
4846 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4847 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4848 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094849 }
Nate Chapind1fe3612021-04-16 20:45:574850 }
Nate Chapinc06cf80a2023-11-18 01:12:254851
Nate Chapin4e657a472022-02-06 03:38:374852 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574853}
4854
Nate Chapinfbfe5af2021-06-10 17:22:084855NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574856NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084857 FrameNavigationEntry* current_entry,
4858 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574859 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084860 if (!target_entry || !target_entry->committed_origin())
4861 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084862 if (!current_entry->committed_origin()->IsSameOriginWith(
4863 *target_entry->committed_origin())) {
4864 return HistoryNavigationAction::kStopLooking;
4865 }
4866
4867 // NOTE: We don't actually care between kSameDocument and
4868 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574869 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084870 return HistoryNavigationAction::kDifferentDocument;
4871 return HistoryNavigationAction::kKeepLooking;
4872}
4873
Domenic Denicolacc094fb2022-03-16 23:40:574874void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204875 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374876 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144877 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574878 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204879 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084880 FrameNavigationEntry* current_entry =
4881 GetLastCommittedEntry()->GetFrameEntry(node);
4882 if (!current_entry)
4883 return;
4884
Alison Gale47d1537d2024-04-19 21:31:464885 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:134886 // when `navigation.traverseTo()` is called.
4887
Nate Chapinfbfe5af2021-06-10 17:22:084888 // We want to find the nearest matching entry that is contiguously
4889 // same-instance and same-origin. Check back first, then forward.
4890 // TODO(japhet): Link spec here once it exists.
4891 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574892 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084893 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4894 if (result == HistoryNavigationAction::kStopLooking)
4895 break;
4896 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144897 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084898 return;
4899 }
4900 }
4901 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574902 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084903 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4904 if (result == HistoryNavigationAction::kStopLooking)
4905 break;
4906 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144907 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084908 return;
4909 }
4910 }
Nate Chapinbf682fa32022-09-26 22:41:204911
4912 // If we fall through to here, a matching NavigationEntry couldn't be found.
4913 // Notify the renderer that the navigation was cancelled.
4914 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4915 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084916}
4917
Domenic Denicolacc094fb2022-03-16 23:40:574918bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304919 network::mojom::ReferrerPolicy referrer_policy) {
4920 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4921 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4922}
4923
shivanigithubf405bf0d2021-11-05 17:58:334924bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4925 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:314926 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:334927 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544928 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:464929 // The preview mode appears as prerendered page in renderers, and
4930 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:034931 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:514932 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:334933 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544934}
4935
Julie Jeongeun Kim0e242242022-11-30 10:45:094936void NavigationControllerImpl::DidChangeReferrerPolicy(
4937 FrameTreeNode* node,
4938 network::mojom::ReferrerPolicy referrer_policy) {
4939 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4940 if (!entry)
4941 return;
4942
4943 // The FrameNavigationEntry may want to change whether to protect its url
4944 // in the navigation API when the referrer policy changes.
4945 entry->set_protect_url_in_navigation_api(
4946 ShouldProtectUrlInNavigationApi(referrer_policy));
4947}
4948
[email protected]8ff00d72012-10-23 19:12:214949} // namespace content