blob: b2913b7c5e58e77643700dd77f5abfce110cdac0 [file] [log] [blame]
Avi Drissman4e1b7bc32022-09-15 14:03:501// Copyright 2013 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
creis4e2ecb72015-06-20 00:46:305/*
6 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
9 * (http://www.torchmobile.com/)
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 *
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
21 * its contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
25 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
28 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35
danakjc492bf82020-09-09 20:02:4436#include "content/browser/renderer_host/navigation_controller_impl.h"
initial.commit09911bf2008-07-26 23:55:2937
Lei Zhang96031532019-10-10 19:05:4738#include <algorithm>
dcheng36b6aec92015-12-26 06:16:3639#include <utility>
40
[email protected]eabfe1912014-05-12 10:07:2841#include "base/command_line.h"
Ayu Ishii2f825852022-03-08 19:47:3842#include "base/containers/adapters.h"
Rakina Zata Amni627360d2022-02-24 00:53:4043#include "base/debug/dump_without_crashing.h"
Avi Drissmanadac21992023-01-11 23:46:3944#include "base/functional/bind.h"
initial.commit09911bf2008-07-26 23:55:2945#include "base/logging.h"
asvitkine30330812016-08-30 04:01:0846#include "base/metrics/histogram_macros.h"
Charlie Reis23c26da2022-01-29 00:57:4747#include "base/numerics/safe_conversions.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3948#include "base/strings/escape.h"
[email protected]348fbaac2013-06-11 06:31:5149#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0050#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3751#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0052#include "base/trace_event/optional_trace_event.h"
ssid3e765612015-01-28 04:03:4253#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0854#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5955#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2856#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1857#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3958#include "content/browser/blob_storage/chrome_blob_storage_context.h"
William Liu055a3542023-04-02 17:21:1959#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3160#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4161#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0462#include "content/browser/dom_storage/session_storage_namespace_impl.h"
Nate Chapinc06cf80a2023-11-18 01:12:2563#include "content/browser/preloading/prerender/prerender_host.h"
Sharon Yang242ef822023-05-15 21:07:3264#include "content/browser/process_lock.h"
Mingyu Lei68f34412023-08-21 07:31:3765#include "content/browser/renderer_host/back_forward_cache_impl.h"
danakjc492bf82020-09-09 20:02:4466#include "content/browser/renderer_host/debug_urls.h"
67#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0068#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3369#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4470#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5771#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4472#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1973#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
74#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
Khushal Sagar94ea2dc2024-08-06 17:15:2675#include "content/browser/renderer_host/navigation_transitions/navigation_transition_config.h"
danakjc492bf82020-09-09 20:02:4476#include "content/browser/renderer_host/navigator.h"
Takashi Toyoshima4dad2c12023-11-13 10:04:4677#include "content/browser/renderer_host/page_delegate.h"
danakjc492bf82020-09-09 20:02:4478#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0079#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0780#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3281#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3382#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4283#include "content/common/content_constants_internal.h"
Rakina Zata Amni84a859df2024-06-07 15:56:3284#include "content/common/content_navigation_policy.h"
Nate Chapind1fe3612021-04-16 20:45:5785#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5186#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1187#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1988#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1189#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4690#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0091#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4792#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5893#include "content/public/browser/render_widget_host.h"
94#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1095#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3496#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1997#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3898#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1099#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47100#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43101#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59102#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36103#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57104#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18105#include "services/metrics/public/cpp/ukm_builders.h"
106#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17107#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37108#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44109#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58110#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39111#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30112#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21113#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06114#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43115#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50116#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31117#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51118#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46119#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26120#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29121
[email protected]8ff00d72012-10-23 19:12:21122namespace content {
[email protected]e9ba4472008-09-14 15:42:43123namespace {
124
125// Invoked when entries have been pruned, or removed. For example, if the
126// current entries are [google, digg, yahoo], with the current entry google,
127// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47128void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50129 int index,
[email protected]c12bf1a12008-09-17 16:28:49130 int count) {
[email protected]8ff00d72012-10-23 19:12:21131 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50132 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49133 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14134 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43135}
136
[email protected]e9ba4472008-09-14 15:42:43137// Configure all the NavigationEntries in entries for restore. This resets
138// the transition type to reload and makes sure the content state isn't empty.
139void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57140 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48141 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47142 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43143 // Use a transition type of reload so that we don't incorrectly increase
144 // the typed count.
Lei Zhang96031532019-10-10 19:05:47145 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
146 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43147 }
148}
149
[email protected]bf70edce2012-06-20 22:32:22150// Determines whether or not we should be carrying over a user agent override
151// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57152bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22153 return last_entry && last_entry->GetIsOverridingUserAgent();
154}
155
Camille Lamy5193caa2018-10-12 11:59:42156// Determines whether to override user agent for a navigation.
157bool ShouldOverrideUserAgent(
158 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57159 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42160 switch (override_user_agent) {
161 case NavigationController::UA_OVERRIDE_INHERIT:
162 return ShouldKeepOverride(last_committed_entry);
163 case NavigationController::UA_OVERRIDE_TRUE:
164 return true;
165 case NavigationController::UA_OVERRIDE_FALSE:
166 return false;
Camille Lamy5193caa2018-10-12 11:59:42167 }
Peter Boströmfc7ddc182024-10-31 19:37:21168 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42169}
170
Rakina Zata Amni312822d72021-06-04 16:13:37171// Returns true if this navigation should be treated as a reload. For e.g.
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,
Charlie Reisf21cd182024-08-09 21:44:52346 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31347 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.
Charlie Reisf21cd182024-08-09 21:44:52389 if (frame_entry && 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) &&
Charlie Reisf21cd182024-08-09 21:44:52408 frame_entry && 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) {
Charlie Reisf21cd182024-08-09 21:44:52466 // TODO(https://crbug.com/40467594): This case should be unreachable once
467 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42468 return;
469 }
470
Camille Lamy5193caa2018-10-12 11:59:42471 DCHECK_EQ(request->common_params().method, frame_entry->method());
472
Nasko Oskovc36327d2019-01-03 23:23:04473 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42474 if (redirect_size == frame_entry->redirect_chain().size()) {
475 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04476 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42477 frame_entry->redirect_chain()[i]);
478 }
479 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21480 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42481 }
482}
483#endif // DCHECK_IS_ON()
484
Dave Tapuska8bfd84c2019-03-26 20:47:16485// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20486// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16487bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20488 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16489 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20490 DCHECK(sandboxed_initiator_rfh);
491 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
492 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16493 for (auto& item : navigations) {
494 bool within_subtree = false;
495 // Check whether this NavigationRequest affects a frame within the
496 // sandboxed frame's subtree by walking up the tree looking for the
497 // sandboxed frame.
498 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03499 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20500 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16501 within_subtree = true;
502 break;
503 }
504 }
505 if (!within_subtree)
506 return false;
507 }
508 return true;
509}
510
William Liu122754942024-01-18 22:34:39511// Used for "Navigation.SessionHistoryCount" histogram.
512enum class HistoryNavTypeForHistogram {
513 // A same-doc or cross-doc navigation of the main frame. We can only have one
514 // main frame request per `NavigationController::GoToIndex()`.
515 kMainFrame = 0,
516 // `NavigationController::GoToIndex()` creates one main frame request and
517 // one or more subframe requests.
518 kMainFrameAndSubframe,
519 // `NavigationController::GoToIndex()` creates one or more subframe requests.
520 kSubframe,
521 // Used for histogram boundary.
522 kCount
523};
524
525void CountRequests(
526 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
527 int& mutable_main_frame_cnt,
528 int& mutable_subframe_cnt) {
529 for (const auto& req : requests) {
530 if (req->IsInPrimaryMainFrame()) {
531 // We can only have one main frame navigation at a time.
532 CHECK_EQ(mutable_main_frame_cnt, 0);
533 ++mutable_main_frame_cnt;
534 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
535 ++mutable_subframe_cnt;
536 }
537 }
538}
539
540// Record the number of different types of navigations as histograms. See
541// `HistoryNavTypeForHistogram` for the types.
542void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
543 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
544 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
545 // We must have one request.
546 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
547
548 int main_frame_cnt = 0;
549 int subframe_cnt = 0;
550 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
551 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
552
553 std::optional<HistoryNavTypeForHistogram> history_nav_type;
554 if (main_frame_cnt > 0) {
555 if (subframe_cnt == 0) {
556 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
557 } else {
558 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
559 }
560 } else if (subframe_cnt > 0) {
561 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
562 }
563 if (history_nav_type.has_value()) {
564 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
565 history_nav_type.value(),
566 HistoryNavTypeForHistogram::kCount);
567 }
568}
569
[email protected]e9ba4472008-09-14 15:42:43570} // namespace
571
arthursonzogni66f711c2019-10-08 14:40:36572// NavigationControllerImpl::PendingEntryRef------------------------------------
573
574NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
575 base::WeakPtr<NavigationControllerImpl> controller)
576 : controller_(controller) {}
577
578NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
579 if (!controller_) // Can be null with interstitials.
580 return;
581
582 controller_->PendingEntryRefDeleted(this);
583}
584
[email protected]d202a7c2012-01-04 07:53:47585// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29586
[email protected]23a918b2014-07-15 09:51:36587const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23588
[email protected]765b35502008-08-21 00:51:20589// static
[email protected]d202a7c2012-01-04 07:53:47590size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23591 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20592
[email protected]e6fec472013-05-14 05:29:02593// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20594// when testing.
595static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29596
[email protected]71fde352011-12-29 03:29:56597// static
dcheng9bfa5162016-04-09 01:00:57598std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
599 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10600 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37601 std::optional<url::Origin> initiator_origin,
602 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10603 ui::PageTransition transition,
604 bool is_renderer_initiated,
605 const std::string& extra_headers,
606 BrowserContext* browser_context,
607 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
608 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21609 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37610 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32611 is_renderer_initiated, extra_headers, browser_context,
612 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10613}
614
615// static
616std::unique_ptr<NavigationEntryImpl>
617NavigationControllerImpl::CreateNavigationEntry(
618 const GURL& url,
619 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37620 std::optional<url::Origin> initiator_origin,
621 std::optional<GURL> initiator_base_url,
622 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57623 ui::PageTransition transition,
624 bool is_renderer_initiated,
625 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09626 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17627 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
628 bool rewrite_virtual_urls) {
629 GURL url_to_load = url;
630 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56631 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17632 if (rewrite_virtual_urls) {
633 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
634 &reverse_on_redirect);
635 }
Lukasz Anforowicz641234d52019-11-07 21:07:10636 // Let the NTP override the navigation params and pretend that this is a
637 // browser-initiated, bookmark-like navigation.
638 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32639 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21640 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10641
Patrick Monettef507e982019-06-19 20:18:06642 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28643 nullptr, // The site instance for tabs is sent on navigation
644 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21645 url_to_load, referrer, initiator_origin, initiator_base_url,
646 std::u16string(), transition, is_renderer_initiated,
647 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17648 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42649 entry->SetVirtualURL(virtual_url);
650 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56651 entry->set_update_virtual_url_with_url(reverse_on_redirect);
652 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06653 return entry;
[email protected]71fde352011-12-29 03:29:56654}
655
[email protected]cdcb1dee2012-01-04 00:46:20656// static
657void NavigationController::DisablePromptOnRepost() {
658 g_check_for_repost = false;
659}
660
[email protected]c5b88d82012-10-06 17:03:33661base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
662 base::Time t) {
663 // If |t| is between the water marks, we're in a run of duplicates
664 // or just getting out of it, so increase the high-water mark to get
665 // a time that probably hasn't been used before and return it.
666 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35667 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33668 return high_water_mark_;
669 }
670
671 // Otherwise, we're clear of the last duplicate run, so reset the
672 // water marks.
673 low_water_mark_ = high_water_mark_ = t;
674 return t;
675}
676
ckitagawa0faa5e42020-06-17 17:30:54677NavigationControllerImpl::ScopedShowRepostDialogForTesting::
678 ScopedShowRepostDialogForTesting()
679 : was_disallowed_(g_check_for_repost) {
680 g_check_for_repost = true;
681}
682
683NavigationControllerImpl::ScopedShowRepostDialogForTesting::
684 ~ScopedShowRepostDialogForTesting() {
685 g_check_for_repost = was_disallowed_;
686}
687
Nate Chapin9eb16be72022-09-23 22:54:31688NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
689 base::SafeRef<NavigationControllerImpl> controller)
690 : controller_(controller) {
691 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
692 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
693 frame_tree_node_id_to_keys_.insert(
694 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
695 if (auto* frame_entry = frame_tree_node->current_frame_host()
696 ->last_committed_frame_entry()) {
697 frame_tree_node_id_to_doc_seq_nos_.insert(
698 {frame_tree_node->frame_tree_node_id(),
699 frame_entry->document_sequence_number()});
700 }
701 }
702 PopulateKeySet(Direction::kBack);
703 PopulateKeySet(Direction::kForward);
704}
705
706void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
707 Direction direction) {
708 // Keep track of which FrameTreeNodes may still have relevant API keys in
709 // additional FrameNavigationEntries.
710 std::set<FrameTreeNode*> nodes_to_process;
711 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
712 nodes_to_process.insert(node);
713 }
714
715 const int offset = direction == Direction::kForward ? 1 : -1;
716 const int start = direction == Direction::kForward
717 ? controller_->GetLastCommittedEntryIndex()
718 : controller_->GetLastCommittedEntryIndex() - 1;
719 for (int i = start;
720 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
721 i += offset) {
722 std::set<FrameTreeNode*> nodes_to_continue_processing;
723
724 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
725 entry->ForEachFrameEntry([this, &nodes_to_process,
726 &nodes_to_continue_processing,
727 &entry](FrameNavigationEntry* frame_entry) {
728 // Find the |node| that matches |frame_entry|, if any.
729 FrameTreeNode* node = nullptr;
730 if (frame_entry == entry->root_node()->frame_entry) {
731 node = controller_->frame_tree().root();
732 } else {
733 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
734 if (it == names_to_nodes_.end())
735 return;
736 node = it->second;
737 }
738
739 // Skip this node if a previous step determine there are no longer
740 // relevant navigation API keys in this direction.
741 if (nodes_to_process.find(node) == nodes_to_process.end())
742 return;
743
744 // Stop processing |node| if we reach a point where it's cross-origin.
745 // See also PopulateSingleNavigationApiHistoryEntryVector().
746 url::Origin frame_entry_origin =
747 frame_entry->committed_origin().value_or(url::Origin::Resolve(
748 frame_entry->url(),
749 frame_entry->initiator_origin().value_or(url::Origin())));
750 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
751 return;
752
753 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
754 frame_entry->navigation_api_key());
755 // Mark |node| as needing more processing for the next entry.
756 nodes_to_continue_processing.insert(node);
757
758 // Check whether |node| went cross-document. If so, its children are
759 // no longer the same conceptual iframe as the current one, and
760 // should no longer be processed. This check is intentionally done
761 // after processing the current |node|, which may still have relevant
762 // discarded API keys.
763 if (frame_entry->document_sequence_number() !=
764 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50765 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31766 nodes_to_process.erase(descendant);
767 }
768 });
769
770 nodes_to_process.swap(nodes_to_continue_processing);
771 }
772}
773
774NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
775 std::set<std::string> all_keys;
776 // Find all remaining navigation API keys after some entries have been
777 // removed.
778 for (auto& entry : controller_->entries_) {
779 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
780 all_keys.insert(frame_entry->navigation_api_key());
781 });
782 }
783
784 // Notify each frame in the renderer of any disposed navigation API keys.
785 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
786 std::vector<std::string> disposed_keys;
787 for (const auto& key : id_to_keys.second) {
788 if (all_keys.find(key) == all_keys.end())
789 disposed_keys.push_back(key);
790 }
791 if (disposed_keys.empty())
792 continue;
793
794 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
795 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
796 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
797 }
798}
799
[email protected]d202a7c2012-01-04 07:53:47800NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00801 BrowserContext* browser_context,
802 FrameTree& frame_tree,
803 NavigationControllerDelegate* delegate)
804 : frame_tree_(frame_tree),
805 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57806 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22807 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37808 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
809 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37810 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29811}
812
[email protected]d202a7c2012-01-04 07:53:47813NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00814 // The NavigationControllerImpl might be called inside its delegate
815 // destructor. Calling it is not valid anymore.
816 delegate_ = nullptr;
817 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29818}
819
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57820BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55821 return browser_context_;
822}
823
[email protected]d202a7c2012-01-04 07:53:47824void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30825 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36826 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57827 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47828 // Note that it's possible for `entries_` to contain multiple entries at this
829 // point, as Restore() might be called on a NavigationController that is
830 // already used (e.g. due to WebView's restoreState() API), not only for fresh
831 // NavigationControllers. These entries are not cleared to preserve legacy
832 // behavior and also because `pending_entry_` might point to one of the
833 // pre-existing entries. An exception for this is when `entries_` contains
834 // only the initial NavigationEntry, which must be removed.
835
836 // Do not proceed if selected_navigation will be out of bounds for the updated
837 // entries_ list, since it will be assigned to last_committed_entry_index_ and
838 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58839 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47840 // is empty, since there should be no work to do (rather than marking the
841 // existing entries as needing reload). Also consider returning early if the
842 // selected index is -1, which represents a no-committed-entry state.
843 if (selected_navigation < -1 ||
844 selected_navigation >=
845 base::checked_cast<int>(entries->size() + entries_.size())) {
846 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24847 }
Charlie Reis23c26da2022-01-29 00:57:47848
Rakina Zata Amni46087a12022-11-11 08:28:38849 // There will always be at least one entry (new NavigationControllers will
850 // have the initial NavigationEntry).
851 if (selected_navigation == -1)
852 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47853
Rakina Zata Amni46087a12022-11-11 08:28:38854 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
855 // If we are on the initial NavigationEntry, it must be the only entry in
856 // the list. Since it's impossible to do a history navigation to the
857 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
858 // `pending_entry` might be set for a new non-history navigation).
859 // Note that we should not clear `entries_` if `entries` is empty (when
860 // InitialNavigationEntry mode is enabled), since that would leave us
861 // without any NavigationEntry.
862 CHECK_EQ(1, GetEntryCount());
863 CHECK_EQ(-1, pending_entry_index_);
864 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47865 }
[email protected]ce3fa3c2009-04-20 19:55:57866
[email protected]ce3fa3c2009-04-20 19:55:57867 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44868 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03869 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47870 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43871 if (entry->GetURL().is_empty()) {
872 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01873 // persisting the initial NavigationEntry [which is no longer possible but
874 // some old persisted sessions might still contain it] or when the
875 // serializer failed to write the URL because it's too long). Trying to
876 // restore and navigate to an entry with an empty URL will result in
877 // crashes, so change the URL to about:blank. See also
878 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43879 entry->SetURL(GURL(url::kAboutBlankURL));
880 }
dcheng36b6aec92015-12-26 06:16:36881 entries_.push_back(
882 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47883 }
avif16f85a72015-11-13 18:25:03884
885 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
886 // cleared out safely.
887 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57888
889 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36890 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57891}
892
toyoshim6142d96f2016-12-19 09:07:25893void NavigationControllerImpl::Reload(ReloadType reload_type,
894 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03895 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
896 (int)reload_type);
897 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
898 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28899 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28900 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32901 int current_index = -1;
902
Carlos IL42b416592019-10-07 23:10:36903 if (entry_replaced_by_post_commit_error_) {
904 // If there is an entry that was replaced by a currently active post-commit
905 // error navigation, this can't be the initial navigation.
906 DCHECK(!IsInitialNavigation());
907 // If the current entry is a post commit error, we reload the entry it
908 // replaced instead. We leave the error entry in place until a commit
909 // replaces it, but the pending entry points to the original entry in the
910 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
911 // case that pending_entry_ != entries_[pending_entry_index_].
912 entry = entry_replaced_by_post_commit_error_.get();
913 current_index = GetCurrentEntryIndex();
914 } else if (IsInitialNavigation() && pending_entry_) {
915 // If we are reloading the initial navigation, just use the current
916 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32917 entry = pending_entry_;
918 // The pending entry might be in entries_ (e.g., after a Clone), so we
919 // should also update the current_index.
920 current_index = pending_entry_index_;
921 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00922 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32923 current_index = GetCurrentEntryIndex();
924 if (current_index != -1) {
creis3da03872015-02-20 21:12:32925 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32926 }
[email protected]979a4bc2013-04-24 01:27:15927 }
[email protected]241db352013-04-22 18:04:05928
[email protected]59167c22013-06-03 18:07:32929 // If we are no where, then we can't reload. TODO(darin): We should add a
930 // CanReload method.
931 if (!entry)
932 return;
933
Rakina Zata Amnif297a802022-01-18 03:53:43934 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
935 // We should never navigate to an existing initial NavigationEntry that is
936 // the initial NavigationEntry for the initial empty document that hasn't
937 // been overridden by the synchronous about:blank commit, to preserve
938 // legacy behavior where trying to reload when the main frame is on the
939 // initial empty document won't result in a navigation. See also
940 // https://crbug.com/1277414.
941 return;
942 }
943
Aran Gilman37d11632019-10-08 23:07:15944 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30945 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07946 // they really want to do this. If they do, the dialog will call us back
947 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57948 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02949
[email protected]106a0812010-03-18 00:15:12950 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57951 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47952 return;
initial.commit09911bf2008-07-26 23:55:29953 }
Lei Zhang96031532019-10-10 19:05:47954
Wang Huia25efabc2022-09-24 17:27:22955 // Set ReloadType for |entry|.
956 entry->set_reload_type(reload_type);
957
Lei Zhang96031532019-10-10 19:05:47958 if (!IsInitialNavigation())
959 DiscardNonCommittedEntries();
960
961 pending_entry_ = entry;
962 pending_entry_index_ = current_index;
963 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
964
Nate Chapin45f620582021-09-30 17:45:43965 // location.reload() goes through BeginNavigation, so all reloads triggered
966 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13967 NavigateToExistingPendingEntry(
968 reload_type,
969 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:37970 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:13971 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29972}
973
[email protected]d202a7c2012-01-04 07:53:47974void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48975 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12976}
977
[email protected]d202a7c2012-01-04 07:53:47978void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49979 // If the pending reload type has been cleared by another navigation
980 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48981 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49982 return;
[email protected]106a0812010-03-18 00:15:12983 }
Wang Hui96ab1012022-10-11 02:05:49984 Reload(pending_reload_, false);
985 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12986}
987
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57988bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09989 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11990}
991
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57992bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38993 // Check that we're on the initial NavigationEntry and that this is not a
994 // cloned tab.
995 return IsInitialNavigation() && GetEntryCount() == 1 &&
996 GetLastCommittedEntry()->IsInitialEntry() &&
997 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40998}
999
Aran Gilman37d11632019-10-08 23:07:151000NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1001 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581002 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031003 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581004}
1005
Adithya Srinivasan9b0c99c2021-08-10 15:19:451006NavigationEntryImpl*
1007NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1008 int nav_entry_id) const {
1009 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1010 if (entry)
1011 return entry;
1012 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521013 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451014 : nullptr;
1015}
1016
W. James MacLeanc07dc41b2022-07-25 18:52:161017void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571018 const url::Origin& origin) {
1019 for (int i = 0; i < GetEntryCount(); i++) {
1020 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161021 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571022 }
1023 if (entry_replaced_by_post_commit_error_) {
1024 // It's possible we could come back to this entry if the error
1025 // page/interstitial goes away.
1026 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161027 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571028 }
W. James MacLean1c40862c2020-04-27 21:05:571029}
1030
avi25764702015-06-23 15:43:371031void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571032 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001033 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371034 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271035 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201036}
1037
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571038NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471039 if (pending_entry_)
1040 return pending_entry_;
1041 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201042}
1043
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571044NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321045 // The pending entry is safe to return for new (non-history), browser-
1046 // initiated navigations. Most renderer-initiated navigations should not
1047 // show the pending entry, to prevent URL spoof attacks.
1048 //
1049 // We make an exception for renderer-initiated navigations in new tabs, as
1050 // long as no other page has tried to access the initial empty document in
1051 // the new tab. If another page modifies this blank page, a URL spoof is
1052 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321053 bool safe_to_show_pending =
1054 pending_entry_ &&
1055 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091056 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321057 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461058 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321059
1060 // Also allow showing the pending entry for history navigations in a new tab,
1061 // such as Ctrl+Back. In this case, no existing page is visible and no one
1062 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151063 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1064 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321065 safe_to_show_pending = true;
1066
1067 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191068 return pending_entry_;
1069 return GetLastCommittedEntry();
1070}
1071
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571072int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201073 if (pending_entry_index_ != -1)
1074 return pending_entry_index_;
1075 return last_committed_entry_index_;
1076}
1077
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571078NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381079 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031080 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201081}
1082
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571083bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351084 const std::string& mime_type = frame_tree_->root()
1085 ->current_frame_host()
1086 ->GetPage()
1087 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531088 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1089 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271090 NavigationEntry* visible_entry = GetVisibleEntry();
1091 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391092 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161093}
1094
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571095int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271096 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451097 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271098 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551099 return last_committed_entry_index_;
1100}
1101
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571102int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451103 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291104 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551105 return static_cast<int>(entries_.size());
1106}
1107
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571108NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371109 if (index < 0 || index >= GetEntryCount())
1110 return nullptr;
1111
avif16f85a72015-11-13 18:25:031112 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251113}
1114
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571115NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471116 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201117}
1118
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571119int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461120 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031121}
1122
Arthur Sonzognic686e8f2024-01-11 08:36:371123std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031124 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591125 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1126 return index;
1127 }
Shivani Sharma298d12852019-01-22 20:04:031128 }
Arthur Sonzognic686e8f2024-01-11 08:36:371129 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591130}
1131
1132bool NavigationControllerImpl::CanGoBack() {
1133 return GetIndexForGoBack().has_value();
1134}
1135
Arthur Sonzognic686e8f2024-01-11 08:36:371136std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591137 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1138 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1139 return index;
1140 }
1141 }
Arthur Sonzognic686e8f2024-01-11 08:36:371142 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201143}
1144
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571145bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591146 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201147}
1148
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571149bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031150 int index = GetIndexForOffset(offset);
1151 return index >= 0 && index < GetEntryCount();
1152}
1153
Xiaohan Wang7f8052e02022-01-14 18:44:281154#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151155bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151156 if (offset == 0)
1157 return true;
1158 int increment = offset > 0 ? 1 : -1;
1159 int non_skippable_entries = 0;
1160 for (int index = GetIndexForOffset(increment);
1161 index >= 0 && index < GetEntryCount(); index += increment) {
1162 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1163 non_skippable_entries++;
1164
1165 if (non_skippable_entries == std::abs(offset))
1166 return true;
1167 }
1168 return false;
1169}
1170#endif
1171
[email protected]d202a7c2012-01-04 07:53:471172void NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371173 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061174
Kevin McNeeedc481c2023-04-27 22:30:581175 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211176
Kevin McNee3b3a56192023-03-17 14:40:591177 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201178}
1179
[email protected]d202a7c2012-01-04 07:53:471180void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161181 // Note that at least one entry (the last one) will be non-skippable since
1182 // entries are marked skippable only when they add another entry because of
1183 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371184 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591185
Kevin McNeeedc481c2023-04-27 22:30:581186 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591187
1188 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201189}
1190
[email protected]d202a7c2012-01-04 07:53:471191void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131192 GoToIndex(index, /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371193 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:131194 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161195}
1196
William Liu62ae26c2024-08-08 14:28:161197std::vector<base::WeakPtr<NavigationRequest>>
1198NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201199 int index,
1200 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371201 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131202 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201203 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441204 TRACE_EVENT0("browser,navigation,benchmark",
1205 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501206 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1207 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1208 entries_.size());
1209 // Indices should have have been validated by the caller.
1210 CHECK_GE(index, 0);
1211 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201212
Rakina Zata Amnif297a802022-01-18 03:53:431213 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1214 // We should never navigate to an existing initial NavigationEntry that is
1215 // the initial NavigationEntry for the initial empty document that hasn't
1216 // been overridden by the synchronous about:blank commit, to preserve
1217 // legacy behavior where trying to reload when the main frame is on the
1218 // initial empty document won't result in a navigation. See also
1219 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161220 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431221 }
1222
[email protected]cbab76d2008-10-13 22:42:471223 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201224
arthursonzogni5c4c202d2017-04-25 23:41:271225 DCHECK_EQ(nullptr, pending_entry_);
1226 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431227
arthursonzogni5c4c202d2017-04-25 23:41:271228 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201229 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271230 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1231 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
William Liuec04e382024-05-23 18:03:271232 return NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
1233 soft_navigation_heuristics_task_id,
1234 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201235}
1236
[email protected]d202a7c2012-01-04 07:53:471237void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121238 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031239 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201240 return;
1241
[email protected]9ba14052012-06-22 23:50:031242 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201243}
1244
Nate Chapinbf682fa32022-09-26 22:41:201245void NavigationControllerImpl::GoToOffsetFromRenderer(
1246 int offset,
Yoav Weiss8c573952022-11-17 17:35:131247 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371248 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131249 soft_navigation_heuristics_task_id) {
Nate Chapinbb74c5a52023-07-21 23:13:351250 // Note: This is actually reached in unit tests.
1251 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431252 return;
1253
Nate Chapinbf682fa32022-09-26 22:41:201254 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131255 soft_navigation_heuristics_task_id,
1256 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431257}
1258
William Liu62ae26c2024-08-08 14:28:161259std::vector<base::WeakPtr<NavigationRequest>>
1260NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271261 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1262 /*soft_navigation_heuristics_task_id=*/std::nullopt,
1263 /*navigation_api_key=*/nullptr);
1264}
1265
Xiaohan Wang7f8052e02022-01-14 18:44:281266#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151267void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1268 // Note: This is actually reached in unit tests.
1269 if (!CanGoToOffsetWithSkipping(offset))
1270 return;
1271
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421272 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151273 GoToIndex(GetIndexForOffset(offset));
1274 return;
1275 }
1276 int increment = offset > 0 ? 1 : -1;
1277 // Find the offset without counting skippable entries.
1278 int target_index = GetIndexForOffset(increment);
1279 int non_skippable_entries = 0;
1280 for (int index = target_index; index >= 0 && index < GetEntryCount();
1281 index += increment) {
1282 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1283 non_skippable_entries++;
1284
1285 if (non_skippable_entries == std::abs(offset)) {
1286 target_index = index;
1287 break;
1288 }
1289 }
1290
1291 GoToIndex(target_index);
1292}
1293#endif
1294
[email protected]41374f12013-07-24 02:49:281295bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151296 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281297 return false;
[email protected]6a13a6c2011-12-20 21:47:121298
[email protected]43032342011-03-21 14:10:311299 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281300 return true;
[email protected]cbab76d2008-10-13 22:42:471301}
1302
Michael Thiessen9b14d512019-09-23 21:19:471303void NavigationControllerImpl::PruneForwardEntries() {
1304 DiscardNonCommittedEntries();
1305 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471306 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471307 if (num_removed <= 0)
1308 return;
Nate Chapin9eb16be72022-09-23 22:54:311309 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471310 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1311 NotifyPrunedEntries(this, remove_start_index /* start index */,
1312 num_removed /* count */);
1313}
1314
Aran Gilman37d11632019-10-08 23:07:151315void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1316 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321317 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311318 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511319 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1320 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321321 }
1322}
1323
Harkiran Bolariaba823e42021-05-21 18:30:361324base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1325 const GURL& url,
1326 const Referrer& referrer,
1327 ui::PageTransition transition,
1328 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471329 LoadURLParams params(url);
1330 params.referrer = referrer;
1331 params.transition_type = transition;
1332 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361333 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471334}
1335
Harkiran Bolariaba823e42021-05-21 18:30:361336base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1337 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061338 if (params.is_renderer_initiated)
1339 DCHECK(params.initiator_origin.has_value());
1340
naskob8744d22014-08-28 17:07:431341 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151342 "NavigationControllerImpl::LoadURLWithParams", "url",
1343 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291344 bool is_explicit_navigation =
1345 GetContentClient()->browser()->IsExplicitNavigation(
1346 params.transition_type);
1347 if (HandleDebugURL(params.url, params.transition_type,
1348 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431349 // If Telemetry is running, allow the URL load to proceed as if it's
1350 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491351 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181352 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361353 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181354 }
[email protected]47752982014-07-29 08:01:431355 }
[email protected]8bf1048012012-02-08 01:22:181356
[email protected]cf002332012-08-14 19:17:471357 // Checks based on params.load_type.
1358 switch (params.load_type) {
1359 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431360 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541361#if BUILDFLAG(IS_ANDROID)
1362 case LOAD_TYPE_PDF_ANDROID:
1363#endif
[email protected]cf002332012-08-14 19:17:471364 break;
1365 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261366 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211367 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471368 }
1369 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461370 }
[email protected]e47ae9472011-10-13 19:48:341371
[email protected]e47ae9472011-10-13 19:48:341372 // The user initiated a load, we don't need to reload anymore.
1373 needs_reload_ = false;
1374
Harkiran Bolariaba823e42021-05-21 18:30:361375 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441376}
1377
Charlie Reis4c53a962023-06-21 23:17:531378void NavigationControllerImpl::LoadOriginalRequestURL() {
1379 // If the original request URL is not valid, matches the current URL, or
1380 // involves POST data, then simply reload. The POST check avoids issues with
1381 // sending data to the wrong page.
1382 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1383 const GURL& original_request_url =
1384 GetLastCommittedEntry()->GetOriginalRequestURL();
1385 if (!original_request_url.is_valid() ||
1386 original_request_url == last_committed_url ||
1387 GetLastCommittedEntry()->GetHasPostData()) {
1388 Reload(ReloadType::NORMAL, true);
1389 return;
1390 }
1391
1392 // Otherwise, attempt to load the original request URL without any of the
1393 // other data from the current NavigationEntry, replacing the current entry.
1394 // Loading the original URL is useful in cases such as modifying the user
1395 // agent.
1396 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1397 std::make_unique<NavigationController::LoadURLParams>(
1398 original_request_url);
1399 load_params->should_replace_current_entry = true;
1400 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1401 LoadURLWithParams(*load_params.get());
1402}
1403
Mohamed Abdelhalim833de902019-09-16 17:41:451404bool NavigationControllerImpl::PendingEntryMatchesRequest(
1405 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191406 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451407 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191408}
1409
[email protected]d202a7c2012-01-04 07:53:471410bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321411 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071412 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331413 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441414 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251415 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561416 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131417 NavigationRequest* navigation_request) {
1418 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331419
1420 // Note: validation checks and renderer kills due to invalid commit messages
1421 // must happen before getting here, in
1422 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1423 // effects of the navigation have already occurred.
1424
[email protected]cd2e15742013-03-08 04:08:311425 is_initial_navigation_ = false;
1426
Wang Hui96ab1012022-10-11 02:05:491427 // Any pending request to repost a form submission is no longer valid, since a
1428 // different NavigationEntry is committing.
1429 pending_reload_ = ReloadType::NONE;
1430
[email protected]0e8db942008-09-24 21:21:481431 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431432 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451433 if (entry_replaced_by_post_commit_error_) {
1434 // Same document navigation events with a post-commit error should already
1435 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1436 // reaching here.
1437 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331438
Xinghui Lub9e86a352024-05-17 16:29:421439 if (pending_entry_) {
1440 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1441 // `pending_entry_` isn't pointing to the last committed entry.
1442 // Instead, all reload approaches (e.g., in `Reload` and
1443 // `LoadIfNecessary`) should attempt to load the
1444 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1445 // entry itself.
1446 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1447 << "Incorrectly reloading the post commit error page entry.";
1448 }
Xinghui Lue4e50be2024-05-15 21:46:001449
Rakina Zata Amnie2d31312022-11-18 03:38:451450 // Any commit while a post-commit error page is showing should put the
1451 // original entry back, replacing the error page's entry. This includes
1452 // reloads, where the original entry was used as the pending entry and
1453 // should now be at the correct index at commit time.
1454 entries_[last_committed_entry_index_] =
1455 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481456 }
Rakina Zata Amnie2d31312022-11-18 03:38:451457 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1458 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001459 // Must honor user agent overrides in the |navigation_request|, such as
1460 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1461 // result, besides comparing |pending_entry_|'s user agent against
1462 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1463 // agent against LastCommittedEntry's.
1464 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541465 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1466 (PendingEntryMatchesRequest(navigation_request) &&
1467 pending_entry_->GetIsOverridingUserAgent() !=
1468 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001469 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451470 }
[email protected]ecd9d8702008-08-28 22:10:171471
Dave Tapuskaa2ab4f252021-07-08 21:31:281472 bool is_main_frame_navigation = !rfh->GetParent();
1473
Alexander Timind2f2e4f22019-04-02 20:04:531474 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1475 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281476 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141477 // BackForwardCacheMetrics to be associated with the new navigation's
1478 // NavigationEntry, by either creating a new object or reusing the previous
1479 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281480 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211481 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141482 back_forward_cache_metrics = BackForwardCacheMetrics::
1483 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281484 GetLastCommittedEntry(), is_main_frame_navigation,
1485 params.document_sequence_number);
1486 }
Yuzu Saijo29f96ca92022-12-08 04:54:121487
Alexander Timind2f2e4f22019-04-02 20:04:531488 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281489 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451490 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1491 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531492 }
1493 }
1494
Rakina Zata Amnifd8370b2022-11-14 13:32:251495 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1496 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091497 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251498 details->did_replace_entry =
1499 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091500
fdegans9caf66a2015-07-30 21:10:421501 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111502 // except for restored entries. This should be true even if the current commit
1503 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291504 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481505 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081506 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111507
1508 // Only make changes based on the pending entry if the NavigationRequest
1509 // matches it. Otherwise, the pending entry may be for a different request
1510 // (e.g., if a slow history navigation is pending while an auto-subframe
1511 // commit occurs).
1512 if (PendingEntryMatchesRequest(navigation_request)) {
1513 // It is no longer necessary to consider the pending entry as restored.
1514 if (pending_entry_->IsRestored()) {
1515 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1516 was_restored = true;
1517 }
[email protected]e9ba4472008-09-14 15:42:431518
Charlie Reisf8cde712022-10-20 16:25:091519 // If the SiteInstance has changed from the matching pending entry, this
1520 // must be treated as a new navigation with replacement. Set the replacement
1521 // bit here and ClassifyNavigation will identify this case and return
1522 // NEW_ENTRY.
1523 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1524 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1525 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251526 // TODO(nasko,creis,rakina): Move this to happen before committing the
1527 // navigation. This is a bit complicated because we don't currently
1528 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091529 details->did_replace_entry = true;
1530 }
Nasko Oskovaee2f862018-06-15 00:05:521531 }
[email protected]bcd904482012-02-01 01:54:221532
[email protected]e9ba4472008-09-14 15:42:431533 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101534 NavigationType navigation_type =
1535 ClassifyNavigation(rfh, params, navigation_request);
1536 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451537
Rakina Zata Amnie2d31312022-11-18 03:38:451538 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451539 // Ensure that this navigation does not add a navigation entry, since
1540 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1541 // beyond the last committed one. Therefore, `should_replace_current_entry`
1542 // should be set, which replaces the current entry, or this should be a
1543 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251544 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331545 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451546 }
1547
Rakina Zata Amnie2d31312022-11-18 03:38:451548 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551549 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241550 // This is a subframe navigation on the initial empty document, which used
1551 // to not have a NavigationEntry to attach to. Now it can attach to the
1552 // initial NavigationEntry, and we must ensure that its NavigationEntry
1553 // will keep the "initial NavigationEntry" status and won't append a new
1554 // NavigationEntry (it should always do replacement instead).
1555 // See also https://crbug.com/1277414.
1556 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551557 // Subframe navigation on initial NavigationEntry must not append a new
1558 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1559 // means every subframe navigation that happens while we're on the initial
1560 // NavigationEntry will always reuse the existing NavigationEntry and
1561 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101562 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1563 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551564 // This is a navigation that modifies the initial NavigationEntry, either
1565 // for a replacement or a reload. The initial NavigationEntry should
1566 // retain its "initial NavigationEntry" status in this case.
1567 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241568 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251569 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1570 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241571 // This is a synchronous about:blank navigation on the main frame, which
1572 // used to not create a NavigationEntry when we have no NavigationEntry on
1573 // FrameTree creation. We now have the initial NavigationEntry and are on
1574 // the initial NavigationEntry. To preserve old behavior, we should still
1575 // keep the "initial" status for the new NavigationEntry that we will
1576 // create for this navigation, so that subframe navigations under the
1577 // synchronously committed about:blank document will never append new
1578 // NavigationEntry, and instead will just reuse the initial
1579 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1580 // See also https://crbug.com/1277414.
1581 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551582 }
1583 }
1584 DCHECK(!details->should_stay_as_initial_entry ||
1585 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201586
eugenebutee08663a2017-04-27 17:43:121587 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441588 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121589
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071590 details->is_prerender_activation =
1591 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241592 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1593 ->GetOutermostMainFrame()
1594 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071595
Peter Boströmd7592132019-01-30 04:50:311596 // Make sure we do not discard the pending entry for a different ongoing
1597 // navigation when a same document commit comes in unexpectedly from the
1598 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1599 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581600 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061601 bool keep_pending_entry =
1602 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101603 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061604 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311605
Miyoung Shin3299cbf2022-11-22 01:41:101606 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061607 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491608 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051609 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561610 previous_document_had_history_intervention_activation,
1611 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431612 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061613 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491614 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1615 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001616 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431617 break;
[email protected]8ff00d72012-10-23 19:12:211618 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471619 RendererDidNavigateNewSubframe(
1620 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561621 previous_document_had_history_intervention_activation,
1622 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431623 break;
[email protected]8ff00d72012-10-23 19:12:211624 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391625 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251626 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001627 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081628 // We don't send a notification about auto-subframe PageState during
1629 // UpdateStateForFrame, since it looks like nothing has changed. Send
1630 // it here at commit time instead.
1631 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431632 return false;
creis59d5a47cb2016-08-24 23:57:191633 }
[email protected]e9ba4472008-09-14 15:42:431634 break;
Aran Gilman37d11632019-10-08 23:07:151635 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211636 NOTREACHED();
[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_) {
Charlie Reisb5f39cf2024-11-12 16:55:011845 // If the renderer was going to a pending entry that got cleared because of
1846 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511847 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491848 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061849 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381850 }
1851
Charlie Reisc0f17d2d2021-01-12 18:52:491852 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101853 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511854 trace_return.traced_value()->SetInteger("existing_entry_index",
1855 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381856 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441857 // The renderer has committed a navigation to an entry that no longer
1858 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491859 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061860 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381861 }
1862
avi7c6f35e2015-05-08 17:52:381863 // Since we weeded out "new" navigations above, we know this is an existing
1864 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491865 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061866 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381867}
1868
Rakina Zata Amni3460d382021-10-29 00:43:371869void NavigationControllerImpl::UpdateNavigationEntryDetails(
1870 NavigationEntryImpl* entry,
1871 RenderFrameHostImpl* rfh,
1872 const mojom::DidCommitProvisionalLoadParams& params,
1873 NavigationRequest* request,
1874 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001875 bool is_new_entry,
1876 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371877 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171878 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371879 entry->AddOrUpdateFrameEntry(
1880 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571881 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371882 rfh->GetSiteInstance(), nullptr, params.url,
1883 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171884 Referrer(*params.referrer),
1885 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371886 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171887 request ? request->GetRedirectChain() : redirects, params.page_state,
1888 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371889 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171890 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211891 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171892 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371893
1894 if (rfh->GetParent()) {
1895 // Only modify the NavigationEntry for main frame navigations.
1896 return;
1897 }
1898 if (entry->update_virtual_url_with_url())
1899 UpdateVirtualURLToURL(entry, params.url);
1900 // Don't use the page type from the pending entry. Some interstitial page
1901 // may have set the type to interstitial. Once we commit, however, the page
1902 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171903 entry->set_page_type((request && request->DidEncounterError())
1904 ? PAGE_TYPE_ERROR
1905 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431906 if (commit_details && commit_details->should_stay_as_initial_entry) {
1907 // Retain the "initial NavigationEntry" status.
1908 if (request->IsSameDocument()) {
1909 // If this is for a same-document navigation, the NavigationEntry must be
1910 // reused and should already be marked as the initial NavigationEntry.
1911 DCHECK(entry->IsInitialEntry());
1912 } else {
1913 // If this is for a cross-document navigation, it can be caused by a
1914 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1915 // "for synchronous about:blank" in the latter case, and also when it is
1916 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1917 // is not for a synchronous about:blank commit.
1918 NavigationEntryImpl::InitialNavigationEntryState new_state =
1919 NavigationEntryImpl::InitialNavigationEntryState::
1920 kInitialNotForSynchronousAboutBlank;
1921 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1922 request->is_synchronous_renderer_commit()) {
1923 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1924 kInitialForSynchronousAboutBlank;
1925 }
1926 entry->set_initial_navigation_entry_state(new_state);
1927 }
1928 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1929 // Remove the "initial NavigationEntry" status.
1930 entry->set_initial_navigation_entry_state(
1931 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001932 }
Rakina Zata Amniddf10502022-01-15 02:56:551933
Rakina Zata Amni3460d382021-10-29 00:43:371934 if (is_new_entry) {
1935 // Some properties of the NavigationEntry are only set when the entry is
1936 // new (we aren't reusing it).
1937 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171938 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:401939 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:011940 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
1941 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:371942 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1943 } else {
1944 // We are reusing the NavigationEntry. The site instance will normally be
1945 // the same except for a few cases:
1946 // 1) session restore, when no site instance will be assigned or
1947 // 2) redirect, when the site instance is reset.
1948 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1949 entry->site_instance() == rfh->GetSiteInstance());
1950 }
1951}
1952
Rakina Zata Amniafd3c6582021-11-30 06:19:171953void NavigationControllerImpl::CreateInitialEntry() {
1954 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031955 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171956 auto params = mojom::DidCommitProvisionalLoadParams::New();
1957 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1958 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1959 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:401960 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:171961 params->http_status_code = 0;
1962 params->url_is_unreachable = false;
1963 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171964 params->post_id = -1;
1965 params->embedding_token = base::UnguessableToken::Create();
1966 params->navigation_token = base::UnguessableToken::Create();
1967 params->did_create_new_entry = true;
1968 params->origin = rfh->GetLastCommittedOrigin();
1969 params->should_update_history = true;
1970 params->item_sequence_number = 0;
1971 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151972 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171973 params->transition = is_in_fenced_frame_tree
1974 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1975 : ui::PAGE_TRANSITION_LINK;
1976 params->referrer = blink::mojom::Referrer::New();
1977
Rakina Zata Amniafd3c6582021-11-30 06:19:171978 auto new_entry = std::make_unique<NavigationEntryImpl>(
1979 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381980 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211981 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1982 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1983 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171984 UpdateNavigationEntryDetails(
1985 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001986 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1987 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171988
1989 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1990 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001991 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171992}
1993
Charlie Reisc0f17d2d2021-01-12 18:52:491994void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321995 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071996 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361997 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441998 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561999 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002000 NavigationRequest* request,
2001 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572002 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372003 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452004 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372005 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522006 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2007 initiator_base_url = request->common_params().initiator_base_url;
2008 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062009
creisf49dfc92016-07-26 17:05:182010 // First check if this is an in-page navigation. If so, clone the current
2011 // entry instead of looking at the pending entry, because the pending entry
2012 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452013 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302014 FrameNavigationEntry* previous_frame_entry =
2015 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452016 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482017 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572018 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082019 rfh->GetSiteInstance(), nullptr, params.url,
2020 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212021 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092022 request->GetRedirectChain(), params.page_state, params.method,
2023 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392024 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302025 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572026 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302027 // FrameNavigationEntry.
2028 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572029 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032030
creisf49dfc92016-07-26 17:05:182031 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032032 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522033 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2034 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572035 // TODO(jam): we had one report of this with a URL that was redirecting to
2036 // only tildes. Until we understand that better, don't copy the cert in
2037 // this case.
2038 new_entry->GetSSL() = SSLStatus();
2039 }
creisf49dfc92016-07-26 17:05:182040
Patrick Monette50e8bd82019-06-13 22:40:452041 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2042 // that |frame_entry| should now have a reference count of exactly 2: one
2043 // due to the local variable |frame_entry|, and another due to |new_entry|
2044 // also retaining one. This should never fail, because it's the main frame.
2045 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182046 }
2047
Harkiran Bolaria59290d62021-03-17 01:53:012048 // If this is an activation navigation from a prerendered page, transfer the
2049 // new entry from an entry already created and stored in the
2050 // NavigationRequest. |new_entry| will not have been set prior to this as
2051 // |is_same_document| is mutually exclusive with
2052 // |IsPrerenderedPageActivation|.
2053 if (request->IsPrerenderedPageActivation()) {
2054 DCHECK(!is_same_document);
2055 DCHECK(!new_entry);
2056 new_entry = request->TakePrerenderNavigationEntry();
2057 DCHECK(new_entry);
2058 }
2059
Charlie Reisc0f17d2d2021-01-12 18:52:492060 // Only make a copy of the pending entry if it is appropriate for the new
2061 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452062 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042063 // 1. The SiteInstance hasn't been assigned to something else.
2064 // 2. The pending entry was intended as a new entry, rather than being a
2065 // history navigation that was interrupted by an unrelated,
2066 // renderer-initiated navigation.
2067 // TODO(csharrison): Investigate whether we can remove some of the coarser
2068 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452069 if (!new_entry && PendingEntryMatchesRequest(request) &&
2070 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342071 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432072 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352073 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432074
Camille Lamy62b826012019-02-26 09:15:472075 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452076 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182077 }
2078
Charlie Reisc0f17d2d2021-01-12 18:52:492079 // For cross-document commits with no matching pending entry, create a new
2080 // entry.
creisf49dfc92016-07-26 17:05:182081 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062082 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072083 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212084 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582085 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452086 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172087 nullptr, // blob_url_loader_factory
2088 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242089
2090 // Find out whether the new entry needs to update its virtual URL on URL
2091 // change and set up the entry accordingly. This is needed to correctly
2092 // update the virtual URL when replaceState is called after a pushState.
2093 GURL url = params.url;
2094 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492095 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412096 // update the virtual URL based on the new URL. For example, this is needed
2097 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2098 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372099 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2100 &url, browser_context_, &needs_update);
2101 new_entry->set_update_virtual_url_with_url(needs_update);
2102
Camille Lamy62b826012019-02-26 09:15:472103 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452104 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432105 }
2106
Alison Gale770f3fc2024-04-27 00:39:582107 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2108 // set for prerendered contents, if any. This is because
2109 // prerendering/activation technically won't be creating a new document.
2110 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2111 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012112 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372113 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2114 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002115 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082116
Harkiran Bolaria59290d62021-03-17 01:53:012117 // history.pushState() is classified as a navigation to a new page, but sets
2118 // is_same_document to true. In this case, we already have the title and
2119 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452120 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012121 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2122 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2123 }
[email protected]3a868f212014-08-09 10:41:192124 }
[email protected]ff64b3e2014-05-31 04:07:332125
[email protected]60d6cca2013-04-30 08:47:132126 DCHECK(!params.history_list_was_cleared || !replace_entry);
2127 // The browser requested to clear the session history when it initiated the
2128 // navigation. Now we know that the renderer has updated its state accordingly
2129 // and it is safe to also clear the browser side history.
2130 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552131 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132132 entries_.clear();
2133 last_committed_entry_index_ = -1;
2134 }
2135
Nasko Oskovaee2f862018-06-15 00:05:522136 // If this is a new navigation with replacement and there is a
2137 // pending_entry_ which matches the navigation reported by the renderer
2138 // process, then it should be the one replaced, so update the
2139 // last_committed_entry_index_ to use it.
2140 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092141 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522142 last_committed_entry_index_ = pending_entry_index_;
2143 }
2144
Alexander Timine3ec4192020-04-20 16:39:402145 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562146 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402147 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052148
Yuzu Saijoa725585f2022-11-28 04:14:032149 // If this is a history navigation and the old entry has an existing
2150 // back/forward cache metrics object, keep using the old one so that the
2151 // reasons logged from the last time the page navigated gets preserved.
2152 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2153 request)) {
2154 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2155 // because some tests do not have a pending entry.
2156 NavigationEntryImpl* entry =
2157 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2158 if (entry && entry->back_forward_cache_metrics()) {
2159 scoped_refptr<BackForwardCacheMetrics> metrics =
2160 entry->TakeBackForwardCacheMetrics();
2161 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2162 }
2163 }
2164
Carlos IL42b416592019-10-07 23:10:362165 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312166 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152167 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432168}
2169
Charlie Reisc0f17d2d2021-01-12 18:52:492170void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322171 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072172 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362173 bool is_same_document,
jam48cea9082017-02-15 06:13:292174 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452175 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002176 bool keep_pending_entry,
2177 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562178 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2179 << "that a last committed entry exists.";
2180
[email protected]e9ba4472008-09-14 15:42:432181 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002182 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432183
Charlie Reis7e2cb6d2021-01-26 01:27:162184 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002185 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162186 // We're guaranteed to have a last committed entry if intended_as_new_entry
2187 // is true.
avicbdc4c12015-07-01 16:07:112188 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162189
2190 // If the NavigationRequest matches a new pending entry and is classified as
2191 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2192 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092193 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162194 // Note: The pending entry will usually have a real ReloadType here, but
2195 // it can still be ReloadType::NONE in cases that
2196 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2197
2198 // If we classified this correctly, the SiteInstance should not have
2199 // changed.
2200 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2201
2202 // For converted reloads, we assign the entry's unique ID to be that of
2203 // the new one. Since this is always the result of a user action, we want
2204 // to dismiss infobars, etc. like a regular user-initiated navigation.
2205 entry->set_unique_id(pending_entry_->GetUniqueID());
2206
2207 // The extra headers may have changed due to reloading with different
2208 // headers.
2209 entry->set_extra_headers(pending_entry_->extra_headers());
2210 }
2211 // Otherwise, this was intended as a new entry but the pending entry was
2212 // lost in the meantime and no new entry was created. We are stuck at the
2213 // last committed entry.
2214
2215 // Even if this is a converted reload from pressing enter in the omnibox,
2216 // the server could redirect, requiring an update to the SSL status. If this
2217 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452218 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162219 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472220 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452221 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162222 }
Rakina Zata Amnif6950d552020-11-24 03:26:102223 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112224 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102225 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b90ce2016-09-01 16:58:162226
eugenebut604866f2017-05-10 21:35:362227 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452228 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362229 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2230 // this was a restored same document navigation entry, then it won't have
2231 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2232 // navigated it.
jam48cea9082017-02-15 06:13:292233 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522234 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2235 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292236 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2237 was_restored) {
2238 entry->GetSSL() = last_entry->GetSSL();
2239 }
2240 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452241 // In rapid back/forward navigations |request| sometimes won't have a cert
2242 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192243 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452244 if (request->GetSSLInfo().has_value() &&
2245 request->GetSSLInfo()->is_valid()) {
2246 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522247 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2248 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192249 entry->GetSSL() = SSLStatus();
2250 }
jam48cea9082017-02-15 06:13:292251 }
avicbdc4c12015-07-01 16:07:112252 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272253 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572254 // navigations that are EXISTING_ENTRY are same-document navigations that
2255 // result in replacement (e.g. history.replaceState(), location.replace(),
2256 // forced replacements for trivial session history contexts). For these
2257 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112258 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102259
Alison Gale81f4f2c72024-04-22 19:33:312260 // TODO(crbug.com/40532777): Set page transition type to
2261 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2262 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2263 // well as to fix the inconsistency with what we report to observers
2264 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102265
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572266 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102267
eugenebut604866f2017-05-10 21:35:362268 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452269 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362270 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472271 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452272 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112273 }
2274 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432275
Rakina Zata Amni3460d382021-10-29 00:43:372276 UpdateNavigationEntryDetails(entry, rfh, params, request,
2277 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002278 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302279
[email protected]5ccd4dc2012-10-24 02:28:142280 // The redirected to page should not inherit the favicon from the previous
2281 // page.
eugenebut604866f2017-05-10 21:35:362282 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482283 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142284
Charlie Reis951f43372023-05-05 00:30:072285 // Update the last committed index to reflect the committed entry. Do this
2286 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2287 // delegate sees the correct committed index when notified of navigation
2288 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2289 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212290 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072291
Peter Boströmd7592132019-01-30 04:50:312292 // We should also usually discard the pending entry if it corresponds to a
2293 // different navigation, since that one is now likely canceled. In rare
2294 // cases, we leave the pending entry for another navigation in place when we
2295 // know it is still ongoing, to avoid a flicker in the omnibox (see
2296 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432297 //
2298 // Note that we need to use the "internal" version since we don't want to
2299 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312300 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002301 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432302}
2303
[email protected]d202a7c2012-01-04 07:53:472304void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322305 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072306 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362307 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472308 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562309 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002310 NavigationRequest* request,
2311 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262312 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2313 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552314 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2315 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112316
[email protected]e9ba4472008-09-14 15:42:432317 // Manual subframe navigations just get the current entry cloned so the user
2318 // can go back or forward to it. The actual subframe information will be
2319 // stored in the page state for each of those entries. This happens out of
2320 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092321 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2322 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382323
Mikel Astizba9cf2fd2017-12-17 10:38:102324 // The DCHECK below documents the fact that we don't know of any situation
2325 // where |replace_entry| is true for subframe navigations. This simplifies
2326 // reasoning about the replacement struct for subframes (see
2327 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2328 DCHECK(!replace_entry);
2329
Patrick Monette50e8bd82019-06-13 22:40:452330 // This FrameNavigationEntry might not end up being used in the
2331 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372332 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452333 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372334 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522335 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2336 initiator_base_url = request->common_params().initiator_base_url;
2337 }
Nate Chapin63db0d12022-01-20 22:03:302338 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2339 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212340 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302341 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());
Khushal Sagar94ea2dc2024-08-06 17:15:262588 if (!nav_entry_screenshot_cache_ &&
2589 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192590 nav_entry_screenshot_cache_ =
2591 std::make_unique<NavigationEntryScreenshotCache>(
2592 BrowserContextImpl::From(browser_context_)
2593 ->GetNavigationEntryScreenshotManager()
2594 ->GetSafeRef(),
2595 this);
2596 }
2597 return nav_entry_screenshot_cache_.get();
2598}
2599
clamy987a3752018-05-03 17:36:262600void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2601 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2602 // progress, since this will cause a use-after-free. (We only allow this
2603 // when the tab is being destroyed for shutdown, since it won't return to
2604 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032605 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262606
2607 if (was_failure && pending_entry_) {
2608 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2609 } else {
2610 failed_pending_entry_id_ = 0;
2611 }
2612
2613 if (pending_entry_) {
2614 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332615 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262616 pending_entry_index_ = -1;
2617 pending_entry_ = nullptr;
2618 }
arthursonzogni66f711c2019-10-08 14:40:362619
2620 // Ensure any refs to the current pending entry are ignored if they get
2621 // deleted, by clearing the set of known refs. All future pending entries will
2622 // only be affected by new refs.
2623 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262624}
2625
2626void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2627 if (pending_entry_)
2628 pending_entry_->set_ssl_error(error);
2629}
2630
Xiaohan Wang7f8052e02022-01-14 18:44:282631#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422632// static
2633bool NavigationControllerImpl::ValidateDataURLAsString(
2634 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2635 if (!data_url_as_string)
2636 return false;
2637
2638 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2639 return false;
2640
2641 // The number of characters that is enough for validating a data: URI.
2642 // From the GURL's POV, the only important part here is scheme, it doesn't
2643 // check the actual content. Thus we can take only the prefix of the url, to
2644 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562645 constexpr size_t kDataUriPrefixMaxLen = 64;
2646 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2647 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422648 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2649 return false;
2650
2651 return true;
2652}
2653#endif
2654
Shivani Sharma194877032019-03-07 17:52:472655void NavigationControllerImpl::NotifyUserActivation() {
2656 // When a user activation occurs, ensure that all adjacent entries for the
2657 // same document clear their skippable bit, so that the history manipulation
2658 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012659 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172660 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012661 // If the value of CanGoBack changes as a result of making some entries
2662 // non-skippable, then we must let the delegate know to update its UI state.
2663 // See https://crbug.com/1477784.
2664 if (!can_go_back && CanGoBack()) {
2665 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2666 }
Shivani Sharma194877032019-03-07 17:52:472667}
2668
clamy987a3752018-05-03 17:36:262669bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2670 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332671 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2672 blink::LocalFrameToken initiator_frame_token,
2673 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262674 NavigationEntryImpl* entry =
2675 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2676 if (!entry)
2677 return false;
2678
2679 FrameNavigationEntry* frame_entry =
2680 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2681 if (!frame_entry)
2682 return false;
2683
Camille Lamy5193caa2018-10-12 11:59:422684 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572685 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232686 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332687 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2688 initiator_process_id);
clamyea99ea12018-05-28 13:54:232689
2690 if (!request)
2691 return false;
2692
arthursonzognif046d4a2019-12-12 19:08:102693 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412694
Rakina Zata Amni1c83b082023-02-08 01:09:002695 SCOPED_CRASH_KEY_STRING256(
2696 "Bug1400009", "req_url",
2697 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2698 SCOPED_CRASH_KEY_NUMBER(
2699 "Bug1400009", "nav_entry_si",
2700 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2701 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2702 frame_entry->site_instance()
2703 ? ((int)frame_entry->site_instance()->GetId())
2704 : -1);
2705 bool has_sig =
2706 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2707 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2708 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2709 has_sig ? (!!frame_tree_->GetRenderViewHost(
2710 frame_entry->site_instance()->group()))
2711 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052712 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2713 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232714
2715 return true;
clamy987a3752018-05-03 17:36:262716}
2717
Tsuyoshi Horo52fd08e2020-07-07 07:03:452718bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2719 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2720 if (!entry)
2721 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432722
2723 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2724 // We should never navigate to an existing initial NavigationEntry that is
2725 // the initial NavigationEntry for the initial empty document that hasn't
2726 // been overridden by the synchronous about:blank commit, to preserve
2727 // legacy behavior where trying to reload when the main frame is on the
2728 // initial empty document won't result in a navigation. See also
2729 // https://crbug.com/1277414.
2730 return false;
2731 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452732 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2733 if (!frame_entry)
2734 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142735 ReloadType reload_type = ReloadType::NORMAL;
2736 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452737 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142738 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452739 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432740 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372741 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332742 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452743 if (!request)
2744 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052745 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452746 return true;
2747}
2748
clamy987a3752018-05-03 17:36:262749void NavigationControllerImpl::NavigateFromFrameProxy(
2750 RenderFrameHostImpl* render_frame_host,
2751 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022752 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452753 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372754 const std::optional<url::Origin>& initiator_origin,
2755 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262756 bool is_renderer_initiated,
2757 SiteInstance* source_site_instance,
2758 const Referrer& referrer,
2759 ui::PageTransition page_transition,
2760 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252761 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262762 const std::string& method,
2763 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092764 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142765 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212766 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502767 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372768 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292769 blink::mojom::NavigationInitiatorActivationAndAdStatus
2770 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222771 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492772 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462773 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452774 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582775 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032776 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342777 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372778 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582779 if (is_renderer_initiated)
2780 DCHECK(initiator_origin.has_value());
2781
clamy987a3752018-05-03 17:36:262782 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582783
Rakina Zata Amni2322f4f82022-01-24 13:24:242784 // Don't allow an entry replacement if there is no entry to replace.
2785 // http://crbug.com/457149
2786 if (GetEntryCount() == 0)
2787 should_replace_current_entry = false;
2788
clamy987a3752018-05-03 17:36:262789 // Create a NavigationEntry for the transfer, without making it the pending
2790 // entry. Subframe transfers should have a clone of the last committed entry
2791 // with a FrameNavigationEntry for the target frame. Main frame transfers
2792 // should have a new NavigationEntry.
2793 // TODO(creis): Make this unnecessary by creating (and validating) the params
2794 // directly, passing them to the destination RenderFrameHost. See
2795 // https://crbug.com/536906.
2796 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262797 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262798 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452799 DCHECK(GetLastCommittedEntry());
2800 entry = GetLastCommittedEntry()->Clone();
2801 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172802 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2803 // Renderer-initiated navigation that target a remote frame are currently
2804 // classified as browser-initiated when this one has already navigated.
2805 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372806 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2807 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2808 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2809 // same-document navigation), they will still be present in the
2810 // committed NavigationEntry that will be referenced to construct the new
2811 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262812 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082813 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582814 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372815 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212816 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152817 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262818 } else {
2819 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172820 // If `node` is the outermost main frame, it rewrites a virtual url in order
2821 // to adjust the original input url if needed. For inner frames such as
2822 // fenced frames or subframes, they don't rewrite urls as the urls are not
2823 // input urls by users.
2824 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372825 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322826 if (source_site_instance && source_site_instance->HasProcess()) {
2827 source_process_site_url =
2828 source_site_instance->GetProcess()->GetProcessLock().site_url();
2829 }
clamy987a3752018-05-03 17:36:262830 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212831 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322832 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212833 extra_headers, browser_context_, blob_url_loader_factory,
2834 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262835 entry->root_node()->frame_entry->set_source_site_instance(
2836 static_cast<SiteInstanceImpl*>(source_site_instance));
2837 entry->root_node()->frame_entry->set_method(method);
2838 }
clamy987a3752018-05-03 17:36:262839
Camille Lamy5193caa2018-10-12 11:59:422840 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452841 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262842 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422843 override_user_agent = true;
clamy987a3752018-05-03 17:36:262844 }
2845 // TODO(creis): Set user gesture and intent received timestamp on Android.
2846
2847 // We may not have successfully added the FrameNavigationEntry to |entry|
2848 // above (per https://crbug.com/608402), in which case we create it from
2849 // scratch. This works because we do not depend on |frame_entry| being inside
2850 // |entry| during NavigateToEntry. This will go away when we shortcut this
2851 // further in https://crbug.com/536906.
2852 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2853 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452854 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082855 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582856 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372857 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212858 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152859 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572860 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262861 }
2862
Camille Lamy5193caa2018-10-12 11:59:422863 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022864 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452865 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292866 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212867 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422868 params.source_site_instance = source_site_instance;
2869 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2870 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032871 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422872 params.referrer = referrer;
2873 /* params.redirect_chain: skip */
2874 params.extra_headers = extra_headers;
2875 params.is_renderer_initiated = is_renderer_initiated;
2876 params.override_user_agent = UA_OVERRIDE_INHERIT;
2877 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542878 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422879 /* params.data_url_as_string: skip */
2880 params.post_data = post_body;
2881 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582882 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422883 /* params.frame_name: skip */
2884 // TODO(clamy): See if user gesture should be propagated to this function.
2885 params.has_user_gesture = false;
2886 params.should_clear_history_list = false;
2887 params.started_from_context_menu = false;
2888 /* params.navigation_ui_data: skip */
2889 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222890 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542891 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212892 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412893 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502894 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292895 params.initiator_activation_and_ad_status =
2896 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032897 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422898
2899 std::unique_ptr<NavigationRequest> request =
2900 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032901 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142902 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392903 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492904 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582905 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:342906 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232907
2908 if (!request)
2909 return;
2910
Garrett Tanzerbb8db412022-09-27 21:59:462911 // Force the navigation to take place in a new browsing instance.
2912 // This is used by _unfencedTop in fenced frames to ensure that navigations
2913 // leaving the fenced context create a new browsing instance.
2914 if (force_new_browsing_instance) {
2915 request->coop_status().ForceBrowsingInstanceSwap();
2916 }
2917
Arthur Hemery948742762019-09-18 10:06:242918 // At this stage we are proceeding with this navigation. If this was renderer
2919 // initiated with user gesture, we need to make sure we clear up potential
2920 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2921 DiscardNonCommittedEntries();
2922
Lukasz Anforowicz9ee83c272020-12-01 20:14:052923 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262924}
2925
[email protected]d1198fd2012-08-13 22:50:192926void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252927 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212928 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192929 if (!session_storage_namespace)
2930 return;
2931
2932 // We can't overwrite an existing SessionStorage without violating spec.
2933 // Attempts to do so may give a tab access to another tab's session storage
2934 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152935 bool successful_insert =
2936 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252937 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052938 static_cast<SessionStorageNamespaceImpl*>(
2939 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302940 .second;
2941 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192942}
2943
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572944bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452945 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032946 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462947}
2948
Aran Gilman37d11632019-10-08 23:07:152949SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252950 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302951 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252952 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032953 DOMStorageContextWrapper* context_wrapper =
2954 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2955
2956 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252957 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032958 if (it != session_storage_namespace_map_.end()) {
2959 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152960 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2961 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472962
michaelnbacbcbd2016-02-09 00:32:032963 return it->second.get();
2964 }
2965
2966 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102967 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2968 SessionStorageNamespaceImpl::Create(context_wrapper);
2969 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2970 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252971 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102972 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302973
Daniel Murphy31bbb8b12018-02-07 21:44:102974 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302975}
2976
2977SessionStorageNamespace*
2978NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252979 return GetSessionStorageNamespace(
2980 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302981}
2982
2983const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572984NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302985 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552986}
[email protected]d202a7c2012-01-04 07:53:472987
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572988bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562989 return needs_reload_;
2990}
[email protected]a26023822011-12-29 00:23:552991
[email protected]46bb5e9c2013-10-03 22:16:472992void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412993 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2994}
2995
2996void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472997 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412998 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542999
3000 if (last_committed_entry_index_ != -1) {
3001 entries_[last_committed_entry_index_]->SetTransitionType(
3002 ui::PAGE_TRANSITION_RELOAD);
3003 }
[email protected]46bb5e9c2013-10-03 22:16:473004}
3005
[email protected]d202a7c2012-01-04 07:53:473006void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573007 DCHECK_LT(index, GetEntryCount());
3008 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313009 DiscardNonCommittedEntries();
3010
Nate Chapin9eb16be72022-09-23 22:54:313011 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313012 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123013 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313014 last_committed_entry_index_--;
3015}
3016
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573017NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273018 // If there is no pending_entry_, there should be no pending_entry_index_.
3019 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3020
3021 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363022 // at that index. An exception is while a reload of a post commit error page
3023 // is ongoing; in that case pending entry will point to the entry replaced
3024 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273025 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363026 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3027 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273028
[email protected]022af742011-12-28 18:37:253029 return pending_entry_;
3030}
3031
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573032int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273033 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273034 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553035 return pending_entry_index_;
3036}
3037
avi25764702015-06-23 15:43:373038void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573039 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363040 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313041 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003042 bool in_fenced_frame_tree,
3043 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313044 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3045 // set because:
3046 // 1) They don't influence the history of the outer page.
3047 // 2) They are always replace only navigation (there is always only one entry
3048 // in their history stack).
3049 // 3) Are not top level navigations and appear similar to iframes.
3050 // Navigations of the fenced frame might create a new NavigationEntry, which
3051 // will call this function. Non fenced frame navigations will never have
3052 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3053 // InsertOrReplaceEntry.
3054 DCHECK_EQ(in_fenced_frame_tree,
3055 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3056 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203057
avi5cad4912015-06-19 05:25:443058 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3059 // need to keep continuity with the pending entry, so copy the pending entry's
3060 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3061 // then the renderer navigated on its own, independent of the pending entry,
3062 // so don't copy anything.
3063 if (pending_entry_ && pending_entry_index_ == -1)
3064 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203065
Rakina Zata Amnia4e27222021-12-22 01:05:003066 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203067
creisee17e932015-07-17 17:56:223068 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453069 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103070 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573071 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363072 // If the new entry is a post-commit error page, we store the current last
3073 // committed entry to the side so that we can put it back when navigating
3074 // away from the error.
3075 if (was_post_commit_error) {
3076 DCHECK(!entry_replaced_by_post_commit_error_);
3077 entry_replaced_by_post_commit_error_ =
3078 std::move(entries_[last_committed_entry_index_]);
3079 }
dcheng36b6aec92015-12-26 06:16:363080 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223081 return;
3082 }
[email protected]765b35502008-08-21 00:51:203083
creis37979a62015-08-04 19:48:183084 // We shouldn't see replace == true when there's no committed entries.
3085 DCHECK(!replace);
3086
Michael Thiessen9b14d512019-09-23 21:19:473087 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203088
Shivani Sharmad8c8d652019-02-13 17:27:573089 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203090
dcheng36b6aec92015-12-26 06:16:363091 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203092 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293093}
3094
Shivani Sharmad8c8d652019-02-13 17:27:573095void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163096 if (entries_.size() < max_entry_count())
3097 return;
3098
3099 DCHECK_EQ(max_entry_count(), entries_.size());
3100 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573101 CHECK_EQ(pending_entry_index_, -1);
3102
3103 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423104 // Retrieve the oldest skippable entry.
3105 for (; index < GetEntryCount(); index++) {
3106 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3107 break;
Shivani Sharmad8c8d652019-02-13 17:27:573108 }
3109
3110 // If there is no skippable entry or if it is the last committed entry then
3111 // fall back to pruning the oldest entry. It is not safe to prune the last
3112 // committed entry.
3113 if (index == GetEntryCount() || index == last_committed_entry_index_)
3114 index = 0;
3115
3116 bool should_succeed = RemoveEntryAtIndex(index);
3117 DCHECK_EQ(true, should_succeed);
3118
3119 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253120}
3121
William Liu62ae26c2024-08-08 14:28:163122std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273123NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163124 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203125 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373126 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133127 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203128 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503129 TRACE_EVENT0("navigation",
3130 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273131 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023132 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363133 if (pending_entry_index_ != -1) {
3134 // The pending entry may not be in entries_ if a post-commit error page is
3135 // showing.
3136 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3137 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3138 }
Gyuyoung Kim107c2a02021-04-13 01:49:303139 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573140 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013141 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033142 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573143 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133144 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3145 // the same as the top level frame being navigated.
3146 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373147 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133148 }
Arthur Sonzogni620cec62018-12-13 13:08:573149
[email protected]83c2e232011-10-07 21:36:463150 // If we were navigating to a slow-to-commit page, and the user performs
3151 // a session history navigation to the last committed page, RenderViewHost
3152 // will force the throbber to start, but WebKit will essentially ignore the
3153 // navigation, and won't send a message to stop the throbber. To prevent this
3154 // from happening, we drop the navigation here and stop the slow-to-commit
3155 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023156 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083157 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273158 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033159 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123160
[email protected]83c2e232011-10-07 21:36:463161 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163162 return {};
[email protected]83c2e232011-10-07 21:36:463163 }
3164
Arthur Sonzognic686e8f2024-01-11 08:36:373165 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333166 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3167 if (initiator_rfh) {
3168 initiator_frame_token = initiator_rfh->GetFrameToken();
3169 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3170 DCHECK(initiator_frame_token);
3171 }
3172
creisce0ef3572017-01-26 17:53:083173 // Compare FrameNavigationEntries to see which frames in the tree need to be
3174 // navigated.
clamy3cb9bea92018-07-10 12:42:023175 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3176 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333177 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3178 initiator_process_id, soft_navigation_heuristics_task_id,
3179 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303180
3181 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573182 // We were unable to match any frames to navigate. This can happen if a
3183 // history navigation targets a subframe that no longer exists
3184 // (https://crbug.com/705550). In this case, we need to update the current
3185 // history entry to the pending one but keep the main document loaded. We
3186 // also need to ensure that observers are informed about the updated
3187 // current history entry (e.g., for greying out back/forward buttons), and
3188 // that renderer processes update their history offsets. The easiest way
3189 // to do all that is to schedule a "redundant" same-document navigation in
3190 // the main frame.
3191 //
3192 // Note that we don't want to remove this history entry, as it might still
3193 // be valid later, since a frame that it's targeting may be recreated.
3194 //
3195 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3196 // need to repeat history navigations until finding the one that works.
3197 // Consider changing this behavior to keep looking for the first valid
3198 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023199 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423200 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573201 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573202 ReloadType::NONE /* reload_type */,
3203 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433204 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333205 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023206 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573207 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023208 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163209 return {};
clamy3cb9bea92018-07-10 12:42:023210 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573211 same_document_loads.push_back(std::move(navigation_request));
3212
3213 // Sanity check that we never take this branch for any kinds of reloads,
3214 // as those should've queued a different-document load in the main frame.
3215 DCHECK(!is_forced_reload);
3216 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303217 }
3218
Nate Chapinbf682fa32022-09-26 22:41:203219 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163220 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203221 if (initiator_rfh && initiator_rfh->IsSandboxed(
3222 network::mojom::WebSandboxFlags::kTopNavigation)) {
3223 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3224 initiator_rfh, same_document_loads) &&
3225 DoesSandboxNavigationStayWithinSubtree(
3226 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503227 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163228 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203229 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3230 initiator_rfh,
3231 navigates_inside_tree
3232 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3233 : blink::mojom::WebFeature::
3234 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523235
3236 // If the navigation occurred outside the tree discard it because
3237 // the sandboxed frame didn't have permission to navigate outside
3238 // its tree. If it is possible that the navigation is both inside and
3239 // outside the frame tree and we discard it entirely because we don't
3240 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143241 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203242 // If a |navigation_api_key| was provided, this navigation originated from
3243 // the navigation API. Notify the renderer that the navigation was
3244 // cancelled so the navigation API can fire an error event and reject the
3245 // relevant promise.
3246 if (navigation_api_key) {
3247 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3248 *navigation_api_key,
3249 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3250 }
Dave Tapuska855c1e12019-08-23 20:45:523251 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133252
3253 for (auto& unused_request : same_document_loads) {
3254 unused_request->set_navigation_discard_reason(
3255 NavigationDiscardReason::kNeverStarted);
3256 }
3257 for (auto& unused_request : different_document_loads) {
3258 unused_request->set_navigation_discard_reason(
3259 NavigationDiscardReason::kNeverStarted);
3260 }
William Liu62ae26c2024-08-08 14:28:163261 return {};
Dave Tapuska855c1e12019-08-23 20:45:523262 }
Dave Tapuska8bfd84c2019-03-26 20:47:163263 }
3264
Nate Chapin6c43c022023-02-13 23:32:423265 // If it is possible that this traverse may involve a same-document navigation
3266 // in the initiator and there is a Navigation API key involved, then we may
3267 // need to notify the initiator if it fails. (The early returns above either
3268 // do not involve these cases or already notify the initiator.)
3269 // The event only needs to fire for the initiator, and only if the initiator
3270 // itself is performing a same-document navigation (because the event will not
3271 // fire if it navigates cross-document).
3272 if (navigation_api_key) {
3273 for (auto& item : same_document_loads) {
3274 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3275 item->set_pending_navigation_api_key(*navigation_api_key);
3276 break;
3277 }
3278 }
3279 }
3280
Carlos Caballero539a421c2020-07-06 10:25:573281 // BackForwardCache:
3282 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563283 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573284 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3285 DCHECK_EQ(reload_type, ReloadType::NONE);
3286 auto navigation_request = CreateNavigationRequestFromEntry(
3287 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3288 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333289 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3290 initiator_process_id);
William Liuec04e382024-05-23 18:03:273291 base::WeakPtr<NavigationRequest> request = navigation_request->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053292 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Rakina Zata Amni58681c62024-06-25 06:32:133293
3294 for (auto& unused_request : same_document_loads) {
3295 unused_request->set_navigation_discard_reason(
3296 NavigationDiscardReason::kNeverStarted);
3297 }
3298 for (auto& unused_request : different_document_loads) {
3299 unused_request->set_navigation_discard_reason(
3300 NavigationDiscardReason::kNeverStarted);
3301 }
3302
William Liu62ae26c2024-08-08 14:28:163303 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_request;
3304 if (request) {
3305 bf_cache_request.push_back(std::move(request));
3306 }
3307 return bf_cache_request;
Carlos Caballero539a421c2020-07-06 10:25:573308 }
3309
3310 // History navigation might try to reuse a specific BrowsingInstance, already
3311 // used by a page in the cache. To avoid having two different main frames that
3312 // live in the same BrowsingInstance, evict the all pages with this
3313 // BrowsingInstance from the cache.
3314 //
3315 // For example, take the following scenario:
3316 //
3317 // A1 = Some page on a.com
3318 // A2 = Some other page on a.com
3319 // B3 = An uncacheable page on b.com
3320 //
3321 // Then the following navigations occur:
3322 // A1->A2->B3->A1
3323 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3324 // take its place) and A1 will be created in the same BrowsingInstance (and
3325 // SiteInstance), as A2.
3326 //
3327 // If we didn't do anything, both A1 and A2 would remain alive in the same
3328 // BrowsingInstance/SiteInstance, which is unsupported by
3329 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3330 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483331 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3332 pending_entry_->site_instance()
3333 ? pending_entry_->site_instance()->GetId().value()
3334 : -1);
3335 SCOPED_CRASH_KEY_NUMBER(
3336 "rvh_double", "pending_entry_bi",
3337 pending_entry_->site_instance()
3338 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3339 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573340 if (pending_entry_->site_instance()) {
3341 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3342 pending_entry_->site_instance());
3343 }
3344
Rakina Zata Amnid605d462022-06-01 10:17:033345 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3346 pending_entry_ && pending_entry_->IsRestored());
3347 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3348 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3349 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3350 pending_entry_index_);
3351 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3352 last_committed_entry_index_);
3353 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3354 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3355 pending_entry_ && pending_entry_->IsInitialEntry());
3356 SCOPED_CRASH_KEY_BOOL(
3357 "nav_reentrancy", "pending_entry_initial2",
3358 pending_entry_ &&
3359 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3360 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3361 IsInitialNavigation());
3362 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3363 IsInitialBlankNavigation());
3364 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3365 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3366 (int)pending_reload_);
3367
clamy3cb9bea92018-07-10 12:42:023368 // This call does not support re-entrancy. See http://crbug.com/347742.
3369 CHECK(!in_navigate_to_pending_entry_);
3370 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303371
Rakina Zata Amnid605d462022-06-01 10:17:033372 // If the navigation-reentrancy is caused by calling
3373 // NavigateToExistingPendingEntry twice, this will note the previous call's
3374 // pending entry's ID.
3375 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3376 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3377
arthursonzogni66f711c2019-10-08 14:40:363378 // It is not possible to delete the pending NavigationEntry while navigating
3379 // to it. Grab a reference to delay potential deletion until the end of this
3380 // function.
3381 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3382
Nate Chapin154b14b2023-02-17 18:28:163383 // If there is a main-frame same-document history navigation, we may defer
3384 // the subframe history navigations in order to give JS in the main frame the
3385 // opportunity to cancel the entire traverse via the navigate event. In that
3386 // case, we need to stash the main frame request's navigation token on the
3387 // subframes, so they can look up the main frame request and defer themselves
3388 // until it completes.
3389 if (!same_document_loads.empty() &&
3390 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3391 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3392 // The token will only be returned in cases where deferring the navigation
3393 // is necessary.
3394 if (auto main_frame_same_document_token =
3395 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3396 for (auto& item : same_document_loads) {
3397 if (item.get() != main_frame_request) {
3398 item->set_main_frame_same_document_history_token(
3399 main_frame_same_document_token);
3400 }
3401 }
3402 for (auto& item : different_document_loads) {
3403 item->set_main_frame_same_document_history_token(
3404 main_frame_same_document_token);
3405 }
3406 }
3407 }
3408
William Liu122754942024-01-18 22:34:393409 if (!initiator_rfh) {
3410 // A browser-initiated navigation won't have a `initiator_rfh`.
3411 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3412 different_document_loads, same_document_loads);
3413 }
3414
William Liu62ae26c2024-08-08 14:28:163415 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3416 all_requests.reserve(same_document_loads.size() +
3417 different_document_loads.size());
3418 bool seen_primary_main_frame_request = false;
3419
creis4e2ecb72015-06-20 00:46:303420 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023421 for (auto& item : same_document_loads) {
3422 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273423 // The request could be destroyed before `navigator().Navigate()` returns.
3424 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053425 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163426 if (request) {
3427 // Can only have one primary main frame request.
3428 CHECK(!seen_primary_main_frame_request ||
3429 !request->IsInPrimaryMainFrame());
3430 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3431 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273432 }
creis4e2ecb72015-06-20 00:46:303433 }
clamy3cb9bea92018-07-10 12:42:023434 for (auto& item : different_document_loads) {
3435 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273436 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053437 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163438 if (request) {
3439 // Can only have one primary main frame request.
3440 CHECK(!seen_primary_main_frame_request ||
3441 !request->IsInPrimaryMainFrame());
3442 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3443 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273444 }
creis4e2ecb72015-06-20 00:46:303445 }
clamy3cb9bea92018-07-10 12:42:023446
3447 in_navigate_to_pending_entry_ = false;
William Liuec04e382024-05-23 18:03:273448
William Liu62ae26c2024-08-08 14:28:163449 return all_requests;
creis4e2ecb72015-06-20 00:46:303450}
3451
Alex Moshchuk3a4e77a2020-05-29 21:32:573452NavigationControllerImpl::HistoryNavigationAction
3453NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303454 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573455 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423456 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583457 // Only active and prerendered documents are allowed to navigate in their
3458 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423459 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013460 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583461 // - If the document is in pending deletion, the browser already committed
3462 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3463 // - If the document is in back-forward cache, it's not allowed to navigate
3464 // as it should remain frozen. Ignore the request and evict the document
3465 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423466 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583467 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423468 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113469 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3470 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423471 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113472 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423473 }
arthursonzogni03f76152019-02-12 10:35:203474
Alex Moshchuk3a4e77a2020-05-29 21:32:573475 // Reloads should result in a different-document load. Note that reloads may
3476 // also happen via the |needs_reload_| mechanism where the reload_type is
3477 // NONE, so detect this by comparing whether we're going to the same
3478 // entry that we're currently on. Similarly to above, only main frames
3479 // should reach this. Note that subframes support reloads, but that's done
3480 // via a different path that doesn't involve FindFramesToNavigate (see
3481 // RenderFrameHost::Reload()).
3482 if (reload_type != ReloadType::NONE ||
3483 pending_entry_index_ == last_committed_entry_index_) {
3484 DCHECK(frame->IsMainFrame());
3485 return HistoryNavigationAction::kDifferentDocument;
3486 }
3487
Alex Moshchuk47d1a4bd2020-06-01 22:15:343488 // If there is no new FrameNavigationEntry for the frame, ignore the
3489 // load. For example, this may happen when going back to an entry before a
3490 // frame was created. Suppose we commit a same-document navigation that also
3491 // results in adding a new subframe somewhere in the tree. If we go back,
3492 // the new subframe will be missing a FrameNavigationEntry in the previous
3493 // NavigationEntry, but we shouldn't delete or change what's loaded in
3494 // it.
3495 //
Alex Moshchuke65c39272020-06-03 17:55:373496 // Note that in this case, there is no need to keep looking for navigations
3497 // in subframes, which would be missing FrameNavigationEntries as well.
3498 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343499 // It's important to check this before checking |old_item| below, since both
3500 // might be null, and in that case we still shouldn't change what's loaded in
3501 // this frame. Note that scheduling any loads assumes that |new_item| is
3502 // non-null. See https://crbug.com/1088354.
3503 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3504 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373505 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343506
Charlie Reisa474fb62022-03-17 02:31:363507 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3508 // which history item it is currently on, since this may be different than the
3509 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3510 // (e.g., if a history navigation is targeting multiple frames and only some
3511 // have committed so far).
creis4e2ecb72015-06-20 00:46:303512 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363513 frame->current_frame_host()->last_committed_frame_entry();
3514 if (!old_item) {
3515 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3516 // fall back to the last committed NavigationEntry's record for this frame.
3517 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583518 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363519 // accurate FrameNavigationEntry and eliminate this case.
3520 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3521 }
3522 // If neither approach finds a FrameNavigationEntry, schedule a
3523 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583524 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573525 if (!old_item)
3526 return HistoryNavigationAction::kDifferentDocument;
3527
Alex Moshchuk3a4e77a2020-05-29 21:32:573528 // If the new item is not in the same SiteInstance, schedule a
3529 // different-document load. Newly restored items may not have a SiteInstance
3530 // yet, in which case it will be assigned on first commit.
3531 if (new_item->site_instance() &&
3532 new_item->site_instance() != old_item->site_instance())
3533 return HistoryNavigationAction::kDifferentDocument;
3534
3535 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313536 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3537 // that we do this even if the history navigation would not be modifying this
3538 // frame were it live.
3539 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573540 return HistoryNavigationAction::kDifferentDocument;
3541
3542 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313543 // Starting a navigation after a crash early-promotes the speculative
3544 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3545 // committed yet, so we can not possibly perform a same-document history
3546 // navigation. The frame would need to be reloaded with a cross-document
3547 // navigation.
3548 if (!frame->current_frame_host()->has_committed_any_navigation())
3549 return HistoryNavigationAction::kDifferentDocument;
3550
creis54131692016-08-12 18:32:253551 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493552 // sequence number but different item sequence number.
3553 if (new_item->document_sequence_number() ==
3554 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573555 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493556 }
avib48cb312016-05-05 21:35:003557
Alex Moshchuk3a4e77a2020-05-29 21:32:573558 // Otherwise, if both item and document sequence numbers differ, this
3559 // should be a different document load.
3560 return HistoryNavigationAction::kDifferentDocument;
3561 }
3562
3563 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373564 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573565 DCHECK_EQ(new_item->document_sequence_number(),
3566 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373567 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573568}
3569
3570void NavigationControllerImpl::FindFramesToNavigate(
3571 FrameTreeNode* frame,
3572 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373573 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333574 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373575 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133576 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573577 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3578 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3579 DCHECK(pending_entry_);
3580 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3581
3582 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3583
3584 if (action == HistoryNavigationAction::kSameDocument) {
3585 std::unique_ptr<NavigationRequest> navigation_request =
3586 CreateNavigationRequestFromEntry(
3587 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133588 /*is_same_document_history_load=*/true,
3589 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333590 initiator_frame_token, initiator_process_id,
3591 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573592 if (navigation_request) {
3593 // Only add the request if was properly created. It's possible for the
3594 // creation to fail in certain cases, e.g. when the URL is invalid.
3595 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303596 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573597 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473598 std::unique_ptr<NavigationRequest> navigation_request =
3599 CreateNavigationRequestFromEntry(
3600 frame, pending_entry_, new_item, reload_type,
3601 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433602 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333603 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473604 if (navigation_request) {
3605 // Only add the request if was properly created. It's possible for the
3606 // creation to fail in certain cases, e.g. when the URL is invalid.
3607 different_document_loads->push_back(std::move(navigation_request));
3608 }
3609 // For a different document, the subframes will be destroyed, so there's
3610 // no need to consider them.
3611 return;
Alex Moshchuke65c39272020-06-03 17:55:373612 } else if (action == HistoryNavigationAction::kStopLooking) {
3613 return;
creis4e2ecb72015-06-20 00:46:303614 }
3615
Yoav Weiss8c573952022-11-17 17:35:133616 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3617 // we currently only support soft navigation heuristics for the top level
3618 // frame.
creis4e2ecb72015-06-20 00:46:303619 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333620 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3621 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373622 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433623 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303624 }
3625}
3626
Harkiran Bolariaba823e42021-05-21 18:30:363627base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243628 const LoadURLParams& params) {
3629 // Find the appropriate FrameTreeNode.
3630 FrameTreeNode* node = nullptr;
Avi Drissmanbd153642024-09-03 18:58:053631 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3632 node = params.frame_tree_node_id
Ali Hijazid87307d2022-11-07 20:15:033633 ? frame_tree_->FindByID(params.frame_tree_node_id)
3634 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503635 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243636 }
3637
3638 // If no FrameTreeNode was specified, navigate the main frame.
3639 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033640 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243641
Camille Lamy5193caa2018-10-12 11:59:423642 // Compute overrides to the LoadURLParams for |override_user_agent|,
3643 // |should_replace_current_entry| and |has_user_gesture| that will be used
3644 // both in the creation of the NavigationEntry and the NavigationRequest.
3645 // Ideally, the LoadURLParams themselves would be updated, but since they are
3646 // passed as a const reference, this is not possible.
3647 // TODO(clamy): When we only create a NavigationRequest, move this to
3648 // CreateNavigationRequestFromLoadURLParams.
3649 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3650 GetLastCommittedEntry());
3651
Rakina Zata Amnie2d31312022-11-18 03:38:453652 // An entry replacement must happen if the current browsing context should
3653 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333654 bool should_replace_current_entry =
3655 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453656 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423657
clamy21718cc22018-06-13 13:34:243658 // Javascript URLs should not create NavigationEntries. All other navigations
3659 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243660 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373661 std::unique_ptr<NavigationEntryImpl> entry =
3662 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3663 should_replace_current_entry,
3664 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243665 DiscardPendingEntry(false);
3666 SetPendingEntry(std::move(entry));
3667 }
3668
Tim Judkins59548192023-05-17 17:51:203669 // Renderer-debug URLs are sent to the current renderer process immediately
3670 // for processing and don't need to create a NavigationRequest. Note: this
3671 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243672 // renderer-debug URLs.
3673 // Note: we intentionally leave the pending entry in place for renderer debug
3674 // URLs, unlike the cases below where we clear it if the navigation doesn't
3675 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303676 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483677 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3678 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153679 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203680 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483681 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363682 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483683 }
3684
clamy21718cc22018-06-13 13:34:243685 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363686 return nullptr;
clamy21718cc22018-06-13 13:34:243687 }
3688
Antonio Sartori78a749f2020-11-30 12:03:393689 DCHECK(pending_entry_);
3690
clamy21718cc22018-06-13 13:34:243691 // Convert navigations to the current URL to a reload.
3692 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3693 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3694 // DevTools sometimes issues navigations to main frames that they do not
3695 // expect to see treated as reload, and it only works because they pass a
3696 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3697 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543698 ReloadType reload_type = params.reload_type;
3699 if (reload_type == ReloadType::NONE &&
3700 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043701 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243702 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243703 params.load_type ==
3704 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543705 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243706 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473707 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393708
3709 // If this is a reload of an existing FrameNavigationEntry and we had a
3710 // policy container for it, then we should copy it into the pending entry,
3711 // so that it is copied to the navigation request in
3712 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453713 FrameNavigationEntry* previous_frame_entry =
3714 GetLastCommittedEntry()->GetFrameEntry(node);
3715 if (previous_frame_entry &&
3716 previous_frame_entry->policy_container_policies()) {
3717 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3718 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393719 }
3720 }
3721
3722 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173723 // document, then we should copy the document polices from RenderFrameHost's
3724 // PolicyContainerHost. The NavigationRequest will create a new
3725 // PolicyContainerHost with the document policies from the |pending_entry_|,
3726 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3727 // the navigation. This way, we ensure that we keep enforcing the right
3728 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453729 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393730 if (node->current_frame_host() &&
3731 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193732 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163733 node->current_frame_host()
3734 ->policy_container_host()
3735 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233736 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393737 }
clamy21718cc22018-06-13 13:34:243738 }
3739
3740 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263741 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243742
Tsuyoshi Horo167ca6432022-03-09 05:16:393743 // This will be used to set the Navigation Timing API navigationStart
3744 // parameter for browser navigations in new tabs (intents, tabs opened through
3745 // "Open link in new tab"). If the navigation must wait on the current
3746 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3747 // will be updated when the BeforeUnload ack is received.
3748 const auto navigation_start_time = base::TimeTicks::Now();
3749
Camille Lamy5193caa2018-10-12 11:59:423750 std::unique_ptr<NavigationRequest> request =
3751 CreateNavigationRequestFromLoadParams(
3752 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143753 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393754 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3755 navigation_start_time);
clamy21718cc22018-06-13 13:34:243756
3757 // If the navigation couldn't start, return immediately and discard the
3758 // pending NavigationEntry.
3759 if (!request) {
3760 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363761 return nullptr;
clamy21718cc22018-06-13 13:34:243762 }
3763
Camille Lamy5193caa2018-10-12 11:59:423764#if DCHECK_IS_ON()
3765 // Safety check that NavigationRequest and NavigationEntry match.
3766 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3767#endif
3768
clamy21718cc22018-06-13 13:34:243769 // This call does not support re-entrancy. See http://crbug.com/347742.
3770 CHECK(!in_navigate_to_pending_entry_);
3771 in_navigate_to_pending_entry_ = true;
3772
arthursonzogni66f711c2019-10-08 14:40:363773 // It is not possible to delete the pending NavigationEntry while navigating
3774 // to it. Grab a reference to delay potential deletion until the end of this
3775 // function.
3776 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3777
Harkiran Bolariaba823e42021-05-21 18:30:363778 base::WeakPtr<NavigationHandle> created_navigation_handle(
3779 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053780 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243781
3782 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363783 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243784}
3785
clamyea99ea12018-05-28 13:54:233786void NavigationControllerImpl::HandleRendererDebugURL(
3787 FrameTreeNode* frame_tree_node,
3788 const GURL& url) {
3789 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243790 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3791 // the renderer process is not live, unless it is the initial navigation
3792 // of the tab.
clamyea99ea12018-05-28 13:54:233793 if (!IsInitialNavigation()) {
3794 DiscardNonCommittedEntries();
3795 return;
3796 }
Fergal Dalyecd3b0202020-06-25 01:57:373797 // The current frame is always a main frame. If IsInitialNavigation() is
3798 // true then there have been no navigations and any frames of this tab must
3799 // be in the same renderer process. If that has crashed then the only frame
3800 // that can be revived is the main frame.
3801 frame_tree_node->render_manager()
3802 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233803 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223804
3805 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3806 // notification, so set is loading to true here to properly surface it when
3807 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313808 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223809 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223810 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223811 }
clamyea99ea12018-05-28 13:54:233812 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3813}
3814
clamy21718cc22018-06-13 13:34:243815std::unique_ptr<NavigationEntryImpl>
3816NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3817 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423818 const LoadURLParams& params,
3819 bool override_user_agent,
3820 bool should_replace_current_entry,
3821 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393822 // Browser initiated navigations might not have a blob_url_loader_factory set
3823 // in params even if the navigation is to a blob URL. If that happens, lookup
3824 // the correct url loader factory to use here.
3825 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483826 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473827 // Resolve the blob URL in the storage partition associated with the target
3828 // frame. This is the storage partition the URL will be loaded in, and only
3829 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393830 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473831 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393832 }
3833
clamy21718cc22018-06-13 13:34:243834 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443835 // extra_headers in params are \n separated; navigation entries want \r\n.
3836 std::string extra_headers_crlf;
3837 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243838
3839 // For subframes, create a pending entry with a corresponding frame entry.
3840 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453841 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243842 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083843 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243844 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373845 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213846 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3847 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393848 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163849 // a conversion of a new navigation into a reload, we will set the right
3850 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193851 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243852 } else {
3853 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173854 // If `node` is the outermost main frame, it rewrites a virtual url in order
3855 // to adjust the original input url if needed. For inner frames such as
3856 // fenced frames or subframes, they don't rewrite urls as the urls are not
3857 // input urls by users.
3858 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323859 scoped_refptr<SiteInstance> source_site_instance =
3860 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373861 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323862 if (source_site_instance && source_site_instance->HasProcess()) {
3863 source_process_site_url =
3864 source_site_instance->GetProcess()->GetProcessLock().site_url();
3865 }
clamy21718cc22018-06-13 13:34:243866 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063867 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323868 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213869 params.transition_type, params.is_renderer_initiated,
3870 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3871 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243872 entry->set_source_site_instance(
3873 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3874 entry->SetRedirectChain(params.redirect_chain);
3875 }
3876
3877 // Set the FTN ID (only used in non-site-per-process, for tests).
3878 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243879 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423880 entry->SetIsOverridingUserAgent(override_user_agent);
3881 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543882 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243883
clamy21718cc22018-06-13 13:34:243884 switch (params.load_type) {
3885 case LOAD_TYPE_DEFAULT:
3886 break;
3887 case LOAD_TYPE_HTTP_POST:
3888 entry->SetHasPostData(true);
3889 entry->SetPostData(params.post_data);
3890 break;
3891 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:543892 // LoadDataWithBaseURL is a special case that needs to assign both a base
3893 // URL and a virtual URL, while loading the actual content from a data
3894 // URL.
clamy21718cc22018-06-13 13:34:243895 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:543896 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:283897#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243898 entry->SetDataURLAsString(params.data_url_as_string);
3899#endif
3900 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3901 break;
Shu Yang112ad492024-07-25 17:11:543902#if BUILDFLAG(IS_ANDROID)
3903 case LOAD_TYPE_PDF_ANDROID:
3904 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
3905 // internal URL is used for the navigation URL.
3906 entry->SetVirtualURL(params.virtual_url_for_special_cases);
3907 break;
3908#endif
clamy21718cc22018-06-13 13:34:243909 }
3910
3911 // TODO(clamy): NavigationEntry is meant for information that will be kept
3912 // after the navigation ended and therefore is not appropriate for
3913 // started_from_context_menu. Move started_from_context_menu to
3914 // NavigationUIData.
3915 entry->set_started_from_context_menu(params.started_from_context_menu);
3916
3917 return entry;
3918}
3919
clamyea99ea12018-05-28 13:54:233920std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423921NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3922 FrameTreeNode* node,
3923 const LoadURLParams& params,
3924 bool override_user_agent,
3925 bool should_replace_current_entry,
3926 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143927 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423928 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573929 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393930 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223931 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493932 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453933 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583934 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343935 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:373936 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573937 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:523938
3939 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
3940 // subframes have FrameNavigationEntries associated with them. Until then,
3941 // there may be cases where a subframe navigation is missing `frame_entry`
3942 // (e.g., see https://crbug.com/358084015).
3943
Nasko Oskov3c2f9e252019-01-10 17:45:533944 // All renderer-initiated navigations must have an initiator_origin.
3945 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513946
Camille Lamy5193caa2018-10-12 11:59:423947 GURL url_to_load;
3948 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323949
Camille Lamy2baa8022018-10-19 16:43:173950 // For main frames, rewrite the URL if necessary and compute the virtual URL
3951 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263952 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423953 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173954 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423955 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423956
Shu Yang112ad492024-07-25 17:11:543957 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
3958 // that need to define a virtual URL to display, which differs from the
3959 // navigation URL.
3960 if (params.load_type == LOAD_TYPE_DATA) {
3961 virtual_url = params.virtual_url_for_special_cases;
3962 }
3963#if BUILDFLAG(IS_ANDROID)
3964 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
3965 virtual_url = params.virtual_url_for_special_cases;
3966 }
3967#endif
Camille Lamy5193caa2018-10-12 11:59:423968
Camille Lamy2baa8022018-10-19 16:43:173969 if (virtual_url.is_empty())
3970 virtual_url = url_to_load;
3971
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573972 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283973
Aran Gilman249eb122019-12-02 23:32:463974 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3975 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3976 // return different results, leading to a different URL in the
3977 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3978 // pending NavigationEntry, as we'll only make one call to
3979 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:523980 if (frame_entry) {
3981 VLOG_IF(1, (url_to_load != frame_entry->url()))
3982 << "NavigationRequest and FrameEntry have different URLs: "
3983 << url_to_load << " vs " << frame_entry->url();
3984 }
Camille Lamyb9ed3c52018-11-19 15:34:283985
Camille Lamy2baa8022018-10-19 16:43:173986 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423987 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173988 // NavigationRequest.
3989 } else {
3990 url_to_load = params.url;
3991 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243992 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173993 }
Camille Lamy5193caa2018-10-12 11:59:423994
Ehsan Karamad44fc72112019-02-26 18:15:473995 if (node->render_manager()->is_attaching_inner_delegate()) {
3996 // Avoid starting any new navigations since this node is now preparing for
3997 // attaching an inner delegate.
3998 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203999 }
Camille Lamy5193caa2018-10-12 11:59:424000
Alex Moshchuk99242832023-05-22 17:21:444001 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424002 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444003 }
Camille Lamy5193caa2018-10-12 11:59:424004
danakjd83d706d2020-11-25 22:11:124005 // Look for a pending commit that is to another document in this
4006 // FrameTreeNode. If one exists, then the last committed URL will not be the
4007 // current URL by the time this navigation commits.
4008 bool has_pending_cross_document_commit =
4009 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214010 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124011
Minggang Wangb9f3fa92021-07-01 15:30:314012 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494013 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524014 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494015 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134016 /*is_same_document_history_load=*/false,
4017 is_embedder_initiated_fenced_frame_navigation,
4018 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424019
4020 // Create the NavigationParams based on |params|.
4021
Hiroki Nakagawa4ed61282021-06-18 05:37:234022 bool is_view_source_mode = entry->IsViewSourceMode();
4023 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294024
Antonio Sartori6984c742021-08-26 08:03:414025 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294026
Hiroki Nakagawa4ed61282021-06-18 05:37:234027 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294028 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254029 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294030
Charlie Reisf21cd182024-08-09 21:44:524031 std::string page_state_data =
4032 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4033
Minggang Wangb9f3fa92021-07-01 15:30:314034 blink::mojom::CommonNavigationParamsPtr common_params =
4035 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214036 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514037 blink::mojom::Referrer::New(params.referrer.url,
4038 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214039 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514040 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:394041 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514042 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144043 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414044 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274045 false /* has_text_fragment_token */,
4046 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4047 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514048 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054049 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424050
Minggang Wangb9f3fa92021-07-01 15:30:314051 blink::mojom::CommitNavigationParamsPtr commit_params =
4052 blink::mojom::CommitNavigationParams::New(
Arthur Sonzognic686e8f2024-01-11 08:36:374053 std::nullopt,
Ari Chivukulac7533522024-05-14 21:52:344054 // The correct storage key will be computed before committing the
4055 // navigation.
4056 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324057 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504058 std::vector<net::RedirectInfo>(), params.post_content_type,
4059 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524060 params.can_load_local_resources, page_state_data,
4061 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134062 /*intended_as_new_entry=*/true,
4063 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144064 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4065 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134066 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314067 params.should_clear_history_list,
4068 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224069 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134070 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514071 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284072#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134073 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144074#endif
Yoav Weiss8c573952022-11-17 17:35:134075 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154076 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134077 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074078 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134079 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4080 /*origin_agent_cluster=*/false,
4081 /*origin_agent_cluster_left_as_default=*/true,
4082 /*enabled_client_hints=*/
4083 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264084 /*is_cross_site_cross_browsing_context_group=*/false,
4085 /*should_have_sticky_user_activation=*/false,
4086 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134087 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014088 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134089 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584090 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134091 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134092 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284093 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134094 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444095 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424096 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374097 /*view_transition_state=*/std::nullopt,
4098 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054099 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464100 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374101 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054102 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094103 /*load_with_storage_access=*/
4104 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374105 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374106 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484107 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314108 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164109 /*local_surface_id=*/std::nullopt,
4110 node->current_frame_host()->GetCachedPermissionStatuses());
Xiaohan Wang7f8052e02022-01-14 18:44:284111#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424112 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564113 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424114 }
4115#endif
4116
Lucas Furukawa Gadania9c45682019-07-31 22:05:144117 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074118 commit_params->navigation_timing->system_entropy_at_navigation_start =
4119 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4120 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424121
Camille Lamy5193caa2018-10-12 11:59:424122 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4123 std::string extra_headers_crlf;
4124 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094125
Alex Moshchuk9321e6a2022-12-07 21:58:314126 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144127 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084128 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094129 params.initiator_frame_token, params.initiator_process_id,
4130 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214131 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294132 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454133 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344134 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034135 embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094136 navigation_request->set_from_download_cross_origin_redirect(
4137 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554138 navigation_request->set_force_new_browsing_instance(
4139 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514140 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434141 if (params.force_no_https_upgrade) {
4142 navigation_request->set_force_no_https_upgrade();
4143 }
Yao Xiaodc5ed102019-06-04 19:19:094144 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424145}
4146
4147std::unique_ptr<NavigationRequest>
4148NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234149 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574150 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234151 FrameNavigationEntry* frame_entry,
4152 ReloadType reload_type,
4153 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434154 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374155 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334156 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374157 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134158 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344159 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234160 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434161 // We should never navigate to an existing initial NavigationEntry that is the
4162 // initial NavigationEntry for the initial empty document that hasn't been
4163 // overridden by the synchronous about:blank commit, to preserve previous
4164 // behavior where trying to reload when the main frame is on the initial empty
4165 // document won't result in a navigation.
4166 // See also https://crbug.com/1277414.
4167 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324168
clamyea99ea12018-05-28 13:54:234169 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234170
Ehsan Karamad44fc72112019-02-26 18:15:474171 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4172 // Avoid starting any new navigations since this node is now preparing for
4173 // attaching an inner delegate.
4174 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204175 }
4176
Alex Moshchuk99242832023-05-22 17:21:444177 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4178 dest_url)) {
clamyea99ea12018-05-28 13:54:234179 return nullptr;
4180 }
4181
clamyea99ea12018-05-28 13:54:234182 // This will be used to set the Navigation Timing API navigationStart
4183 // parameter for browser navigations in new tabs (intents, tabs opened through
4184 // "Open link in new tab"). If the navigation must wait on the current
4185 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4186 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074187
clamyea99ea12018-05-28 13:54:234188 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074189 const auto navigation_start_system_entropy =
4190 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4191 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234192
danakjd83d706d2020-11-25 22:11:124193 // Look for a pending commit that is to another document in this
4194 // FrameTreeNode. If one exists, then the last committed URL will not be the
4195 // current URL by the time this navigation commits.
4196 bool has_pending_cross_document_commit =
4197 frame_tree_node->render_manager()
4198 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494199 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214200 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124201
Minggang Wangb9f3fa92021-07-01 15:30:314202 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124203 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524204 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494205 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494206 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134207 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494208 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424209
4210 // A form submission may happen here if the navigation is a
4211 // back/forward/reload navigation that does a form resubmission.
4212 scoped_refptr<network::ResourceRequestBody> request_body;
4213 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394214 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504215 // entry. This way, it could be directly retrieved here. Right now, it is only
4216 // partially recovered when request.method == "POST" and request.body exists.
4217 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424218 if (frame_entry->method() == "POST") {
4219 request_body = frame_entry->GetPostData(&post_content_type);
4220 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304221 post_content_type = std::string(
4222 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504223 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424224 }
4225
4226 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314227 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514228 entry->ConstructCommonNavigationParams(
4229 *frame_entry, request_body, dest_url,
4230 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384231 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534232 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514233 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554234 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424235
4236 // TODO(clamy): |intended_as_new_entry| below should always be false once
4237 // Reload no longer leads to this being called for a pending NavigationEntry
4238 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314239 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144240 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404241 *frame_entry, common_params->url, common_params->method,
4242 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144243 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534244 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484245 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134246 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074247 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144248 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074249 commit_params->navigation_timing->system_entropy_at_navigation_start =
4250 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4251 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164252 commit_params->initial_permission_statuses =
4253 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424254
W. James MacLeanb7d6092682022-10-05 15:23:264255 if (common_params->url.IsAboutSrcdoc()) {
4256 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4257 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594258 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264259 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334260 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314261 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144262 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434263 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334264 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4265 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374266 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294267 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4268 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474269 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234270}
4271
[email protected]d202a7c2012-01-04 07:53:474272void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214273 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274274 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404275
Takashi Toyoshimaea534ef22021-07-21 03:27:594276 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404277 // location bar will have up-to-date information about the security style
4278 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134279 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404280
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374281 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574282 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294283}
4284
initial.commit09911bf2008-07-26 23:55:294285// static
[email protected]d202a7c2012-01-04 07:53:474286size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234287 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154288 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214289 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234290}
4291
[email protected]d202a7c2012-01-04 07:53:474292void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224293 if (is_active && needs_reload_)
4294 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214295
4296 if (frame_tree_->is_primary();
4297 auto* cache = GetNavigationEntryScreenshotCache()) {
4298 cache->SetVisible(is_active);
4299 }
initial.commit09911bf2008-07-26 23:55:294300}
4301
[email protected]d202a7c2012-01-04 07:53:474302void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034303 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4304 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294305 if (!needs_reload_)
4306 return;
4307
Bo Liucdfa4b12018-11-06 00:21:444308 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4309 needs_reload_type_);
4310
initial.commit09911bf2008-07-26 23:55:294311 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004312 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294313 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004314 if (entry_replaced_by_post_commit_error_) {
4315 // If the current entry is a post commit error, we reload the entry it
4316 // replaced instead. We leave the error entry in place until a commit
4317 // replaces it, but the pending entry points to the original entry in the
4318 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4319 // case that pending_entry_ != entries_[pending_entry_index_].
4320 // Note that this handling is similar to
4321 // `NavigationControllerImpl::Reload()`.
4322 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4323 pending_entry_index_ = GetCurrentEntryIndex();
4324 NavigateToExistingPendingEntry(
4325 ReloadType::NONE,
4326 /*initiator_rfh=*/nullptr,
4327 /*soft_navigation_heuristics_task_id=*/std::nullopt,
4328 /*navigation_api_key=*/nullptr);
4329 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134330 NavigateToExistingPendingEntry(
4331 ReloadType::NONE,
4332 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374333 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134334 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454335 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434336 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274337 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344338 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134339 NavigateToExistingPendingEntry(
4340 ReloadType::NONE,
4341 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374342 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134343 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344344 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434345 // We should never navigate to an existing initial NavigationEntry that is
4346 // the initial NavigationEntry for the initial empty document that hasn't
4347 // been overridden by the synchronous about:blank commit, to preserve
4348 // legacy behavior where trying to reload when the main frame is on the
4349 // initial empty document won't result in a navigation. See also
4350 // https://crbug.com/1277414. If there is something to reload, the
4351 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4352 // it here.
avicc872d7242015-08-19 21:26:344353 needs_reload_ = false;
4354 }
initial.commit09911bf2008-07-26 23:55:294355}
4356
Kevin McNeeccca6172021-10-19 17:11:144357base::WeakPtr<NavigationHandle>
4358NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364359 RenderFrameHost* render_frame_host,
4360 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364361 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134362 RenderFrameHostImpl* rfhi =
4363 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584364
4365 // Only active documents can load post-commit error pages:
4366 // - If the document is in pending deletion, the browser already committed to
4367 // destroying this RenderFrameHost so ignore loading the error page.
4368 // - If the document is in back-forward cache, it's not allowed to navigate as
4369 // it should remain frozen. Ignore the request and evict the document from
4370 // back-forward cache.
4371 // - If the document is prerendering, it can navigate but when loading error
4372 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114373 if (rfhi->IsInactiveAndDisallowActivation(
4374 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144375 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114376 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584377
Rakina Zata Amni919b7922020-12-11 09:03:134378 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414379
Minggang Wangb9f3fa92021-07-01 15:30:314380 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434381 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594382 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4383 // the frame actually committed (e.g. iframe with "src" set to a
4384 // slow-responding URL). We should rewrite the URL to about:blank in this
4385 // case, as the renderer will only think a page is an error page if it has a
4386 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134387 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314388 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434389 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334390 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414391
Mike Jacksone2aa7af2023-05-17 06:45:074392 commit_params->navigation_timing->system_entropy_at_navigation_start =
4393 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4394 node, blink::mojom::SystemEntropy::kNormal);
4395
arthursonzogni70ac7302020-05-28 08:49:054396 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4397 // error pages.
Liam Brady34639ec92023-10-13 19:50:454398 commit_params->frame_policy = node->pending_frame_policy();
arthursonzogni70ac7302020-05-28 08:49:054399
John Delaney131ad362019-08-08 21:57:414400 std::unique_ptr<NavigationRequest> navigation_request =
4401 NavigationRequest::CreateBrowserInitiated(
4402 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094403 false /* was_opener_suppressed */, "" /* extra_headers */,
4404 nullptr /* frame_entry */, nullptr /* entry */,
4405 false /* is_form_submission */, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374406 std::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364407 navigation_request->set_post_commit_error_page_html(error_page_html);
Lei Zhanga4770832023-07-19 18:02:364408 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
Charlie Reis09952ee2022-12-08 16:35:074409 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414410 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144411
4412 // Calling BeginNavigation may destroy the NavigationRequest.
4413 base::WeakPtr<NavigationRequest> created_navigation_request(
4414 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414415 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144416 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414417}
4418
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574419void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214420 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094421 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154422 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144423 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294424}
4425
[email protected]d202a7c2012-01-04 07:53:474426void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364427 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584428 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474429 // represent a no-committed-entry state.
4430 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364431 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584432 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474433 // if `entries_` contains pre-existing entries from the NavigationController
4434 // before restore, which would not be removed and will be at the front of the
4435 // entries list, causing the index to be off by the amount of pre-existing
4436 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294437 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294438}
[email protected]765b35502008-08-21 00:51:204439
arthursonzogni69a6a1b2019-09-17 09:23:004440void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004441 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4442}
4443
4444void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4445 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474446 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104447 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4448 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294449 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474450 return;
Michael Thiessenc5676d22019-09-25 22:32:104451 }
avi45a72532015-04-07 21:01:454452 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314453
4454 if (!delegate_)
4455 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374456 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484457}
4458
avi7c6f35e2015-05-08 17:52:384459int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4460 int nav_entry_id) const {
4461 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4462 if (entries_[i]->GetUniqueID() == nav_entry_id)
4463 return i;
4464 }
4465 return -1;
4466}
4467
[email protected]d202a7c2012-01-04 07:53:474468void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574469 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254470 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574471 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594472 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254473 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374474 // Normally, cloning a NavigationEntryImpl results in sharing
4475 // FrameNavigationEntries between the original and the clone. However, when
4476 // cloning from a different NavigationControllerImpl, we want to fork the
4477 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374478 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594479 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254480 }
Rakina Zata Amnie2d31312022-11-18 03:38:454481 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274482 DCHECK(pending_entry_index_ == -1 ||
4483 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254484}
[email protected]c5b88d82012-10-06 17:03:334485
4486void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184487 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334488 get_timestamp_callback_ = get_timestamp_callback;
4489}
[email protected]8ff00d72012-10-23 19:12:214490
Shivani Sharmaffb32b82019-04-09 16:58:474491// History manipulation intervention:
4492void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474493 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564494 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404495 bool is_renderer_initiated,
4496 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564497 // Note that for a subframe,
4498 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454499 // gesture happened in any subframe (propagated to main frame) or in the main
4500 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564501 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274502 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474503 return;
4504 }
4505 if (last_committed_entry_index_ == -1)
4506 return;
4507
Shivani Sharmac4cc8922019-04-18 03:11:174508 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474509
Alexander Timine3ec4192020-04-20 16:39:404510 // Log UKM with the URL we are navigating away from.
4511 ukm::builders::HistoryManipulationIntervention(
4512 previous_page_load_ukm_source_id)
4513 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474514}
4515
Shivani Sharmac4cc8922019-04-18 03:11:174516void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4517 int reference_index,
4518 bool skippable) {
4519 auto* reference_entry = GetEntryAtIndex(reference_index);
4520 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4521
4522 int64_t document_sequence_number =
4523 reference_entry->root_node()->frame_entry->document_sequence_number();
4524 for (int index = 0; index < GetEntryCount(); index++) {
4525 auto* entry = GetEntryAtIndex(index);
4526 if (entry->root_node()->frame_entry->document_sequence_number() ==
4527 document_sequence_number) {
4528 entry->set_should_skip_on_back_forward_ui(skippable);
4529 }
4530 }
4531}
4532
arthursonzogni66f711c2019-10-08 14:40:364533std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4534NavigationControllerImpl::ReferencePendingEntry() {
4535 DCHECK(pending_entry_);
4536 auto pending_entry_ref =
4537 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4538 pending_entry_refs_.insert(pending_entry_ref.get());
4539 return pending_entry_ref;
4540}
4541
4542void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4543 // Ignore refs that don't correspond to the current pending entry.
4544 auto it = pending_entry_refs_.find(ref);
4545 if (it == pending_entry_refs_.end())
4546 return;
4547 pending_entry_refs_.erase(it);
4548
4549 if (!pending_entry_refs_.empty())
4550 return;
4551
4552 // The pending entry may be deleted before the last PendingEntryRef.
4553 if (!pending_entry_)
4554 return;
4555
4556 // We usually clear the pending entry when the matching NavigationRequest
4557 // fails, so that an arbitrary URL isn't left visible above a committed page.
4558 //
4559 // However, we do preserve the pending entry in some cases, such as on the
4560 // initial navigation of an unmodified blank tab. We also allow the delegate
4561 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4562 // user edit the URL and try again. This may be useful in cases that the
4563 // committed page cannot be attacker-controlled. In these cases, we still
4564 // allow the view to clear the pending entry and typed URL if the user
4565 // requests (e.g., hitting Escape with focus in the address bar).
4566 //
4567 // Do not leave the pending entry visible if it has an invalid URL, since this
4568 // might be formatted in an unexpected or unsafe way.
4569 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364570 bool should_preserve_entry =
4571 (pending_entry_ == GetVisibleEntry()) &&
4572 pending_entry_->GetURL().is_valid() &&
4573 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4574 if (should_preserve_entry)
4575 return;
4576
4577 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374578 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364579}
4580
Titouan Rigoudy6ec70402021-02-02 15:42:194581std::unique_ptr<PolicyContainerPolicies>
4582NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394583 RenderFrameHostImpl* rfh,
4584 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214585 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174586 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214587 if (navigation_encountered_error) {
4588 // We should never reload the policy container of an error page from
4589 // history, see https://crbug.com/364773822.
4590 return nullptr;
4591 }
4592
Antonio Sartori78a749f2020-11-30 12:03:394593 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454594 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394595 FrameNavigationEntry* previous_frame_entry =
4596 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4597
Alison Gale770f3fc2024-04-27 00:39:584598 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394599 // ensure we always have a FrameNavigationEntry here.
4600 if (!previous_frame_entry)
4601 return nullptr;
4602
Titouan Rigoudy6ec70402021-02-02 15:42:194603 const PolicyContainerPolicies* previous_policies =
4604 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394605
Titouan Rigoudy6ec70402021-02-02 15:42:194606 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394607 return nullptr;
4608
4609 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234610 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394611 }
4612
Titouan Rigoudy72f892d2022-05-02 18:21:234613 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394614}
4615
Hayato Ito2c8c08d02021-06-23 03:38:434616void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504617 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434618 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4619 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4620 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504621
Kevin McNee7705fe82024-11-07 18:56:314622 int history_offset = GetLastCommittedEntryIndex();
4623 int history_length = GetEntryCount();
4624 auto callback = [history_offset, history_length](RenderViewHostImpl* rvh) {
4625 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4626 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4627 }
4628 };
Ali Hijazid87307d2022-11-07 20:15:034629 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504630}
4631
4632void NavigationControllerImpl::DidAccessInitialMainDocument() {
4633 // We may have left a failed browser-initiated navigation in the address bar
4634 // to let the user edit it and try again. Clear it now that content might
4635 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034636 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504637 DiscardPendingEntry(false);
4638
4639 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374640 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504641}
4642
4643void NavigationControllerImpl::UpdateStateForFrame(
4644 RenderFrameHostImpl* rfhi,
4645 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564646 OPTIONAL_TRACE_EVENT1("content",
4647 "NavigationControllerImpl::UpdateStateForFrame",
4648 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504649 // The state update affects the last NavigationEntry associated with the given
4650 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4651 // in the case of an UpdateState from a frame being swapped out). We track
4652 // which entry this is in the RenderFrameHost's nav_entry_id.
4653 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4654 if (!entry)
4655 return;
4656
4657 FrameNavigationEntry* frame_entry =
4658 entry->GetFrameEntry(rfhi->frame_tree_node());
4659 if (!frame_entry)
4660 return;
4661
4662 // The SiteInstance might not match if we do a cross-process navigation with
4663 // replacement (e.g., auto-subframe), in which case the swap out of the old
4664 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4665 // has already been replaced and destroyed.
4666 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4667 return;
4668
4669 if (page_state == frame_entry->page_state())
4670 return; // Nothing to update.
4671
4672 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4673
4674 // The document_sequence_number and item_sequence_number recorded in the
4675 // FrameNavigationEntry should not differ from the one coming with the update,
4676 // since it must come from the same document. Do not update it if a difference
4677 // is detected, as this indicates that |frame_entry| is not the correct one.
4678 blink::ExplodedPageState exploded_state;
4679 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4680 return;
4681
4682 if (exploded_state.top.document_sequence_number !=
4683 frame_entry->document_sequence_number() ||
4684 exploded_state.top.item_sequence_number !=
4685 frame_entry->item_sequence_number()) {
4686 return;
4687 }
4688
4689 frame_entry->SetPageState(page_state);
4690 NotifyEntryChanged(entry);
4691}
4692
Nate Chapina2c881f52023-11-07 17:02:094693namespace {
4694
4695// The caller is responsible for ensuring the entry is same-origin to the
4696// origin to be committed.
4697blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4698 FrameNavigationEntry* frame_entry,
4699 int64_t pending_document_sequence_number) {
4700 blink::ExplodedPageState exploded_state;
4701 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4702 &exploded_state)) {
4703 return nullptr;
4704 }
4705 blink::ExplodedFrameState frame_state = exploded_state.top;
4706
4707 // If the document represented by this FNE hid its full url from appearing in
4708 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4709 // in the navigation API as well (unless we're navigating to that document).
4710 std::u16string url;
4711 if (pending_document_sequence_number ==
4712 frame_entry->document_sequence_number() ||
4713 !frame_entry->protect_url_in_navigation_api()) {
4714 url = frame_state.url_string.value_or(std::u16string());
4715 }
4716
4717 return blink::mojom::NavigationApiHistoryEntry::New(
4718 frame_state.navigation_api_key.value_or(std::u16string()),
4719 frame_state.navigation_api_id.value_or(std::u16string()), url,
4720 frame_state.item_sequence_number, frame_state.document_sequence_number,
4721 frame_state.navigation_api_state);
4722}
4723
4724} // namespace
4725
Domenic Denicolacd30f5f82022-03-16 21:48:014726std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4727NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574728 Direction direction,
4729 int entry_index,
4730 const url::Origin& pending_origin,
4731 FrameTreeNode* node,
4732 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304733 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094734 int64_t pending_document_sequence_number,
4735 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014736 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454737 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174738 // Don't process the initial entry.
4739 DCHECK_EQ(GetEntryCount(), 1);
4740 return entries;
4741 }
Nate Chapind1fe3612021-04-16 20:45:574742 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304743 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574744 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4745 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094746 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574747 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414748 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574749 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014750 // An entry should only appear in the navigation API entries if it is for
4751 // the same origin as the document being committed. Check the committed
4752 // origin, or if that is not available (during restore), check against the
4753 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584754 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094755 // once we can be sure that entries with the same ISN will never be
4756 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414757 url::Origin frame_entry_origin =
4758 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4759 frame_entry->url(),
4760 frame_entry->initiator_origin().value_or(url::Origin())));
4761 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574762 break;
4763 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4764 continue;
Nate Chapina2c881f52023-11-07 17:02:094765 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4766 ToNavigationApiHistoryEntry(frame_entry,
4767 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304768 DCHECK(entry->url.empty() ||
4769 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574770 entries.push_back(std::move(entry));
4771 previous_item_sequence_number = frame_entry->item_sequence_number();
4772 }
4773 }
4774 // If |entries| was constructed by iterating backwards from
4775 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4776 // earliest-at-the-front. Reverse it.
4777 if (direction == Direction::kBack)
4778 std::reverse(entries.begin(), entries.end());
4779 return entries;
4780}
4781
Domenic Denicolacd30f5f82022-03-16 21:48:014782blink::mojom::NavigationApiHistoryEntryArraysPtr
4783NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554784 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574785 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404786 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444787 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404788 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574789
Nate Chapind1fe3612021-04-16 20:45:574790 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554791 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574792
Nate Chapine82339d02022-05-03 23:48:254793 // NOTE: |entry_index| is the index where this entry will commit if no
4794 // modifications are made between now and DidCommitNavigation. This is used to
4795 // walk |entries_| and determine which entries should be exposed by the
4796 // navigation API. It is important to calculate this correctly, because blink
4797 // will cancel a same-document history commit if it's not present in the
4798 // entries blink knows about.
4799 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574800 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304801 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254802 bool will_create_new_entry = false;
4803 if (GetPendingEntryIndex() != -1) {
4804 entry_index = GetPendingEntryIndex();
4805 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4806 pending_item_sequence_number = frame_entry->item_sequence_number();
4807 pending_document_sequence_number =
4808 frame_entry->document_sequence_number();
4809 }
4810 } else if (request &&
4811 !NavigationTypeUtils::IsReload(
4812 request->common_params().navigation_type) &&
4813 !NavigationTypeUtils::IsHistory(
4814 request->common_params().navigation_type) &&
4815 !request->common_params().should_replace_current_entry &&
4816 !request->common_params()
4817 .is_history_navigation_in_new_child_frame) {
4818 will_create_new_entry = true;
4819 entry_index = GetLastCommittedEntryIndex() + 1;
4820 // Don't set pending_item_sequence_number or
4821 // pending_document_sequence_number in this case - a new unique isn/dsn will
4822 // be calculated in the renderer later.
4823 } else if (GetLastCommittedEntryIndex() != -1) {
4824 entry_index = GetLastCommittedEntryIndex();
4825 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574826 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304827 pending_document_sequence_number =
4828 frame_entry->document_sequence_number();
4829 }
Nate Chapind1fe3612021-04-16 20:45:574830 }
4831
Domenic Denicolacd30f5f82022-03-16 21:48:014832 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254833 if (entry_index == -1) {
4834 // TODO(rakina): Exit early when there is no last committed entry.
4835 // Remove when InitialNavigationEntry ships.
4836 return entry_arrays;
4837 }
4838
Nate Chapina2c881f52023-11-07 17:02:094839 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014840 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574841 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094842 pending_item_sequence_number, pending_document_sequence_number,
4843 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574844
4845 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094846 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574847 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014848 entry_arrays->forward_entries =
4849 PopulateSingleNavigationApiHistoryEntryVector(
4850 Direction::kForward, entry_index, pending_origin, node,
4851 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094852 pending_document_sequence_number, forwardmost_index);
4853 }
4854
4855 // If the previous entry is within the block of contiguous entries being
4856 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254857 FrameNavigationEntry* previous_entry = nullptr;
4858 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:054859 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4860 .initiator_frame_tree_node_id();
4861 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:254862 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4863 previous_entry = initiator_node->frame_tree()
4864 .controller()
4865 .GetLastCommittedEntry()
4866 ->GetFrameEntry(initiator_node);
4867 }
4868 } else if (GetLastCommittedEntryIndex() != -1 &&
4869 GetLastCommittedEntryIndex() >= backmost_index &&
4870 GetLastCommittedEntryIndex() <= forwardmost_index) {
4871 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4872 }
4873 if (previous_entry) {
4874 url::Origin previous_entry_origin =
4875 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4876 previous_entry->url(),
4877 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:584878 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:254879 // once we can be sure that entries with the same ISN will never be
4880 // cross-origin.
4881 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4882 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4883 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094884 }
Nate Chapind1fe3612021-04-16 20:45:574885 }
Nate Chapinc06cf80a2023-11-18 01:12:254886
Nate Chapin4e657a472022-02-06 03:38:374887 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574888}
4889
Nate Chapinfbfe5af2021-06-10 17:22:084890NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574891NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084892 FrameNavigationEntry* current_entry,
4893 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574894 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084895 if (!target_entry || !target_entry->committed_origin())
4896 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084897 if (!current_entry->committed_origin()->IsSameOriginWith(
4898 *target_entry->committed_origin())) {
4899 return HistoryNavigationAction::kStopLooking;
4900 }
4901
4902 // NOTE: We don't actually care between kSameDocument and
4903 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574904 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084905 return HistoryNavigationAction::kDifferentDocument;
4906 return HistoryNavigationAction::kKeepLooking;
4907}
4908
Domenic Denicolacc094fb2022-03-16 23:40:574909void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204910 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374911 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144912 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574913 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204914 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084915 FrameNavigationEntry* current_entry =
4916 GetLastCommittedEntry()->GetFrameEntry(node);
4917 if (!current_entry)
4918 return;
4919
Alison Gale47d1537d2024-04-19 21:31:464920 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:134921 // when `navigation.traverseTo()` is called.
4922
Nate Chapinfbfe5af2021-06-10 17:22:084923 // We want to find the nearest matching entry that is contiguously
4924 // same-instance and same-origin. Check back first, then forward.
4925 // TODO(japhet): Link spec here once it exists.
4926 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574927 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084928 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4929 if (result == HistoryNavigationAction::kStopLooking)
4930 break;
4931 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144932 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084933 return;
4934 }
4935 }
4936 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574937 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084938 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4939 if (result == HistoryNavigationAction::kStopLooking)
4940 break;
4941 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144942 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084943 return;
4944 }
4945 }
Nate Chapinbf682fa32022-09-26 22:41:204946
4947 // If we fall through to here, a matching NavigationEntry couldn't be found.
4948 // Notify the renderer that the navigation was cancelled.
4949 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4950 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084951}
4952
Domenic Denicolacc094fb2022-03-16 23:40:574953bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304954 network::mojom::ReferrerPolicy referrer_policy) {
4955 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4956 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4957}
4958
shivanigithubf405bf0d2021-11-05 17:58:334959bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4960 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:314961 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:334962 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544963 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:464964 // The preview mode appears as prerendered page in renderers, and
4965 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:034966 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:514967 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:334968 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544969}
4970
Julie Jeongeun Kim0e242242022-11-30 10:45:094971void NavigationControllerImpl::DidChangeReferrerPolicy(
4972 FrameTreeNode* node,
4973 network::mojom::ReferrerPolicy referrer_policy) {
4974 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4975 if (!entry)
4976 return;
4977
4978 // The FrameNavigationEntry may want to change whether to protect its url
4979 // in the navigation API when the referrer policy changes.
4980 entry->set_protect_url_in_navigation_api(
4981 ShouldProtectUrlInNavigationApi(referrer_policy));
4982}
4983
[email protected]8ff00d72012-10-23 19:12:214984} // namespace content