blob: 026607da671e085fbbf4009ca5bfd2eaba46f462 [file] [log] [blame]
Avi Drissman4e1b7bc32022-09-15 14:03:501// Copyright 2013 The Chromium Authors
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit09911bf2008-07-26 23:55:294
creis4e2ecb72015-06-20 00:46:305/*
6 * Copyright (C) 2006, 2007, 2008, 2009 Apple Inc. All rights reserved.
7 * Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
8 * Copyright (C) 2008, 2009 Torch Mobile Inc. All rights reserved.
9 * (http://www.torchmobile.com/)
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 *
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 * 3. Neither the name of Apple Computer, Inc. ("Apple") nor the names of
21 * its contributors may be used to endorse or promote products derived
22 * from this software without specific prior written permission.
23 *
24 * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
25 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
26 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27 * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
28 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
29 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
30 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
31 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
33 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
34 */
35
danakjc492bf82020-09-09 20:02:4436#include "content/browser/renderer_host/navigation_controller_impl.h"
initial.commit09911bf2008-07-26 23:55:2937
Lei Zhang96031532019-10-10 19:05:4738#include <algorithm>
dcheng36b6aec92015-12-26 06:16:3639#include <utility>
40
[email protected]eabfe1912014-05-12 10:07:2841#include "base/command_line.h"
Ayu Ishii2f825852022-03-08 19:47:3842#include "base/containers/adapters.h"
Rakina Zata Amni627360d2022-02-24 00:53:4043#include "base/debug/dump_without_crashing.h"
Avi Drissmanadac21992023-01-11 23:46:3944#include "base/functional/bind.h"
initial.commit09911bf2008-07-26 23:55:2945#include "base/logging.h"
asvitkine30330812016-08-30 04:01:0846#include "base/metrics/histogram_macros.h"
Charlie Reis23c26da2022-01-29 00:57:4747#include "base/numerics/safe_conversions.h"
Ryan Hamilton7f3bd3d2022-04-23 00:07:3948#include "base/strings/escape.h"
[email protected]348fbaac2013-06-11 06:31:5149#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0050#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3751#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0052#include "base/trace_event/optional_trace_event.h"
ssid3e765612015-01-28 04:03:4253#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0854#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5955#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2856#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1857#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3958#include "content/browser/blob_storage/chrome_blob_storage_context.h"
William Liu055a3542023-04-02 17:21:1959#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3160#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4161#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0462#include "content/browser/dom_storage/session_storage_namespace_impl.h"
Nate Chapinc06cf80a2023-11-18 01:12:2563#include "content/browser/preloading/prerender/prerender_host.h"
Sharon Yang242ef822023-05-15 21:07:3264#include "content/browser/process_lock.h"
Mingyu Lei68f34412023-08-21 07:31:3765#include "content/browser/renderer_host/back_forward_cache_impl.h"
danakjc492bf82020-09-09 20:02:4466#include "content/browser/renderer_host/debug_urls.h"
67#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0068#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3369#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4470#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5771#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4472#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1973#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
74#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.h"
Khushal Sagar94ea2dc2024-08-06 17:15:2675#include "content/browser/renderer_host/navigation_transitions/navigation_transition_config.h"
danakjc492bf82020-09-09 20:02:4476#include "content/browser/renderer_host/navigator.h"
Takashi Toyoshima4dad2c12023-11-13 10:04:4677#include "content/browser/renderer_host/page_delegate.h"
danakjc492bf82020-09-09 20:02:4478#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0079#include "content/browser/renderer_host/render_view_host_impl.h"
Mike Jacksone2aa7af2023-05-17 06:45:0780#include "content/browser/renderer_host/system_entropy_utils.h"
Sharon Yangd70a5392021-10-26 23:06:3281#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3382#include "content/browser/site_instance_impl.h"
Camille Lamy5193caa2018-10-12 11:59:4283#include "content/common/content_constants_internal.h"
Rakina Zata Amni84a859df2024-06-07 15:56:3284#include "content/common/content_navigation_policy.h"
Nate Chapind1fe3612021-04-16 20:45:5785#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5186#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1187#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1988#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1189#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4690#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0091#include "content/public/browser/navigation_details.h"
Lei Zhang96031532019-10-10 19:05:4792#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5893#include "content/public/browser/render_widget_host.h"
94#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1095#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3496#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1997#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3898#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1099#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47100#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43101#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59102#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36103#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57104#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18105#include "services/metrics/public/cpp/ukm_builders.h"
106#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17107#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37108#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44109#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58110#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39111#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30112#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21113#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06114#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43115#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50116#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31117#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51118#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46119#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26120#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29121
[email protected]8ff00d72012-10-23 19:12:21122namespace content {
[email protected]e9ba4472008-09-14 15:42:43123namespace {
124
125// Invoked when entries have been pruned, or removed. For example, if the
126// current entries are [google, digg, yahoo], with the current entry google,
127// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47128void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50129 int index,
[email protected]c12bf1a12008-09-17 16:28:49130 int count) {
[email protected]8ff00d72012-10-23 19:12:21131 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50132 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49133 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14134 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43135}
136
[email protected]e9ba4472008-09-14 15:42:43137// Configure all the NavigationEntries in entries for restore. This resets
138// the transition type to reload and makes sure the content state isn't empty.
139void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57140 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48141 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47142 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43143 // Use a transition type of reload so that we don't incorrectly increase
144 // the typed count.
Lei Zhang96031532019-10-10 19:05:47145 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
146 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43147 }
148}
149
[email protected]bf70edce2012-06-20 22:32:22150// Determines whether or not we should be carrying over a user agent override
151// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57152bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22153 return last_entry && last_entry->GetIsOverridingUserAgent();
154}
155
Camille Lamy5193caa2018-10-12 11:59:42156// Determines whether to override user agent for a navigation.
157bool ShouldOverrideUserAgent(
158 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57159 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42160 switch (override_user_agent) {
161 case NavigationController::UA_OVERRIDE_INHERIT:
162 return ShouldKeepOverride(last_committed_entry);
163 case NavigationController::UA_OVERRIDE_TRUE:
164 return true;
165 case NavigationController::UA_OVERRIDE_FALSE:
166 return false;
Camille Lamy5193caa2018-10-12 11:59:42167 }
Peter Boströmfc7ddc182024-10-31 19:37:21168 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42169}
170
Rakina Zata Amni312822d72021-06-04 16:13:37171// Returns true if this navigation should be treated as a reload. For e.g.
Liang Zhao0351d762024-11-13 00:10:07172// clicking on a link which results in a navigation to the last committed URL
173// (but wasn't converted to do a replacement navigation in the renderer), etc.
174// This intentionally excludes navigating to the last committed URL via the
175// address bar, so that the current scroll position is not restored.
Fergal Daly766177d2020-07-07 07:54:04176// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
177// |base_url_for_data_url|, |transition_type| correspond to the new navigation
178// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
179// navigation that committed.
180bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
181 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57182 const GURL& virtual_url,
183 const GURL& base_url_for_data_url,
184 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57185 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37186 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57187 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37188 // Navigations intended to do a replacement shouldn't be converted to do a
189 // reload.
190 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28191 return false;
clamy0a656e42018-02-06 18:18:28192 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45193 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55194 return false;
195
arthursonzogni7a8243682017-12-14 16:41:42196 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28197 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42198 return false;
199
Liang Zhao0351d762024-11-13 00:10:07200 // Same URL navigations from the address bar should only be treated as reloads
201 // if PAGE_TRANSITION_RELOAD is set (not for PAGE_TRANSITION_TYPED or
202 // PAGE_TRANSITION_LINK). In non-address-bar cases, PAGE_TRANSITION_TYPED
203 // and PAGE_TRANSITION_LINK can be treated as reloads.
clamy0a656e42018-02-06 18:18:28204 bool transition_type_can_be_converted = false;
Liang Zhao0351d762024-11-13 00:10:07205 if (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR) {
206 if (ui::PageTransitionCoreTypeIs(transition_type,
207 ui::PAGE_TRANSITION_RELOAD)) {
208 transition_type_can_be_converted = true;
209 }
210 } else {
211 if (ui::PageTransitionCoreTypeIs(transition_type,
212 ui::PAGE_TRANSITION_TYPED) ||
213 ui::PageTransitionCoreTypeIs(transition_type,
214 ui::PAGE_TRANSITION_LINK)) {
215 transition_type_can_be_converted = true;
216 }
ananta3bdd8ae2016-12-22 17:11:55217 }
clamy0a656e42018-02-06 18:18:28218 if (!transition_type_can_be_converted)
219 return false;
220
221 // This check is required for cases like view-source:, etc. Here the URL of
222 // the navigation entry would contain the url of the page, while the virtual
223 // URL contains the full URL including the view-source prefix.
224 if (virtual_url != last_committed_entry->GetVirtualURL())
225 return false;
226
Fergal Daly766177d2020-07-07 07:54:04227 // Check that the URLs match.
228 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
229 // If there's no frame entry then by definition the URLs don't match.
230 if (!frame_entry)
231 return false;
232
233 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28234 return false;
235
236 // This check is required for Android WebView loadDataWithBaseURL. Apps
237 // can pass in anything in the base URL and we need to ensure that these
238 // match before classifying it as a reload.
239 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
240 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
241 return false;
ananta3bdd8ae2016-12-22 17:11:55242 }
243
clamy0a656e42018-02-06 18:18:28244 // Skip entries with SSL errors.
245 if (last_committed_entry->ssl_error())
246 return false;
247
248 // Don't convert to a reload when the last navigation was a POST or the new
249 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04250 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28251 return false;
252
253 return true;
ananta3bdd8ae2016-12-22 17:11:55254}
255
Arthur Sonzognic686e8f2024-01-11 08:36:37256std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12257 const mojom::DidCommitProvisionalLoadParams& params,
258 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32259 // Error pages commit in an opaque origin, yet have the real URL that resulted
260 // in an error as the |params.url|. Since successful reload of an error page
261 // should commit in the correct origin, setting the opaque origin on the
262 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17263 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37264 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32265
Arthur Sonzognic686e8f2024-01-11 08:36:37266 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32267}
268
Alex Moshchuk99242832023-05-22 17:21:44269bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42270 const GURL& virtual_url,
271 const GURL& dest_url) {
272 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44273 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
274 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42275 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
276 << virtual_url.possibly_invalid_spec();
277 return false;
278 }
279
280 // Don't attempt to navigate to non-empty invalid URLs.
281 if (!dest_url.is_valid() && !dest_url.is_empty()) {
282 LOG(WARNING) << "Refusing to load invalid URL: "
283 << dest_url.possibly_invalid_spec();
284 return false;
285 }
286
287 // The renderer will reject IPC messages with URLs longer than
288 // this limit, so don't attempt to navigate with a longer URL.
289 if (dest_url.spec().size() > url::kMaxURLChars) {
290 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
291 << " characters.";
292 return false;
293 }
294
Aaron Colwell33109c592020-04-21 21:31:19295 // Reject renderer debug URLs because they should have been handled before
296 // we get to this point. This check handles renderer debug URLs
297 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
298 // provides defense-in-depth if a renderer debug URL manages to get here via
299 // some other path. We want to reject the navigation here so it doesn't
300 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30301 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19302 LOG(WARNING) << "Refusing to load renderer debug URL: "
303 << dest_url.possibly_invalid_spec();
304 return false;
305 }
306
Alex Moshchuk99242832023-05-22 17:21:44307 // Guests only support navigations to known-safe schemes. This check already
308 // exists in the extensions layer, where it also dispatches proper events to
309 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
310 // for defense-in-depth to ensure that no other places in the codebase
311 // accidentally navigate guests to schemes such as WebUI, which is not
312 // supported. See https://crbug.com/1444221.
313 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
314 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
315 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
316 !dest_url.SchemeIs(url::kAboutScheme)) {
317 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
318 << dest_url.possibly_invalid_spec();
319 return false;
320 }
321 }
322
Camille Lamy5193caa2018-10-12 11:59:42323 return true;
324}
325
Mikel Astizba9cf2fd2017-12-17 10:38:10326// See replaced_navigation_entry_data.h for details: this information is meant
327// to ensure |*output_entry| keeps track of its original URL (landing page in
328// case of server redirects) as it gets replaced (e.g. history.replaceState()),
329// without overwriting it later, for main frames.
330void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57331 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10332 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17333 if (output_entry->GetReplacedEntryData().has_value() ||
334 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10335 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17336 }
Mikel Astizba9cf2fd2017-12-17 10:38:10337
338 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57339 data.first_committed_url = replaced_entry->GetURL();
340 data.first_timestamp = replaced_entry->GetTimestamp();
341 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29342 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10343}
344
Minggang Wangb9f3fa92021-07-01 15:30:31345blink::mojom::NavigationType GetNavigationType(
346 const GURL& old_url,
347 const GURL& new_url,
348 ReloadType reload_type,
349 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52350 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31351 bool has_pending_cross_document_commit,
352 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49353 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13354 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49355 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23356 // Reload navigations
357 switch (reload_type) {
358 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31359 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23360 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31361 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23362 case ReloadType::NONE:
363 break; // Fall through to rest of function.
364 }
365
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08366 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31367 return entry->GetHasPostData()
368 ? blink::mojom::NavigationType::RESTORE_WITH_POST
369 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23370 }
371
danakjb952ef12021-01-14 19:58:49372 const bool can_be_same_document =
373 // A pending cross-document commit means this navigation will not occur in
374 // the current document, as that document would end up being replaced in
375 // the meantime.
376 !has_pending_cross_document_commit &&
377 // If the current document is an error page, we should always treat it as
378 // a different-document navigation so that we'll attempt to load the
379 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49380 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13381 // If the navigation is an embedder-initiated navigation of a fenced
382 // frame root (i.e. enters a fenced frame tree from outside),
383 // same-document navigations should be disabled because we don't want to
384 // allow information to be joined across multiple embedder-initiated
385 // fenced frame navigations (which may contain separate cross-site data).
386 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49387 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
388 // same-document navigations should be disabled because we want to force
389 // the creation of a new browsing context group.
390 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12391
clamyea99ea12018-05-28 13:54:23392 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52393 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12394 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31395 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
396 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23397 }
398 DCHECK(!is_same_document_history_load);
399
400 // A same-document fragment-navigation happens when the only part of the url
401 // that is modified is after the '#' character.
402 //
403 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12404 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23405 //
406 // Note: this check is only valid for navigations that are not history
407 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
408 // history navigation from 'A#foo' to 'A#bar' is not a same-document
409 // navigation, but a different-document one. This is why history navigation
410 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47411 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52412 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12413
414 // The one case where we do the wrong thing here and incorrectly choose
415 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
416 // the renderer is a frameset. All frameset navigations should be
417 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
418 // navigation would do the right thing, as it would send it to the browser and
419 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
420 // into this method). But since we can't tell that case here for browser-
421 // initiated navigations, we have to get the renderer involved. In that case
422 // the navigation would be restarted due to the renderer spending a reply of
423 // mojom::CommitResult::RestartCrossDocument.
424
425 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31426 ? blink::mojom::NavigationType::SAME_DOCUMENT
427 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23428}
429
Camille Lamy5193caa2018-10-12 11:59:42430// Adjusts the original input URL if needed, to get the URL to actually load and
431// the virtual URL, which may differ.
432void RewriteUrlForNavigation(const GURL& original_url,
433 BrowserContext* browser_context,
434 GURL* url_to_load,
435 GURL* virtual_url,
436 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42437 // Allow the browser URL handler to rewrite the URL. This will, for example,
438 // remove "view-source:" from the beginning of the URL to get the URL that
439 // will actually be loaded. This real URL won't be shown to the user, just
440 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31441 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42442 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
443 url_to_load, browser_context, reverse_on_redirect);
444}
445
446#if DCHECK_IS_ON()
447// Helper sanity check function used in debug mode.
448void ValidateRequestMatchesEntry(NavigationRequest* request,
449 NavigationEntryImpl* entry) {
450 if (request->frame_tree_node()->IsMainFrame()) {
451 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
452 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31453 ui::PageTransitionFromInt(request->common_params().transition),
454 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42455 }
Nasko Oskovc36327d2019-01-03 23:23:04456 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42457 entry->should_clear_history_list());
458 DCHECK_EQ(request->common_params().has_user_gesture,
459 entry->has_user_gesture());
460 DCHECK_EQ(request->common_params().base_url_for_data_url,
461 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04462 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42463 entry->GetCanLoadLocalResources());
464 DCHECK_EQ(request->common_params().started_from_context_menu,
465 entry->has_started_from_context_menu());
466
467 FrameNavigationEntry* frame_entry =
468 entry->GetFrameEntry(request->frame_tree_node());
469 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52470 // TODO(https://crbug.com/40467594): This case should be unreachable once
471 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42472 return;
473 }
474
Camille Lamy5193caa2018-10-12 11:59:42475 DCHECK_EQ(request->common_params().method, frame_entry->method());
476
Nasko Oskovc36327d2019-01-03 23:23:04477 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42478 if (redirect_size == frame_entry->redirect_chain().size()) {
479 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04480 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42481 frame_entry->redirect_chain()[i]);
482 }
483 } else {
Peter Boströmfc7ddc182024-10-31 19:37:21484 NOTREACHED();
Camille Lamy5193caa2018-10-12 11:59:42485 }
486}
487#endif // DCHECK_IS_ON()
488
Dave Tapuska8bfd84c2019-03-26 20:47:16489// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20490// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16491bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20492 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16493 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20494 DCHECK(sandboxed_initiator_rfh);
495 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
496 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16497 for (auto& item : navigations) {
498 bool within_subtree = false;
499 // Check whether this NavigationRequest affects a frame within the
500 // sandboxed frame's subtree by walking up the tree looking for the
501 // sandboxed frame.
502 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03503 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20504 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16505 within_subtree = true;
506 break;
507 }
508 }
509 if (!within_subtree)
510 return false;
511 }
512 return true;
513}
514
William Liu122754942024-01-18 22:34:39515// Used for "Navigation.SessionHistoryCount" histogram.
516enum class HistoryNavTypeForHistogram {
517 // A same-doc or cross-doc navigation of the main frame. We can only have one
518 // main frame request per `NavigationController::GoToIndex()`.
519 kMainFrame = 0,
520 // `NavigationController::GoToIndex()` creates one main frame request and
521 // one or more subframe requests.
522 kMainFrameAndSubframe,
523 // `NavigationController::GoToIndex()` creates one or more subframe requests.
524 kSubframe,
525 // Used for histogram boundary.
526 kCount
527};
528
529void CountRequests(
530 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
531 int& mutable_main_frame_cnt,
532 int& mutable_subframe_cnt) {
533 for (const auto& req : requests) {
534 if (req->IsInPrimaryMainFrame()) {
535 // We can only have one main frame navigation at a time.
536 CHECK_EQ(mutable_main_frame_cnt, 0);
537 ++mutable_main_frame_cnt;
538 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
539 ++mutable_subframe_cnt;
540 }
541 }
542}
543
544// Record the number of different types of navigations as histograms. See
545// `HistoryNavTypeForHistogram` for the types.
546void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
547 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
548 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
549 // We must have one request.
550 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
551
552 int main_frame_cnt = 0;
553 int subframe_cnt = 0;
554 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
555 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
556
557 std::optional<HistoryNavTypeForHistogram> history_nav_type;
558 if (main_frame_cnt > 0) {
559 if (subframe_cnt == 0) {
560 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
561 } else {
562 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
563 }
564 } else if (subframe_cnt > 0) {
565 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
566 }
567 if (history_nav_type.has_value()) {
568 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
569 history_nav_type.value(),
570 HistoryNavTypeForHistogram::kCount);
571 }
572}
573
[email protected]e9ba4472008-09-14 15:42:43574} // namespace
575
arthursonzogni66f711c2019-10-08 14:40:36576// NavigationControllerImpl::PendingEntryRef------------------------------------
577
578NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
579 base::WeakPtr<NavigationControllerImpl> controller)
580 : controller_(controller) {}
581
582NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
583 if (!controller_) // Can be null with interstitials.
584 return;
585
586 controller_->PendingEntryRefDeleted(this);
587}
588
[email protected]d202a7c2012-01-04 07:53:47589// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29590
[email protected]23a918b2014-07-15 09:51:36591const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23592
[email protected]765b35502008-08-21 00:51:20593// static
[email protected]d202a7c2012-01-04 07:53:47594size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23595 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20596
[email protected]e6fec472013-05-14 05:29:02597// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20598// when testing.
599static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29600
[email protected]71fde352011-12-29 03:29:56601// static
dcheng9bfa5162016-04-09 01:00:57602std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
603 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10604 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37605 std::optional<url::Origin> initiator_origin,
606 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10607 ui::PageTransition transition,
608 bool is_renderer_initiated,
609 const std::string& extra_headers,
610 BrowserContext* browser_context,
611 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
612 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21613 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37614 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32615 is_renderer_initiated, extra_headers, browser_context,
616 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10617}
618
619// static
620std::unique_ptr<NavigationEntryImpl>
621NavigationControllerImpl::CreateNavigationEntry(
622 const GURL& url,
623 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37624 std::optional<url::Origin> initiator_origin,
625 std::optional<GURL> initiator_base_url,
626 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57627 ui::PageTransition transition,
628 bool is_renderer_initiated,
629 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09630 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17631 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
632 bool rewrite_virtual_urls) {
633 GURL url_to_load = url;
634 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56635 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17636 if (rewrite_virtual_urls) {
637 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
638 &reverse_on_redirect);
639 }
Lukasz Anforowicz641234d52019-11-07 21:07:10640 // Let the NTP override the navigation params and pretend that this is a
641 // browser-initiated, bookmark-like navigation.
642 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32643 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21644 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10645
Patrick Monettef507e982019-06-19 20:18:06646 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28647 nullptr, // The site instance for tabs is sent on navigation
648 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21649 url_to_load, referrer, initiator_origin, initiator_base_url,
650 std::u16string(), transition, is_renderer_initiated,
651 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17652 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42653 entry->SetVirtualURL(virtual_url);
654 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56655 entry->set_update_virtual_url_with_url(reverse_on_redirect);
656 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06657 return entry;
[email protected]71fde352011-12-29 03:29:56658}
659
[email protected]cdcb1dee2012-01-04 00:46:20660// static
661void NavigationController::DisablePromptOnRepost() {
662 g_check_for_repost = false;
663}
664
[email protected]c5b88d82012-10-06 17:03:33665base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
666 base::Time t) {
667 // If |t| is between the water marks, we're in a run of duplicates
668 // or just getting out of it, so increase the high-water mark to get
669 // a time that probably hasn't been used before and return it.
670 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35671 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33672 return high_water_mark_;
673 }
674
675 // Otherwise, we're clear of the last duplicate run, so reset the
676 // water marks.
677 low_water_mark_ = high_water_mark_ = t;
678 return t;
679}
680
ckitagawa0faa5e42020-06-17 17:30:54681NavigationControllerImpl::ScopedShowRepostDialogForTesting::
682 ScopedShowRepostDialogForTesting()
683 : was_disallowed_(g_check_for_repost) {
684 g_check_for_repost = true;
685}
686
687NavigationControllerImpl::ScopedShowRepostDialogForTesting::
688 ~ScopedShowRepostDialogForTesting() {
689 g_check_for_repost = was_disallowed_;
690}
691
Nate Chapin9eb16be72022-09-23 22:54:31692NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
693 base::SafeRef<NavigationControllerImpl> controller)
694 : controller_(controller) {
695 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
696 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
697 frame_tree_node_id_to_keys_.insert(
698 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
699 if (auto* frame_entry = frame_tree_node->current_frame_host()
700 ->last_committed_frame_entry()) {
701 frame_tree_node_id_to_doc_seq_nos_.insert(
702 {frame_tree_node->frame_tree_node_id(),
703 frame_entry->document_sequence_number()});
704 }
705 }
706 PopulateKeySet(Direction::kBack);
707 PopulateKeySet(Direction::kForward);
708}
709
710void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
711 Direction direction) {
712 // Keep track of which FrameTreeNodes may still have relevant API keys in
713 // additional FrameNavigationEntries.
714 std::set<FrameTreeNode*> nodes_to_process;
715 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
716 nodes_to_process.insert(node);
717 }
718
719 const int offset = direction == Direction::kForward ? 1 : -1;
720 const int start = direction == Direction::kForward
721 ? controller_->GetLastCommittedEntryIndex()
722 : controller_->GetLastCommittedEntryIndex() - 1;
723 for (int i = start;
724 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
725 i += offset) {
726 std::set<FrameTreeNode*> nodes_to_continue_processing;
727
728 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
729 entry->ForEachFrameEntry([this, &nodes_to_process,
730 &nodes_to_continue_processing,
731 &entry](FrameNavigationEntry* frame_entry) {
732 // Find the |node| that matches |frame_entry|, if any.
733 FrameTreeNode* node = nullptr;
734 if (frame_entry == entry->root_node()->frame_entry) {
735 node = controller_->frame_tree().root();
736 } else {
737 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
738 if (it == names_to_nodes_.end())
739 return;
740 node = it->second;
741 }
742
743 // Skip this node if a previous step determine there are no longer
744 // relevant navigation API keys in this direction.
745 if (nodes_to_process.find(node) == nodes_to_process.end())
746 return;
747
748 // Stop processing |node| if we reach a point where it's cross-origin.
749 // See also PopulateSingleNavigationApiHistoryEntryVector().
750 url::Origin frame_entry_origin =
751 frame_entry->committed_origin().value_or(url::Origin::Resolve(
752 frame_entry->url(),
753 frame_entry->initiator_origin().value_or(url::Origin())));
754 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
755 return;
756
757 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
758 frame_entry->navigation_api_key());
759 // Mark |node| as needing more processing for the next entry.
760 nodes_to_continue_processing.insert(node);
761
762 // Check whether |node| went cross-document. If so, its children are
763 // no longer the same conceptual iframe as the current one, and
764 // should no longer be processed. This check is intentionally done
765 // after processing the current |node|, which may still have relevant
766 // discarded API keys.
767 if (frame_entry->document_sequence_number() !=
768 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50769 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31770 nodes_to_process.erase(descendant);
771 }
772 });
773
774 nodes_to_process.swap(nodes_to_continue_processing);
775 }
776}
777
778NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
779 std::set<std::string> all_keys;
780 // Find all remaining navigation API keys after some entries have been
781 // removed.
782 for (auto& entry : controller_->entries_) {
783 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
784 all_keys.insert(frame_entry->navigation_api_key());
785 });
786 }
787
788 // Notify each frame in the renderer of any disposed navigation API keys.
789 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
790 std::vector<std::string> disposed_keys;
791 for (const auto& key : id_to_keys.second) {
792 if (all_keys.find(key) == all_keys.end())
793 disposed_keys.push_back(key);
794 }
795 if (disposed_keys.empty())
796 continue;
797
798 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
799 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
800 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
801 }
802}
803
[email protected]d202a7c2012-01-04 07:53:47804NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00805 BrowserContext* browser_context,
806 FrameTree& frame_tree,
807 NavigationControllerDelegate* delegate)
808 : frame_tree_(frame_tree),
809 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57810 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22811 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37812 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
813 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37814 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29815}
816
[email protected]d202a7c2012-01-04 07:53:47817NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00818 // The NavigationControllerImpl might be called inside its delegate
819 // destructor. Calling it is not valid anymore.
820 delegate_ = nullptr;
821 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29822}
823
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57824BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55825 return browser_context_;
826}
827
[email protected]d202a7c2012-01-04 07:53:47828void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30829 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36830 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57831 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47832 // Note that it's possible for `entries_` to contain multiple entries at this
833 // point, as Restore() might be called on a NavigationController that is
834 // already used (e.g. due to WebView's restoreState() API), not only for fresh
835 // NavigationControllers. These entries are not cleared to preserve legacy
836 // behavior and also because `pending_entry_` might point to one of the
837 // pre-existing entries. An exception for this is when `entries_` contains
838 // only the initial NavigationEntry, which must be removed.
839
840 // Do not proceed if selected_navigation will be out of bounds for the updated
841 // entries_ list, since it will be assigned to last_committed_entry_index_ and
842 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58843 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47844 // is empty, since there should be no work to do (rather than marking the
845 // existing entries as needing reload). Also consider returning early if the
846 // selected index is -1, which represents a no-committed-entry state.
847 if (selected_navigation < -1 ||
848 selected_navigation >=
849 base::checked_cast<int>(entries->size() + entries_.size())) {
850 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24851 }
Charlie Reis23c26da2022-01-29 00:57:47852
Rakina Zata Amni46087a12022-11-11 08:28:38853 // There will always be at least one entry (new NavigationControllers will
854 // have the initial NavigationEntry).
855 if (selected_navigation == -1)
856 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47857
Rakina Zata Amni46087a12022-11-11 08:28:38858 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
859 // If we are on the initial NavigationEntry, it must be the only entry in
860 // the list. Since it's impossible to do a history navigation to the
861 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
862 // `pending_entry` might be set for a new non-history navigation).
863 // Note that we should not clear `entries_` if `entries` is empty (when
864 // InitialNavigationEntry mode is enabled), since that would leave us
865 // without any NavigationEntry.
866 CHECK_EQ(1, GetEntryCount());
867 CHECK_EQ(-1, pending_entry_index_);
868 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47869 }
[email protected]ce3fa3c2009-04-20 19:55:57870
[email protected]ce3fa3c2009-04-20 19:55:57871 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44872 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03873 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47874 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43875 if (entry->GetURL().is_empty()) {
876 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01877 // persisting the initial NavigationEntry [which is no longer possible but
878 // some old persisted sessions might still contain it] or when the
879 // serializer failed to write the URL because it's too long). Trying to
880 // restore and navigate to an entry with an empty URL will result in
881 // crashes, so change the URL to about:blank. See also
882 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43883 entry->SetURL(GURL(url::kAboutBlankURL));
884 }
dcheng36b6aec92015-12-26 06:16:36885 entries_.push_back(
886 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47887 }
avif16f85a72015-11-13 18:25:03888
889 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
890 // cleared out safely.
891 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57892
893 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36894 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57895}
896
toyoshim6142d96f2016-12-19 09:07:25897void NavigationControllerImpl::Reload(ReloadType reload_type,
898 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03899 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
900 (int)reload_type);
901 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
902 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28903 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28904 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32905 int current_index = -1;
906
Carlos IL42b416592019-10-07 23:10:36907 if (entry_replaced_by_post_commit_error_) {
908 // If there is an entry that was replaced by a currently active post-commit
909 // error navigation, this can't be the initial navigation.
910 DCHECK(!IsInitialNavigation());
911 // If the current entry is a post commit error, we reload the entry it
912 // replaced instead. We leave the error entry in place until a commit
913 // replaces it, but the pending entry points to the original entry in the
914 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
915 // case that pending_entry_ != entries_[pending_entry_index_].
916 entry = entry_replaced_by_post_commit_error_.get();
917 current_index = GetCurrentEntryIndex();
918 } else if (IsInitialNavigation() && pending_entry_) {
919 // If we are reloading the initial navigation, just use the current
920 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32921 entry = pending_entry_;
922 // The pending entry might be in entries_ (e.g., after a Clone), so we
923 // should also update the current_index.
924 current_index = pending_entry_index_;
925 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00926 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32927 current_index = GetCurrentEntryIndex();
928 if (current_index != -1) {
creis3da03872015-02-20 21:12:32929 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32930 }
[email protected]979a4bc2013-04-24 01:27:15931 }
[email protected]241db352013-04-22 18:04:05932
[email protected]59167c22013-06-03 18:07:32933 // If we are no where, then we can't reload. TODO(darin): We should add a
934 // CanReload method.
935 if (!entry)
936 return;
937
Rakina Zata Amnif297a802022-01-18 03:53:43938 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
939 // We should never navigate to an existing initial NavigationEntry that is
940 // the initial NavigationEntry for the initial empty document that hasn't
941 // been overridden by the synchronous about:blank commit, to preserve
942 // legacy behavior where trying to reload when the main frame is on the
943 // initial empty document won't result in a navigation. See also
944 // https://crbug.com/1277414.
945 return;
946 }
947
Aran Gilman37d11632019-10-08 23:07:15948 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30949 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07950 // they really want to do this. If they do, the dialog will call us back
951 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57952 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02953
[email protected]106a0812010-03-18 00:15:12954 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57955 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47956 return;
initial.commit09911bf2008-07-26 23:55:29957 }
Lei Zhang96031532019-10-10 19:05:47958
Wang Huia25efabc2022-09-24 17:27:22959 // Set ReloadType for |entry|.
960 entry->set_reload_type(reload_type);
961
Lei Zhang96031532019-10-10 19:05:47962 if (!IsInitialNavigation())
963 DiscardNonCommittedEntries();
964
965 pending_entry_ = entry;
966 pending_entry_index_ = current_index;
967 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
968
Nate Chapin45f620582021-09-30 17:45:43969 // location.reload() goes through BeginNavigation, so all reloads triggered
970 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13971 NavigateToExistingPendingEntry(
972 reload_type,
973 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:37974 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:13975 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29976}
977
[email protected]d202a7c2012-01-04 07:53:47978void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48979 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12980}
981
[email protected]d202a7c2012-01-04 07:53:47982void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49983 // If the pending reload type has been cleared by another navigation
984 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48985 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49986 return;
[email protected]106a0812010-03-18 00:15:12987 }
Wang Hui96ab1012022-10-11 02:05:49988 Reload(pending_reload_, false);
989 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12990}
991
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57992bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09993 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11994}
995
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57996bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38997 // Check that we're on the initial NavigationEntry and that this is not a
998 // cloned tab.
999 return IsInitialNavigation() && GetEntryCount() == 1 &&
1000 GetLastCommittedEntry()->IsInitialEntry() &&
1001 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401002}
1003
Aran Gilman37d11632019-10-08 23:07:151004NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1005 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581006 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031007 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581008}
1009
Adithya Srinivasan9b0c99c2021-08-10 15:19:451010NavigationEntryImpl*
1011NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1012 int nav_entry_id) const {
1013 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1014 if (entry)
1015 return entry;
1016 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521017 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451018 : nullptr;
1019}
1020
W. James MacLeanc07dc41b2022-07-25 18:52:161021void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571022 const url::Origin& origin) {
1023 for (int i = 0; i < GetEntryCount(); i++) {
1024 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161025 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571026 }
1027 if (entry_replaced_by_post_commit_error_) {
1028 // It's possible we could come back to this entry if the error
1029 // page/interstitial goes away.
1030 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161031 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571032 }
W. James MacLean1c40862c2020-04-27 21:05:571033}
1034
avi25764702015-06-23 15:43:371035void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571036 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001037 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371038 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271039 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201040}
1041
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571042NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471043 if (pending_entry_)
1044 return pending_entry_;
1045 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201046}
1047
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571048NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321049 // The pending entry is safe to return for new (non-history), browser-
1050 // initiated navigations. Most renderer-initiated navigations should not
1051 // show the pending entry, to prevent URL spoof attacks.
1052 //
1053 // We make an exception for renderer-initiated navigations in new tabs, as
1054 // long as no other page has tried to access the initial empty document in
1055 // the new tab. If another page modifies this blank page, a URL spoof is
1056 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321057 bool safe_to_show_pending =
1058 pending_entry_ &&
1059 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091060 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321061 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461062 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321063
1064 // Also allow showing the pending entry for history navigations in a new tab,
1065 // such as Ctrl+Back. In this case, no existing page is visible and no one
1066 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151067 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1068 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321069 safe_to_show_pending = true;
1070
1071 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191072 return pending_entry_;
1073 return GetLastCommittedEntry();
1074}
1075
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571076int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201077 if (pending_entry_index_ != -1)
1078 return pending_entry_index_;
1079 return last_committed_entry_index_;
1080}
1081
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571082NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381083 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031084 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201085}
1086
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571087bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351088 const std::string& mime_type = frame_tree_->root()
1089 ->current_frame_host()
1090 ->GetPage()
1091 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531092 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1093 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271094 NavigationEntry* visible_entry = GetVisibleEntry();
1095 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391096 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161097}
1098
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571099int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271100 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451101 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271102 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551103 return last_committed_entry_index_;
1104}
1105
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571106int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451107 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291108 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551109 return static_cast<int>(entries_.size());
1110}
1111
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571112NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371113 if (index < 0 || index >= GetEntryCount())
1114 return nullptr;
1115
avif16f85a72015-11-13 18:25:031116 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251117}
1118
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571119NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471120 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201121}
1122
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571123int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461124 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031125}
1126
Arthur Sonzognic686e8f2024-01-11 08:36:371127std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031128 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591129 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1130 return index;
1131 }
Shivani Sharma298d12852019-01-22 20:04:031132 }
Arthur Sonzognic686e8f2024-01-11 08:36:371133 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591134}
1135
1136bool NavigationControllerImpl::CanGoBack() {
1137 return GetIndexForGoBack().has_value();
1138}
1139
Arthur Sonzognic686e8f2024-01-11 08:36:371140std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591141 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1142 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1143 return index;
1144 }
1145 }
Arthur Sonzognic686e8f2024-01-11 08:36:371146 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201147}
1148
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571149bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591150 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201151}
1152
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571153bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031154 int index = GetIndexForOffset(offset);
1155 return index >= 0 && index < GetEntryCount();
1156}
1157
Xiaohan Wang7f8052e02022-01-14 18:44:281158#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151159bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151160 if (offset == 0)
1161 return true;
1162 int increment = offset > 0 ? 1 : -1;
1163 int non_skippable_entries = 0;
1164 for (int index = GetIndexForOffset(increment);
1165 index >= 0 && index < GetEntryCount(); index += increment) {
1166 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1167 non_skippable_entries++;
1168
1169 if (non_skippable_entries == std::abs(offset))
1170 return true;
1171 }
1172 return false;
1173}
1174#endif
1175
[email protected]d202a7c2012-01-04 07:53:471176void NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371177 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061178
Kevin McNeeedc481c2023-04-27 22:30:581179 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211180
Kevin McNee3b3a56192023-03-17 14:40:591181 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201182}
1183
[email protected]d202a7c2012-01-04 07:53:471184void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161185 // Note that at least one entry (the last one) will be non-skippable since
1186 // entries are marked skippable only when they add another entry because of
1187 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371188 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591189
Kevin McNeeedc481c2023-04-27 22:30:581190 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591191
1192 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201193}
1194
[email protected]d202a7c2012-01-04 07:53:471195void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131196 GoToIndex(index, /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371197 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:131198 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161199}
1200
William Liu62ae26c2024-08-08 14:28:161201std::vector<base::WeakPtr<NavigationRequest>>
1202NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201203 int index,
1204 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371205 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131206 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201207 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441208 TRACE_EVENT0("browser,navigation,benchmark",
1209 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501210 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1211 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1212 entries_.size());
1213 // Indices should have have been validated by the caller.
1214 CHECK_GE(index, 0);
1215 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201216
Rakina Zata Amnif297a802022-01-18 03:53:431217 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1218 // We should never navigate to an existing initial NavigationEntry that is
1219 // the initial NavigationEntry for the initial empty document that hasn't
1220 // been overridden by the synchronous about:blank commit, to preserve
1221 // legacy behavior where trying to reload when the main frame is on the
1222 // initial empty document won't result in a navigation. See also
1223 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161224 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431225 }
1226
[email protected]cbab76d2008-10-13 22:42:471227 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201228
arthursonzogni5c4c202d2017-04-25 23:41:271229 DCHECK_EQ(nullptr, pending_entry_);
1230 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431231
arthursonzogni5c4c202d2017-04-25 23:41:271232 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201233 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271234 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1235 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
William Liuec04e382024-05-23 18:03:271236 return NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
1237 soft_navigation_heuristics_task_id,
1238 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201239}
1240
[email protected]d202a7c2012-01-04 07:53:471241void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121242 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031243 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201244 return;
1245
[email protected]9ba14052012-06-22 23:50:031246 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201247}
1248
Nate Chapinbf682fa32022-09-26 22:41:201249void NavigationControllerImpl::GoToOffsetFromRenderer(
1250 int offset,
Yoav Weiss8c573952022-11-17 17:35:131251 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371252 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131253 soft_navigation_heuristics_task_id) {
Nate Chapinbb74c5a52023-07-21 23:13:351254 // Note: This is actually reached in unit tests.
1255 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431256 return;
1257
Nate Chapinbf682fa32022-09-26 22:41:201258 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131259 soft_navigation_heuristics_task_id,
1260 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431261}
1262
William Liu62ae26c2024-08-08 14:28:161263std::vector<base::WeakPtr<NavigationRequest>>
1264NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271265 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1266 /*soft_navigation_heuristics_task_id=*/std::nullopt,
1267 /*navigation_api_key=*/nullptr);
1268}
1269
Xiaohan Wang7f8052e02022-01-14 18:44:281270#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151271void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1272 // Note: This is actually reached in unit tests.
1273 if (!CanGoToOffsetWithSkipping(offset))
1274 return;
1275
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421276 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151277 GoToIndex(GetIndexForOffset(offset));
1278 return;
1279 }
1280 int increment = offset > 0 ? 1 : -1;
1281 // Find the offset without counting skippable entries.
1282 int target_index = GetIndexForOffset(increment);
1283 int non_skippable_entries = 0;
1284 for (int index = target_index; index >= 0 && index < GetEntryCount();
1285 index += increment) {
1286 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1287 non_skippable_entries++;
1288
1289 if (non_skippable_entries == std::abs(offset)) {
1290 target_index = index;
1291 break;
1292 }
1293 }
1294
1295 GoToIndex(target_index);
1296}
1297#endif
1298
[email protected]41374f12013-07-24 02:49:281299bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151300 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281301 return false;
[email protected]6a13a6c2011-12-20 21:47:121302
[email protected]43032342011-03-21 14:10:311303 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281304 return true;
[email protected]cbab76d2008-10-13 22:42:471305}
1306
Michael Thiessen9b14d512019-09-23 21:19:471307void NavigationControllerImpl::PruneForwardEntries() {
1308 DiscardNonCommittedEntries();
1309 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471310 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471311 if (num_removed <= 0)
1312 return;
Nate Chapin9eb16be72022-09-23 22:54:311313 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471314 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1315 NotifyPrunedEntries(this, remove_start_index /* start index */,
1316 num_removed /* count */);
1317}
1318
Aran Gilman37d11632019-10-08 23:07:151319void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1320 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321321 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311322 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511323 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1324 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321325 }
1326}
1327
Harkiran Bolariaba823e42021-05-21 18:30:361328base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1329 const GURL& url,
1330 const Referrer& referrer,
1331 ui::PageTransition transition,
1332 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471333 LoadURLParams params(url);
1334 params.referrer = referrer;
1335 params.transition_type = transition;
1336 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361337 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471338}
1339
Harkiran Bolariaba823e42021-05-21 18:30:361340base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1341 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061342 if (params.is_renderer_initiated)
1343 DCHECK(params.initiator_origin.has_value());
1344
naskob8744d22014-08-28 17:07:431345 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151346 "NavigationControllerImpl::LoadURLWithParams", "url",
1347 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291348 bool is_explicit_navigation =
1349 GetContentClient()->browser()->IsExplicitNavigation(
1350 params.transition_type);
1351 if (HandleDebugURL(params.url, params.transition_type,
1352 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431353 // If Telemetry is running, allow the URL load to proceed as if it's
1354 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491355 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181356 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361357 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181358 }
[email protected]47752982014-07-29 08:01:431359 }
[email protected]8bf1048012012-02-08 01:22:181360
[email protected]cf002332012-08-14 19:17:471361 // Checks based on params.load_type.
1362 switch (params.load_type) {
1363 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431364 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541365#if BUILDFLAG(IS_ANDROID)
1366 case LOAD_TYPE_PDF_ANDROID:
1367#endif
[email protected]cf002332012-08-14 19:17:471368 break;
1369 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261370 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boströmfc7ddc182024-10-31 19:37:211371 NOTREACHED() << "Data load must use data scheme.";
[email protected]cf002332012-08-14 19:17:471372 }
1373 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461374 }
[email protected]e47ae9472011-10-13 19:48:341375
[email protected]e47ae9472011-10-13 19:48:341376 // The user initiated a load, we don't need to reload anymore.
1377 needs_reload_ = false;
1378
Harkiran Bolariaba823e42021-05-21 18:30:361379 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441380}
1381
Charlie Reis4c53a962023-06-21 23:17:531382void NavigationControllerImpl::LoadOriginalRequestURL() {
1383 // If the original request URL is not valid, matches the current URL, or
1384 // involves POST data, then simply reload. The POST check avoids issues with
1385 // sending data to the wrong page.
1386 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1387 const GURL& original_request_url =
1388 GetLastCommittedEntry()->GetOriginalRequestURL();
1389 if (!original_request_url.is_valid() ||
1390 original_request_url == last_committed_url ||
1391 GetLastCommittedEntry()->GetHasPostData()) {
1392 Reload(ReloadType::NORMAL, true);
1393 return;
1394 }
1395
1396 // Otherwise, attempt to load the original request URL without any of the
1397 // other data from the current NavigationEntry, replacing the current entry.
1398 // Loading the original URL is useful in cases such as modifying the user
1399 // agent.
1400 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1401 std::make_unique<NavigationController::LoadURLParams>(
1402 original_request_url);
1403 load_params->should_replace_current_entry = true;
1404 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1405 LoadURLWithParams(*load_params.get());
1406}
1407
Mohamed Abdelhalim833de902019-09-16 17:41:451408bool NavigationControllerImpl::PendingEntryMatchesRequest(
1409 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191410 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451411 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191412}
1413
[email protected]d202a7c2012-01-04 07:53:471414bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321415 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071416 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331417 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441418 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251419 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561420 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131421 NavigationRequest* navigation_request) {
1422 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331423
1424 // Note: validation checks and renderer kills due to invalid commit messages
1425 // must happen before getting here, in
1426 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1427 // effects of the navigation have already occurred.
1428
[email protected]cd2e15742013-03-08 04:08:311429 is_initial_navigation_ = false;
1430
Wang Hui96ab1012022-10-11 02:05:491431 // Any pending request to repost a form submission is no longer valid, since a
1432 // different NavigationEntry is committing.
1433 pending_reload_ = ReloadType::NONE;
1434
[email protected]0e8db942008-09-24 21:21:481435 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431436 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451437 if (entry_replaced_by_post_commit_error_) {
1438 // Same document navigation events with a post-commit error should already
1439 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1440 // reaching here.
1441 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331442
Xinghui Lub9e86a352024-05-17 16:29:421443 if (pending_entry_) {
1444 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1445 // `pending_entry_` isn't pointing to the last committed entry.
1446 // Instead, all reload approaches (e.g., in `Reload` and
1447 // `LoadIfNecessary`) should attempt to load the
1448 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1449 // entry itself.
1450 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1451 << "Incorrectly reloading the post commit error page entry.";
1452 }
Xinghui Lue4e50be2024-05-15 21:46:001453
Rakina Zata Amnie2d31312022-11-18 03:38:451454 // Any commit while a post-commit error page is showing should put the
1455 // original entry back, replacing the error page's entry. This includes
1456 // reloads, where the original entry was used as the pending entry and
1457 // should now be at the correct index at commit time.
1458 entries_[last_committed_entry_index_] =
1459 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481460 }
Rakina Zata Amnie2d31312022-11-18 03:38:451461 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1462 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001463 // Must honor user agent overrides in the |navigation_request|, such as
1464 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1465 // result, besides comparing |pending_entry_|'s user agent against
1466 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1467 // agent against LastCommittedEntry's.
1468 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541469 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1470 (PendingEntryMatchesRequest(navigation_request) &&
1471 pending_entry_->GetIsOverridingUserAgent() !=
1472 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001473 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451474 }
[email protected]ecd9d8702008-08-28 22:10:171475
Dave Tapuskaa2ab4f252021-07-08 21:31:281476 bool is_main_frame_navigation = !rfh->GetParent();
1477
Alexander Timind2f2e4f22019-04-02 20:04:531478 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1479 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281480 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141481 // BackForwardCacheMetrics to be associated with the new navigation's
1482 // NavigationEntry, by either creating a new object or reusing the previous
1483 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281484 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211485 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141486 back_forward_cache_metrics = BackForwardCacheMetrics::
1487 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281488 GetLastCommittedEntry(), is_main_frame_navigation,
1489 params.document_sequence_number);
1490 }
Yuzu Saijo29f96ca92022-12-08 04:54:121491
Alexander Timind2f2e4f22019-04-02 20:04:531492 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281493 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451494 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1495 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531496 }
1497 }
1498
Rakina Zata Amnifd8370b2022-11-14 13:32:251499 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1500 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091501 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251502 details->did_replace_entry =
1503 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091504
fdegans9caf66a2015-07-30 21:10:421505 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111506 // except for restored entries. This should be true even if the current commit
1507 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291508 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481509 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081510 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111511
1512 // Only make changes based on the pending entry if the NavigationRequest
1513 // matches it. Otherwise, the pending entry may be for a different request
1514 // (e.g., if a slow history navigation is pending while an auto-subframe
1515 // commit occurs).
1516 if (PendingEntryMatchesRequest(navigation_request)) {
1517 // It is no longer necessary to consider the pending entry as restored.
1518 if (pending_entry_->IsRestored()) {
1519 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1520 was_restored = true;
1521 }
[email protected]e9ba4472008-09-14 15:42:431522
Charlie Reisf8cde712022-10-20 16:25:091523 // If the SiteInstance has changed from the matching pending entry, this
1524 // must be treated as a new navigation with replacement. Set the replacement
1525 // bit here and ClassifyNavigation will identify this case and return
1526 // NEW_ENTRY.
1527 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1528 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1529 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251530 // TODO(nasko,creis,rakina): Move this to happen before committing the
1531 // navigation. This is a bit complicated because we don't currently
1532 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091533 details->did_replace_entry = true;
1534 }
Nasko Oskovaee2f862018-06-15 00:05:521535 }
[email protected]bcd904482012-02-01 01:54:221536
[email protected]e9ba4472008-09-14 15:42:431537 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101538 NavigationType navigation_type =
1539 ClassifyNavigation(rfh, params, navigation_request);
1540 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451541
Rakina Zata Amnie2d31312022-11-18 03:38:451542 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451543 // Ensure that this navigation does not add a navigation entry, since
1544 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1545 // beyond the last committed one. Therefore, `should_replace_current_entry`
1546 // should be set, which replaces the current entry, or this should be a
1547 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251548 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331549 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451550 }
1551
Rakina Zata Amnie2d31312022-11-18 03:38:451552 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551553 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241554 // This is a subframe navigation on the initial empty document, which used
1555 // to not have a NavigationEntry to attach to. Now it can attach to the
1556 // initial NavigationEntry, and we must ensure that its NavigationEntry
1557 // will keep the "initial NavigationEntry" status and won't append a new
1558 // NavigationEntry (it should always do replacement instead).
1559 // See also https://crbug.com/1277414.
1560 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551561 // Subframe navigation on initial NavigationEntry must not append a new
1562 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1563 // means every subframe navigation that happens while we're on the initial
1564 // NavigationEntry will always reuse the existing NavigationEntry and
1565 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101566 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1567 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551568 // This is a navigation that modifies the initial NavigationEntry, either
1569 // for a replacement or a reload. The initial NavigationEntry should
1570 // retain its "initial NavigationEntry" status in this case.
1571 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241572 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251573 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1574 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241575 // This is a synchronous about:blank navigation on the main frame, which
1576 // used to not create a NavigationEntry when we have no NavigationEntry on
1577 // FrameTree creation. We now have the initial NavigationEntry and are on
1578 // the initial NavigationEntry. To preserve old behavior, we should still
1579 // keep the "initial" status for the new NavigationEntry that we will
1580 // create for this navigation, so that subframe navigations under the
1581 // synchronously committed about:blank document will never append new
1582 // NavigationEntry, and instead will just reuse the initial
1583 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1584 // See also https://crbug.com/1277414.
1585 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551586 }
1587 }
1588 DCHECK(!details->should_stay_as_initial_entry ||
1589 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201590
eugenebutee08663a2017-04-27 17:43:121591 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441592 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121593
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071594 details->is_prerender_activation =
1595 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241596 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1597 ->GetOutermostMainFrame()
1598 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071599
Peter Boströmd7592132019-01-30 04:50:311600 // Make sure we do not discard the pending entry for a different ongoing
1601 // navigation when a same document commit comes in unexpectedly from the
1602 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1603 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581604 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061605 bool keep_pending_entry =
1606 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101607 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061608 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311609
Miyoung Shin3299cbf2022-11-22 01:41:101610 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061611 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491612 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051613 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561614 previous_document_had_history_intervention_activation,
1615 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431616 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061617 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491618 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1619 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001620 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431621 break;
[email protected]8ff00d72012-10-23 19:12:211622 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471623 RendererDidNavigateNewSubframe(
1624 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561625 previous_document_had_history_intervention_activation,
1626 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431627 break;
[email protected]8ff00d72012-10-23 19:12:211628 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391629 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251630 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001631 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081632 // We don't send a notification about auto-subframe PageState during
1633 // UpdateStateForFrame, since it looks like nothing has changed. Send
1634 // it here at commit time instead.
1635 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431636 return false;
creis59d5a47cb2016-08-24 23:57:191637 }
[email protected]e9ba4472008-09-14 15:42:431638 break;
Aran Gilman37d11632019-10-08 23:07:151639 case NAVIGATION_TYPE_UNKNOWN:
Peter Boströmfc7ddc182024-10-31 19:37:211640 NOTREACHED();
[email protected]765b35502008-08-21 00:51:201641 }
1642
[email protected]688aa65c62012-09-28 04:32:221643 // At this point, we know that the navigation has just completed, so
1644 // record the time.
1645 //
1646 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261647 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331648 base::Time timestamp =
1649 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1650 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131651 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221652
Peter Boströmd7592132019-01-30 04:50:311653 // If we aren't keeping the pending entry, there shouldn't be one at this
1654 // point. Clear it again in case any error cases above forgot to do so.
1655 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1656 // been cleared instead of protecting against it.
1657 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551658 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141659
[email protected]e9ba4472008-09-14 15:42:431660 // All committed entries should have nonempty content state so WebKit doesn't
1661 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471662 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321663 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221664 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441665 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141666
Alexander Timind2f2e4f22019-04-02 20:04:531667 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1668 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281669 if (back_forward_cache_metrics &&
1670 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531671 active_entry->set_back_forward_cache_metrics(
1672 std::move(back_forward_cache_metrics));
1673 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281674
1675 // `back_forward_cache_metrics()` may return null as we do not record
1676 // back-forward cache metrics for navigations in non-primary frame trees.
1677 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581678 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141679 // These are both only available from details at this point, so we capture
1680 // them here.
1681 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101682 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141683 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1684 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281685 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1686 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321687 IsBackForwardCacheEnabled() &&
1688 rfh->delegate()->IsBackForwardCacheSupported() &&
1689 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281690 }
naskoc7533512016-05-06 17:01:121691
Charles Reisc0507202017-09-21 00:40:021692 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1693 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1694 // A mismatch can occur if the renderer lies or due to a unique name collision
1695 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121696 FrameNavigationEntry* frame_entry =
1697 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021698 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1699 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031700 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081701 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1702 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031703 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201704
1705 // Remember the bindings the renderer process has at this point, so that
1706 // we do not grant this entry additional bindings if we come back to it.
1707 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301708 }
[email protected]132e281a2012-07-31 18:32:441709
[email protected]97d8f0d2013-10-29 16:49:211710 // Once it is committed, we no longer need to track several pieces of state on
1711 // the entry.
naskoc7533512016-05-06 17:01:121712 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131713
[email protected]49bd30e62011-03-22 20:12:591714 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221715 // TODO(creis): This check won't pass for subframes until we create entries
1716 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001717 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421718 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591719
[email protected]e9ba4472008-09-14 15:42:431720 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001721 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001722 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311723 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531724
arthursonzogni7ddc6542021-04-09 09:16:501725 active_entry->SetIsOverridingUserAgent(
1726 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031727
[email protected]93f230e02011-06-01 14:40:001728 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291729
aelias100c9192017-01-13 00:01:431730 if (overriding_user_agent_changed)
1731 delegate_->UpdateOverridingUserAgent();
1732
creis03b48002015-11-04 00:54:561733 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1734 // one knows the latest NavigationEntry it is showing (whether it has
1735 // committed anything in this navigation or not). This allows things like
1736 // state and title updates from RenderFrames to apply to the latest relevant
1737 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381738 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031739 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381740 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431741
1742 if (navigation_request->IsPrerenderedPageActivation()) {
1743 BroadcastHistoryOffsetAndLength();
Alison Gale47d1537d2024-04-19 21:31:461744 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431745 // is activated. As a result, a "prerenderingchange" event listener sees the
1746 // history.length which is not updated yet. We should guarantee that
1747 // history's length and offset should be updated before a
1748 // "prerenderingchange" event listener runs. One possible approach is to use
1749 // the same IPC which "prerenderingchange" uses, and propagate history's
1750 // length and offset together with that.
1751 }
1752
[email protected]e9ba4472008-09-14 15:42:431753 return true;
initial.commit09911bf2008-07-26 23:55:291754}
1755
[email protected]8ff00d72012-10-23 19:12:211756NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321757 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101758 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241759 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591760 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511761 "ClassifyNavigation");
1762
avi7c6f35e2015-05-08 17:52:381763 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241764 // A new entry. We may or may not have a corresponding pending entry, and
1765 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001766 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491767 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061768 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381769 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241770 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511771 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381772 return NAVIGATION_TYPE_NEW_SUBFRAME;
1773 }
1774
Charlie Reisc0f17d2d2021-01-12 18:52:491775 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381776 DCHECK(!params.history_list_was_cleared);
1777
avi39c1edd32015-06-04 20:06:001778 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381779 // All manual subframes would be did_create_new_entry and handled above, so
1780 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081781 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1782 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381783 }
1784
Rakina Zata Amnif6950d552020-11-24 03:26:101785 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1786 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381787 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1788 // create a new page.
1789
Hayato Ito2ae49442021-07-02 02:59:251790 // This main frame navigation is not a history navigation (since
1791 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1792 // reload or a replacement navigation, which will modify the existing entry.
1793 //
Nasko Oskov332593c2018-08-16 17:21:341794 // TODO(nasko): With error page isolation, reloading an existing session
1795 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491796 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341797 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511798 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491799 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061800 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381801 }
1802
Charlie Reisf8cde712022-10-20 16:25:091803 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521804 // If the SiteInstance of the |pending_entry_| does not match the
1805 // SiteInstance that got committed, treat this as a new navigation with
1806 // replacement. This can happen if back/forward/reload encounters a server
1807 // redirect to a different site or an isolated error page gets successfully
1808 // reloaded into a different SiteInstance.
1809 if (pending_entry_->site_instance() &&
1810 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491811 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061812 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521813 }
creis77c9aa32015-09-25 19:59:421814
Nasko Oskovaee2f862018-06-15 00:05:521815 if (pending_entry_index_ == -1) {
1816 // In this case, we have a pending entry for a load of a new URL but Blink
1817 // didn't do a new navigation (params.did_create_new_entry). First check
1818 // to make sure Blink didn't treat a new cross-process navigation as
1819 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161820 // we must treat it as NEW rather than the converted reload case below,
1821 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451822 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161823 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061824 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521825 }
1826
1827 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161828 // We will create a pending entry, but NavigateWithoutEntry will convert
1829 // it to a reload since it's the same page and not create a new entry for
1830 // it. (The user doesn't want to have a new back/forward entry when they
1831 // do this.) Therefore we want to just ignore the pending entry and go
1832 // back to where we were (the "existing entry").
1833 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061834 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521835 }
avi7c6f35e2015-05-08 17:52:381836 }
1837
Rakina Zata Amni153d5702021-09-13 22:48:001838 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381839 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491840 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1841 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161842 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061843 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381844 }
1845
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121846 if (navigation_request->DidEncounterError() &&
1847 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101848 nav_entry_id == failed_pending_entry_id_) {
Charlie Reisb5f39cf2024-11-12 16:55:011849 // If the renderer was going to a pending entry that got cleared because of
1850 // an error, then the error page will replace the existing entry.
Nasko Oskovae49e292020-08-13 02:08:511851 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491852 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061853 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381854 }
1855
Charlie Reisc0f17d2d2021-01-12 18:52:491856 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101857 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511858 trace_return.traced_value()->SetInteger("existing_entry_index",
1859 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381860 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441861 // The renderer has committed a navigation to an entry that no longer
1862 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491863 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061864 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381865 }
1866
avi7c6f35e2015-05-08 17:52:381867 // Since we weeded out "new" navigations above, we know this is an existing
1868 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491869 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061870 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381871}
1872
Rakina Zata Amni3460d382021-10-29 00:43:371873void NavigationControllerImpl::UpdateNavigationEntryDetails(
1874 NavigationEntryImpl* entry,
1875 RenderFrameHostImpl* rfh,
1876 const mojom::DidCommitProvisionalLoadParams& params,
1877 NavigationRequest* request,
1878 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001879 bool is_new_entry,
1880 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371881 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171882 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371883 entry->AddOrUpdateFrameEntry(
1884 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571885 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371886 rfh->GetSiteInstance(), nullptr, params.url,
1887 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171888 Referrer(*params.referrer),
1889 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371890 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171891 request ? request->GetRedirectChain() : redirects, params.page_state,
1892 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371893 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171894 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211895 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171896 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371897
1898 if (rfh->GetParent()) {
1899 // Only modify the NavigationEntry for main frame navigations.
1900 return;
1901 }
1902 if (entry->update_virtual_url_with_url())
1903 UpdateVirtualURLToURL(entry, params.url);
1904 // Don't use the page type from the pending entry. Some interstitial page
1905 // may have set the type to interstitial. Once we commit, however, the page
1906 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171907 entry->set_page_type((request && request->DidEncounterError())
1908 ? PAGE_TYPE_ERROR
1909 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431910 if (commit_details && commit_details->should_stay_as_initial_entry) {
1911 // Retain the "initial NavigationEntry" status.
1912 if (request->IsSameDocument()) {
1913 // If this is for a same-document navigation, the NavigationEntry must be
1914 // reused and should already be marked as the initial NavigationEntry.
1915 DCHECK(entry->IsInitialEntry());
1916 } else {
1917 // If this is for a cross-document navigation, it can be caused by a
1918 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1919 // "for synchronous about:blank" in the latter case, and also when it is
1920 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1921 // is not for a synchronous about:blank commit.
1922 NavigationEntryImpl::InitialNavigationEntryState new_state =
1923 NavigationEntryImpl::InitialNavigationEntryState::
1924 kInitialNotForSynchronousAboutBlank;
1925 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1926 request->is_synchronous_renderer_commit()) {
1927 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1928 kInitialForSynchronousAboutBlank;
1929 }
1930 entry->set_initial_navigation_entry_state(new_state);
1931 }
1932 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1933 // Remove the "initial NavigationEntry" status.
1934 entry->set_initial_navigation_entry_state(
1935 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001936 }
Rakina Zata Amniddf10502022-01-15 02:56:551937
Rakina Zata Amni3460d382021-10-29 00:43:371938 if (is_new_entry) {
1939 // Some properties of the NavigationEntry are only set when the entry is
1940 // new (we aren't reusing it).
1941 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171942 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:401943 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:011944 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
1945 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:371946 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1947 } else {
1948 // We are reusing the NavigationEntry. The site instance will normally be
1949 // the same except for a few cases:
1950 // 1) session restore, when no site instance will be assigned or
1951 // 2) redirect, when the site instance is reset.
1952 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1953 entry->site_instance() == rfh->GetSiteInstance());
1954 }
1955}
1956
Rakina Zata Amniafd3c6582021-11-30 06:19:171957void NavigationControllerImpl::CreateInitialEntry() {
1958 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031959 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171960 auto params = mojom::DidCommitProvisionalLoadParams::New();
1961 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1962 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1963 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:401964 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:171965 params->http_status_code = 0;
1966 params->url_is_unreachable = false;
1967 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171968 params->post_id = -1;
1969 params->embedding_token = base::UnguessableToken::Create();
1970 params->navigation_token = base::UnguessableToken::Create();
1971 params->did_create_new_entry = true;
1972 params->origin = rfh->GetLastCommittedOrigin();
1973 params->should_update_history = true;
1974 params->item_sequence_number = 0;
1975 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151976 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171977 params->transition = is_in_fenced_frame_tree
1978 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1979 : ui::PAGE_TRANSITION_LINK;
1980 params->referrer = blink::mojom::Referrer::New();
1981
Rakina Zata Amniafd3c6582021-11-30 06:19:171982 auto new_entry = std::make_unique<NavigationEntryImpl>(
1983 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381984 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211985 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1986 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1987 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171988 UpdateNavigationEntryDetails(
1989 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001990 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1991 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171992
1993 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1994 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001995 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171996}
1997
Charlie Reisc0f17d2d2021-01-12 18:52:491998void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321999 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072000 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362001 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442002 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562003 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002004 NavigationRequest* request,
2005 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572006 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372007 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452008 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372009 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522010 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2011 initiator_base_url = request->common_params().initiator_base_url;
2012 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062013
creisf49dfc92016-07-26 17:05:182014 // First check if this is an in-page navigation. If so, clone the current
2015 // entry instead of looking at the pending entry, because the pending entry
2016 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452017 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302018 FrameNavigationEntry* previous_frame_entry =
2019 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452020 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482021 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572022 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082023 rfh->GetSiteInstance(), nullptr, params.url,
2024 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212025 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092026 request->GetRedirectChain(), params.page_state, params.method,
2027 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392028 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302029 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572030 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302031 // FrameNavigationEntry.
2032 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572033 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032034
creisf49dfc92016-07-26 17:05:182035 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032036 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522037 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2038 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572039 // TODO(jam): we had one report of this with a URL that was redirecting to
2040 // only tildes. Until we understand that better, don't copy the cert in
2041 // this case.
2042 new_entry->GetSSL() = SSLStatus();
2043 }
creisf49dfc92016-07-26 17:05:182044
Patrick Monette50e8bd82019-06-13 22:40:452045 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2046 // that |frame_entry| should now have a reference count of exactly 2: one
2047 // due to the local variable |frame_entry|, and another due to |new_entry|
2048 // also retaining one. This should never fail, because it's the main frame.
2049 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182050 }
2051
Harkiran Bolaria59290d62021-03-17 01:53:012052 // If this is an activation navigation from a prerendered page, transfer the
2053 // new entry from an entry already created and stored in the
2054 // NavigationRequest. |new_entry| will not have been set prior to this as
2055 // |is_same_document| is mutually exclusive with
2056 // |IsPrerenderedPageActivation|.
2057 if (request->IsPrerenderedPageActivation()) {
2058 DCHECK(!is_same_document);
2059 DCHECK(!new_entry);
2060 new_entry = request->TakePrerenderNavigationEntry();
2061 DCHECK(new_entry);
2062 }
2063
Charlie Reisc0f17d2d2021-01-12 18:52:492064 // Only make a copy of the pending entry if it is appropriate for the new
2065 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452066 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042067 // 1. The SiteInstance hasn't been assigned to something else.
2068 // 2. The pending entry was intended as a new entry, rather than being a
2069 // history navigation that was interrupted by an unrelated,
2070 // renderer-initiated navigation.
2071 // TODO(csharrison): Investigate whether we can remove some of the coarser
2072 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452073 if (!new_entry && PendingEntryMatchesRequest(request) &&
2074 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342075 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432076 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352077 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432078
Camille Lamy62b826012019-02-26 09:15:472079 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452080 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182081 }
2082
Charlie Reisc0f17d2d2021-01-12 18:52:492083 // For cross-document commits with no matching pending entry, create a new
2084 // entry.
creisf49dfc92016-07-26 17:05:182085 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062086 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072087 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212088 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582089 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452090 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172091 nullptr, // blob_url_loader_factory
2092 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242093
2094 // Find out whether the new entry needs to update its virtual URL on URL
2095 // change and set up the entry accordingly. This is needed to correctly
2096 // update the virtual URL when replaceState is called after a pushState.
2097 GURL url = params.url;
2098 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492099 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412100 // update the virtual URL based on the new URL. For example, this is needed
2101 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2102 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372103 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2104 &url, browser_context_, &needs_update);
2105 new_entry->set_update_virtual_url_with_url(needs_update);
2106
Camille Lamy62b826012019-02-26 09:15:472107 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452108 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432109 }
2110
Alison Gale770f3fc2024-04-27 00:39:582111 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2112 // set for prerendered contents, if any. This is because
2113 // prerendering/activation technically won't be creating a new document.
2114 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2115 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012116 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372117 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2118 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002119 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082120
Harkiran Bolaria59290d62021-03-17 01:53:012121 // history.pushState() is classified as a navigation to a new page, but sets
2122 // is_same_document to true. In this case, we already have the title and
2123 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452124 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012125 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2126 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2127 }
[email protected]3a868f212014-08-09 10:41:192128 }
[email protected]ff64b3e2014-05-31 04:07:332129
[email protected]60d6cca2013-04-30 08:47:132130 DCHECK(!params.history_list_was_cleared || !replace_entry);
2131 // The browser requested to clear the session history when it initiated the
2132 // navigation. Now we know that the renderer has updated its state accordingly
2133 // and it is safe to also clear the browser side history.
2134 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552135 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132136 entries_.clear();
2137 last_committed_entry_index_ = -1;
2138 }
2139
Nasko Oskovaee2f862018-06-15 00:05:522140 // If this is a new navigation with replacement and there is a
2141 // pending_entry_ which matches the navigation reported by the renderer
2142 // process, then it should be the one replaced, so update the
2143 // last_committed_entry_index_ to use it.
2144 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092145 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522146 last_committed_entry_index_ = pending_entry_index_;
2147 }
2148
Alexander Timine3ec4192020-04-20 16:39:402149 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562150 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402151 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052152
Yuzu Saijoa725585f2022-11-28 04:14:032153 // If this is a history navigation and the old entry has an existing
2154 // back/forward cache metrics object, keep using the old one so that the
2155 // reasons logged from the last time the page navigated gets preserved.
2156 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2157 request)) {
2158 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2159 // because some tests do not have a pending entry.
2160 NavigationEntryImpl* entry =
2161 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2162 if (entry && entry->back_forward_cache_metrics()) {
2163 scoped_refptr<BackForwardCacheMetrics> metrics =
2164 entry->TakeBackForwardCacheMetrics();
2165 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2166 }
2167 }
2168
Carlos IL42b416592019-10-07 23:10:362169 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312170 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152171 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432172}
2173
Charlie Reisc0f17d2d2021-01-12 18:52:492174void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322175 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072176 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362177 bool is_same_document,
jam48cea9082017-02-15 06:13:292178 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452179 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002180 bool keep_pending_entry,
2181 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562182 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2183 << "that a last committed entry exists.";
2184
[email protected]e9ba4472008-09-14 15:42:432185 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002186 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432187
Charlie Reis7e2cb6d2021-01-26 01:27:162188 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002189 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162190 // We're guaranteed to have a last committed entry if intended_as_new_entry
2191 // is true.
avicbdc4c12015-07-01 16:07:112192 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162193
2194 // If the NavigationRequest matches a new pending entry and is classified as
2195 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2196 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092197 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162198 // Note: The pending entry will usually have a real ReloadType here, but
2199 // it can still be ReloadType::NONE in cases that
2200 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2201
2202 // If we classified this correctly, the SiteInstance should not have
2203 // changed.
2204 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2205
2206 // For converted reloads, we assign the entry's unique ID to be that of
2207 // the new one. Since this is always the result of a user action, we want
2208 // to dismiss infobars, etc. like a regular user-initiated navigation.
2209 entry->set_unique_id(pending_entry_->GetUniqueID());
2210
2211 // The extra headers may have changed due to reloading with different
2212 // headers.
2213 entry->set_extra_headers(pending_entry_->extra_headers());
2214 }
2215 // Otherwise, this was intended as a new entry but the pending entry was
2216 // lost in the meantime and no new entry was created. We are stuck at the
2217 // last committed entry.
2218
2219 // Even if this is a converted reload from pressing enter in the omnibox,
2220 // the server could redirect, requiring an update to the SSL status. If this
2221 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452222 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162223 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472224 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452225 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162226 }
Rakina Zata Amnif6950d552020-11-24 03:26:102227 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112228 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102229 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162230
eugenebut604866f2017-05-10 21:35:362231 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452232 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362233 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2234 // this was a restored same document navigation entry, then it won't have
2235 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2236 // navigated it.
jam48cea9082017-02-15 06:13:292237 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522238 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2239 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292240 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2241 was_restored) {
2242 entry->GetSSL() = last_entry->GetSSL();
2243 }
2244 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452245 // In rapid back/forward navigations |request| sometimes won't have a cert
2246 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192247 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452248 if (request->GetSSLInfo().has_value() &&
2249 request->GetSSLInfo()->is_valid()) {
2250 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522251 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2252 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192253 entry->GetSSL() = SSLStatus();
2254 }
jam48cea9082017-02-15 06:13:292255 }
avicbdc4c12015-07-01 16:07:112256 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272257 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572258 // navigations that are EXISTING_ENTRY are same-document navigations that
2259 // result in replacement (e.g. history.replaceState(), location.replace(),
2260 // forced replacements for trivial session history contexts). For these
2261 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112262 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102263
Alison Gale81f4f2c72024-04-22 19:33:312264 // TODO(crbug.com/40532777): Set page transition type to
2265 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2266 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2267 // well as to fix the inconsistency with what we report to observers
2268 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102269
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572270 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102271
eugenebut604866f2017-05-10 21:35:362272 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452273 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362274 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472275 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452276 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112277 }
2278 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432279
Rakina Zata Amni3460d382021-10-29 00:43:372280 UpdateNavigationEntryDetails(entry, rfh, params, request,
2281 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002282 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302283
[email protected]5ccd4dc2012-10-24 02:28:142284 // The redirected to page should not inherit the favicon from the previous
2285 // page.
eugenebut604866f2017-05-10 21:35:362286 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482287 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142288
Charlie Reis951f43372023-05-05 00:30:072289 // Update the last committed index to reflect the committed entry. Do this
2290 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2291 // delegate sees the correct committed index when notified of navigation
2292 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2293 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212294 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072295
Peter Boströmd7592132019-01-30 04:50:312296 // We should also usually discard the pending entry if it corresponds to a
2297 // different navigation, since that one is now likely canceled. In rare
2298 // cases, we leave the pending entry for another navigation in place when we
2299 // know it is still ongoing, to avoid a flicker in the omnibox (see
2300 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432301 //
2302 // Note that we need to use the "internal" version since we don't want to
2303 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312304 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002305 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432306}
2307
[email protected]d202a7c2012-01-04 07:53:472308void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322309 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072310 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362311 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472312 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562313 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002314 NavigationRequest* request,
2315 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262316 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2317 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552318 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2319 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112320
[email protected]e9ba4472008-09-14 15:42:432321 // Manual subframe navigations just get the current entry cloned so the user
2322 // can go back or forward to it. The actual subframe information will be
2323 // stored in the page state for each of those entries. This happens out of
2324 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092325 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2326 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382327
Mikel Astizba9cf2fd2017-12-17 10:38:102328 // The DCHECK below documents the fact that we don't know of any situation
2329 // where |replace_entry| is true for subframe navigations. This simplifies
2330 // reasoning about the replacement struct for subframes (see
2331 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2332 DCHECK(!replace_entry);
2333
Patrick Monette50e8bd82019-06-13 22:40:452334 // This FrameNavigationEntry might not end up being used in the
2335 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372336 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452337 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372338 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522339 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2340 initiator_base_url = request->common_params().initiator_base_url;
2341 }
Nate Chapin63db0d12022-01-20 22:03:302342 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2343 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212344 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302345 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572346 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302347 if (is_same_document) {
2348 FrameNavigationEntry* previous_frame_entry =
2349 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572350 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302351 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572352 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302353 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572354 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302355 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572356 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302357 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572358 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302359 policy_container_policies->referrer_policy);
2360 }
2361
Patrick Monette50e8bd82019-06-13 22:40:452362 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482363 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572364 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082365 rfh->GetSiteInstance(), nullptr, params.url,
2366 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212367 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2368 request->GetRedirectChain(), params.page_state, params.method,
2369 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572370 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032371
creisce0ef3572017-01-26 17:53:082372 std::unique_ptr<NavigationEntryImpl> new_entry =
2373 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452374 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032375 frame_tree_->root());
creise062d542015-08-25 02:01:552376
Alexander Timine3ec4192020-04-20 16:39:402377 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562378 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402379 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472380
creisce0ef3572017-01-26 17:53:082381 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452382 // to replace, which can happen due to a unique name change. See
2383 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2384 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382385
Dave Tapuska87696ae2021-11-18 18:48:312386 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152387 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432388}
2389
[email protected]d202a7c2012-01-04 07:53:472390bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322391 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072392 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392393 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252394 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002395 NavigationRequest* request,
2396 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292397 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2398 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2399
[email protected]e9ba4472008-09-14 15:42:432400 // We're guaranteed to have a previously committed entry, and we now need to
2401 // handle navigation inside of a subframe in it without creating a new entry.
2402 DCHECK(GetLastCommittedEntry());
2403
creis913c63ce2016-07-16 19:52:522404 // For newly created subframes, we don't need to send a commit notification.
2405 // This is only necessary for history navigations in subframes.
2406 bool send_commit_notification = false;
2407
Rakina Zata Amnif6950d552020-11-24 03:26:102408 // If |nav_entry_id| is non-zero and matches an existing entry, this
2409 // is a history navigation. Update the last committed index accordingly. If
2410 // we don't recognize the |nav_entry_id|, it might be a recently
2411 // pruned entry. We'll handle it below.
2412 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2413 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472414 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062415 // Make sure that a subframe commit isn't changing the main frame's
2416 // origin. Otherwise the renderer process may be confused, leading to a
2417 // URL spoof. We can't check the path since that may change
2418 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572419 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2420 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242421 // We should use checks similar to RenderFrameHostImpl's
2422 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2423 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572424 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2425 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2426 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2427 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522428 current_top_url.DeprecatedGetOriginAsURL() !=
2429 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442430 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512431 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062432 }
creis3cdc3b02015-05-29 23:00:472433
creis913c63ce2016-07-16 19:52:522434 // We only need to discard the pending entry in this history navigation
2435 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062436 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002437 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522438
2439 // History navigations should send a commit notification.
2440 send_commit_notification = true;
avi98405c22015-05-21 20:47:062441 }
[email protected]e9ba4472008-09-14 15:42:432442 }
[email protected]f233e4232013-02-23 00:55:142443
creisce0ef3572017-01-26 17:53:082444 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2445 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372446 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2447 // exists), or we may want to clobber it and create a new one. We update in
2448 // cases where the corresponding FrameNavigationEntry is conceptually similar
2449 // to the document described by the commit params: same-document
2450 // navigations, history traversal to an existing entry, and reloads (including
2451 // a "soft reload" where we navigate to the same url without flagging it as a
2452 // reload). But in the case of a different document that is not logically
2453 // related to the committed FrameNavigationEntry's document (cross-document,
2454 // not same url, not a reload, not a history traversal), we replace rather
2455 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252456 //
Nate Chapin9f169072021-06-09 19:32:372457 // In the case where we update, the FrameNavigationEntry will potentially be
2458 // shared across multiple NavigationEntries, and any updates will be reflected
2459 // in all of those NavigationEntries. In the replace case, any existing
2460 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252461 //
2462 // When navigating away from the initial empty document, we also update rather
2463 // than replace. Either update or replace will overwrite the initial empty
2464 // document state for |last_committed|, but if the FrameNavigationEntry for
2465 // the initial empty document is shared across multiple NavigationEntries (due
2466 // to a navigation in another frame), we want to make sure we overwrite the
2467 // initial empty document state everywhere this FrameNavigationEntry is used,
2468 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452469 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372470 FrameNavigationEntry* last_committed_frame_entry =
2471 last_committed->GetFrameEntry(rfh->frame_tree_node());
2472 NavigationEntryImpl::UpdatePolicy update_policy =
2473 NavigationEntryImpl::UpdatePolicy::kUpdate;
2474 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312475 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372476 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252477 last_committed_frame_entry->url() != params.url &&
2478 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372479 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2480 }
2481
Rakina Zata Amni3460d382021-10-29 00:43:372482 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002483 update_policy, false /* is_new_entry */,
2484 commit_details);
creis625a0c7d2015-03-24 23:17:122485
creis913c63ce2016-07-16 19:52:522486 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432487}
2488
[email protected]d202a7c2012-01-04 07:53:472489int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232490 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032491 for (size_t i = 0; i < entries_.size(); ++i) {
2492 if (entries_[i].get() == entry)
2493 return i;
2494 }
2495 return -1;
[email protected]765b35502008-08-21 00:51:202496}
2497
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572498void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242499 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572500 NavigationControllerImpl* source =
2501 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572502 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382503 DCHECK_EQ(1, GetEntryCount());
2504 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472505 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172506 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572507
Francois Dorayeaace782017-06-21 16:37:242508 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442509 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572510 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572511
Fergal Dalya1d569972021-03-16 03:24:532512 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302513 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532514 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2515 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302516 }
[email protected]4e6419c2010-01-15 04:50:342517
Lukasz Anforowicz0de0f452020-12-02 19:57:152518 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572519}
2520
[email protected]79368982013-11-13 01:11:012521bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022522 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162523 if (last_committed_entry_index_ == -1)
2524 return false;
[email protected]9350602e2013-02-26 23:27:442525
[email protected]474f8512013-05-31 22:31:162526 // We cannot prune if there is a pending entry at an existing entry index.
2527 // It may not commit, so we have to keep the last committed entry, and thus
2528 // there is no sensible place to keep the pending entry. It is ok to have
2529 // a new pending entry, which can optionally commit as a new navigation.
2530 if (pending_entry_index_ != -1)
2531 return false;
2532
[email protected]474f8512013-05-31 22:31:162533 return true;
2534}
2535
[email protected]79368982013-11-13 01:11:012536void NavigationControllerImpl::PruneAllButLastCommitted() {
2537 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162538
avi2b177592014-12-10 02:08:022539 DCHECK_EQ(0, last_committed_entry_index_);
2540 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442541
Hayato Ito2c8c08d02021-06-23 03:38:432542 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442543}
2544
[email protected]79368982013-11-13 01:11:012545void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162546 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012547 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262548
Nate Chapin9eb16be72022-09-23 22:54:312549 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2550
[email protected]474f8512013-05-31 22:31:162551 // Erase all entries but the last committed entry. There may still be a
2552 // new pending entry after this.
2553 entries_.erase(entries_.begin(),
2554 entries_.begin() + last_committed_entry_index_);
2555 entries_.erase(entries_.begin() + 1, entries_.end());
2556 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262557}
2558
Christian Dullweber1af31e62018-02-22 11:49:482559void NavigationControllerImpl::DeleteNavigationEntries(
2560 const DeletionPredicate& deletionPredicate) {
2561 // It is up to callers to check the invariants before calling this.
2562 CHECK(CanPruneAllButLastCommitted());
2563 std::vector<int> delete_indices;
2564 for (size_t i = 0; i < entries_.size(); i++) {
2565 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572566 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482567 delete_indices.push_back(i);
2568 }
2569 }
2570 if (delete_indices.empty())
2571 return;
2572
2573 if (delete_indices.size() == GetEntryCount() - 1U) {
2574 PruneAllButLastCommitted();
2575 } else {
2576 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382577 for (const auto& index : base::Reversed(delete_indices)) {
2578 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482579 }
Hayato Ito2c8c08d02021-06-23 03:38:432580 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482581 }
2582 delegate()->NotifyNavigationEntriesDeleted();
2583}
2584
Carlos Caballero35ce710c2019-09-19 10:59:452585BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2586 return back_forward_cache_;
2587}
2588
William Liu055a3542023-04-02 17:21:192589NavigationEntryScreenshotCache*
2590NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212591 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262592 if (!nav_entry_screenshot_cache_ &&
2593 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192594 nav_entry_screenshot_cache_ =
2595 std::make_unique<NavigationEntryScreenshotCache>(
2596 BrowserContextImpl::From(browser_context_)
2597 ->GetNavigationEntryScreenshotManager()
2598 ->GetSafeRef(),
2599 this);
2600 }
2601 return nav_entry_screenshot_cache_.get();
2602}
2603
clamy987a3752018-05-03 17:36:262604void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2605 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2606 // progress, since this will cause a use-after-free. (We only allow this
2607 // when the tab is being destroyed for shutdown, since it won't return to
2608 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032609 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262610
2611 if (was_failure && pending_entry_) {
2612 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2613 } else {
2614 failed_pending_entry_id_ = 0;
2615 }
2616
2617 if (pending_entry_) {
2618 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332619 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262620 pending_entry_index_ = -1;
2621 pending_entry_ = nullptr;
2622 }
arthursonzogni66f711c2019-10-08 14:40:362623
2624 // Ensure any refs to the current pending entry are ignored if they get
2625 // deleted, by clearing the set of known refs. All future pending entries will
2626 // only be affected by new refs.
2627 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262628}
2629
2630void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2631 if (pending_entry_)
2632 pending_entry_->set_ssl_error(error);
2633}
2634
Xiaohan Wang7f8052e02022-01-14 18:44:282635#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422636// static
2637bool NavigationControllerImpl::ValidateDataURLAsString(
2638 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2639 if (!data_url_as_string)
2640 return false;
2641
2642 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2643 return false;
2644
2645 // The number of characters that is enough for validating a data: URI.
2646 // From the GURL's POV, the only important part here is scheme, it doesn't
2647 // check the actual content. Thus we can take only the prefix of the url, to
2648 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562649 constexpr size_t kDataUriPrefixMaxLen = 64;
2650 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2651 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422652 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2653 return false;
2654
2655 return true;
2656}
2657#endif
2658
Shivani Sharma194877032019-03-07 17:52:472659void NavigationControllerImpl::NotifyUserActivation() {
2660 // When a user activation occurs, ensure that all adjacent entries for the
2661 // same document clear their skippable bit, so that the history manipulation
2662 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012663 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172664 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012665 // If the value of CanGoBack changes as a result of making some entries
2666 // non-skippable, then we must let the delegate know to update its UI state.
2667 // See https://crbug.com/1477784.
2668 if (!can_go_back && CanGoBack()) {
2669 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2670 }
Shivani Sharma194877032019-03-07 17:52:472671}
2672
clamy987a3752018-05-03 17:36:262673bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2674 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332675 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2676 blink::LocalFrameToken initiator_frame_token,
2677 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262678 NavigationEntryImpl* entry =
2679 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2680 if (!entry)
2681 return false;
2682
2683 FrameNavigationEntry* frame_entry =
2684 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2685 if (!frame_entry)
2686 return false;
2687
Camille Lamy5193caa2018-10-12 11:59:422688 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572689 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232690 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332691 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2692 initiator_process_id);
clamyea99ea12018-05-28 13:54:232693
2694 if (!request)
2695 return false;
2696
arthursonzognif046d4a2019-12-12 19:08:102697 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412698
Rakina Zata Amni1c83b082023-02-08 01:09:002699 SCOPED_CRASH_KEY_STRING256(
2700 "Bug1400009", "req_url",
2701 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2702 SCOPED_CRASH_KEY_NUMBER(
2703 "Bug1400009", "nav_entry_si",
2704 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2705 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2706 frame_entry->site_instance()
2707 ? ((int)frame_entry->site_instance()->GetId())
2708 : -1);
2709 bool has_sig =
2710 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2711 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2712 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2713 has_sig ? (!!frame_tree_->GetRenderViewHost(
2714 frame_entry->site_instance()->group()))
2715 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052716 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2717 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232718
2719 return true;
clamy987a3752018-05-03 17:36:262720}
2721
Tsuyoshi Horo52fd08e2020-07-07 07:03:452722bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2723 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2724 if (!entry)
2725 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432726
2727 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2728 // We should never navigate to an existing initial NavigationEntry that is
2729 // the initial NavigationEntry for the initial empty document that hasn't
2730 // been overridden by the synchronous about:blank commit, to preserve
2731 // legacy behavior where trying to reload when the main frame is on the
2732 // initial empty document won't result in a navigation. See also
2733 // https://crbug.com/1277414.
2734 return false;
2735 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452736 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2737 if (!frame_entry)
2738 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142739 ReloadType reload_type = ReloadType::NORMAL;
2740 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452741 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142742 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452743 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432744 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372745 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332746 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452747 if (!request)
2748 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052749 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452750 return true;
2751}
2752
clamy987a3752018-05-03 17:36:262753void NavigationControllerImpl::NavigateFromFrameProxy(
2754 RenderFrameHostImpl* render_frame_host,
2755 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022756 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452757 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372758 const std::optional<url::Origin>& initiator_origin,
2759 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262760 bool is_renderer_initiated,
2761 SiteInstance* source_site_instance,
2762 const Referrer& referrer,
2763 ui::PageTransition page_transition,
2764 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252765 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262766 const std::string& method,
2767 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092768 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142769 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212770 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502771 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372772 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292773 blink::mojom::NavigationInitiatorActivationAndAdStatus
2774 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222775 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492776 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462777 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452778 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582779 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032780 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342781 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372782 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582783 if (is_renderer_initiated)
2784 DCHECK(initiator_origin.has_value());
2785
clamy987a3752018-05-03 17:36:262786 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582787
Rakina Zata Amni2322f4f82022-01-24 13:24:242788 // Don't allow an entry replacement if there is no entry to replace.
2789 // http://crbug.com/457149
2790 if (GetEntryCount() == 0)
2791 should_replace_current_entry = false;
2792
clamy987a3752018-05-03 17:36:262793 // Create a NavigationEntry for the transfer, without making it the pending
2794 // entry. Subframe transfers should have a clone of the last committed entry
2795 // with a FrameNavigationEntry for the target frame. Main frame transfers
2796 // should have a new NavigationEntry.
2797 // TODO(creis): Make this unnecessary by creating (and validating) the params
2798 // directly, passing them to the destination RenderFrameHost. See
2799 // https://crbug.com/536906.
2800 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262801 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262802 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452803 DCHECK(GetLastCommittedEntry());
2804 entry = GetLastCommittedEntry()->Clone();
2805 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172806 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2807 // Renderer-initiated navigation that target a remote frame are currently
2808 // classified as browser-initiated when this one has already navigated.
2809 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372810 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2811 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2812 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2813 // same-document navigation), they will still be present in the
2814 // committed NavigationEntry that will be referenced to construct the new
2815 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262816 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082817 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582818 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372819 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212820 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152821 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262822 } else {
2823 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172824 // If `node` is the outermost main frame, it rewrites a virtual url in order
2825 // to adjust the original input url if needed. For inner frames such as
2826 // fenced frames or subframes, they don't rewrite urls as the urls are not
2827 // input urls by users.
2828 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372829 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322830 if (source_site_instance && source_site_instance->HasProcess()) {
2831 source_process_site_url =
2832 source_site_instance->GetProcess()->GetProcessLock().site_url();
2833 }
clamy987a3752018-05-03 17:36:262834 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212835 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322836 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212837 extra_headers, browser_context_, blob_url_loader_factory,
2838 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262839 entry->root_node()->frame_entry->set_source_site_instance(
2840 static_cast<SiteInstanceImpl*>(source_site_instance));
2841 entry->root_node()->frame_entry->set_method(method);
2842 }
clamy987a3752018-05-03 17:36:262843
Camille Lamy5193caa2018-10-12 11:59:422844 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452845 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262846 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422847 override_user_agent = true;
clamy987a3752018-05-03 17:36:262848 }
2849 // TODO(creis): Set user gesture and intent received timestamp on Android.
2850
2851 // We may not have successfully added the FrameNavigationEntry to |entry|
2852 // above (per https://crbug.com/608402), in which case we create it from
2853 // scratch. This works because we do not depend on |frame_entry| being inside
2854 // |entry| during NavigateToEntry. This will go away when we shortcut this
2855 // further in https://crbug.com/536906.
2856 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2857 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452858 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082859 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582860 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372861 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212862 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152863 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572864 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262865 }
2866
Camille Lamy5193caa2018-10-12 11:59:422867 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022868 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452869 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292870 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212871 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422872 params.source_site_instance = source_site_instance;
2873 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2874 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032875 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422876 params.referrer = referrer;
2877 /* params.redirect_chain: skip */
2878 params.extra_headers = extra_headers;
2879 params.is_renderer_initiated = is_renderer_initiated;
2880 params.override_user_agent = UA_OVERRIDE_INHERIT;
2881 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542882 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422883 /* params.data_url_as_string: skip */
2884 params.post_data = post_body;
2885 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582886 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422887 /* params.frame_name: skip */
2888 // TODO(clamy): See if user gesture should be propagated to this function.
2889 params.has_user_gesture = false;
2890 params.should_clear_history_list = false;
2891 params.started_from_context_menu = false;
2892 /* params.navigation_ui_data: skip */
2893 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222894 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542895 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212896 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412897 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502898 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292899 params.initiator_activation_and_ad_status =
2900 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032901 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422902
2903 std::unique_ptr<NavigationRequest> request =
2904 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032905 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142906 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392907 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492908 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582909 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:342910 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232911
2912 if (!request)
2913 return;
2914
Garrett Tanzerbb8db412022-09-27 21:59:462915 // Force the navigation to take place in a new browsing instance.
2916 // This is used by _unfencedTop in fenced frames to ensure that navigations
2917 // leaving the fenced context create a new browsing instance.
2918 if (force_new_browsing_instance) {
2919 request->coop_status().ForceBrowsingInstanceSwap();
2920 }
2921
Arthur Hemery948742762019-09-18 10:06:242922 // At this stage we are proceeding with this navigation. If this was renderer
2923 // initiated with user gesture, we need to make sure we clear up potential
2924 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2925 DiscardNonCommittedEntries();
2926
Lukasz Anforowicz9ee83c272020-12-01 20:14:052927 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262928}
2929
[email protected]d1198fd2012-08-13 22:50:192930void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252931 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212932 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192933 if (!session_storage_namespace)
2934 return;
2935
2936 // We can't overwrite an existing SessionStorage without violating spec.
2937 // Attempts to do so may give a tab access to another tab's session storage
2938 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152939 bool successful_insert =
2940 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252941 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052942 static_cast<SessionStorageNamespaceImpl*>(
2943 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302944 .second;
2945 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192946}
2947
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572948bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452949 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032950 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462951}
2952
Aran Gilman37d11632019-10-08 23:07:152953SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252954 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302955 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252956 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032957 DOMStorageContextWrapper* context_wrapper =
2958 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2959
2960 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252961 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032962 if (it != session_storage_namespace_map_.end()) {
2963 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152964 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2965 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472966
michaelnbacbcbd2016-02-09 00:32:032967 return it->second.get();
2968 }
2969
2970 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102971 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2972 SessionStorageNamespaceImpl::Create(context_wrapper);
2973 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2974 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252975 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102976 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302977
Daniel Murphy31bbb8b12018-02-07 21:44:102978 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302979}
2980
2981SessionStorageNamespace*
2982NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252983 return GetSessionStorageNamespace(
2984 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302985}
2986
2987const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572988NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302989 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552990}
[email protected]d202a7c2012-01-04 07:53:472991
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572992bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562993 return needs_reload_;
2994}
[email protected]a26023822011-12-29 00:23:552995
[email protected]46bb5e9c2013-10-03 22:16:472996void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412997 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2998}
2999
3000void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473001 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413002 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543003
3004 if (last_committed_entry_index_ != -1) {
3005 entries_[last_committed_entry_index_]->SetTransitionType(
3006 ui::PAGE_TRANSITION_RELOAD);
3007 }
[email protected]46bb5e9c2013-10-03 22:16:473008}
3009
[email protected]d202a7c2012-01-04 07:53:473010void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573011 DCHECK_LT(index, GetEntryCount());
3012 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313013 DiscardNonCommittedEntries();
3014
Nate Chapin9eb16be72022-09-23 22:54:313015 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313016 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123017 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313018 last_committed_entry_index_--;
3019}
3020
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573021NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273022 // If there is no pending_entry_, there should be no pending_entry_index_.
3023 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3024
3025 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363026 // at that index. An exception is while a reload of a post commit error page
3027 // is ongoing; in that case pending entry will point to the entry replaced
3028 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273029 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363030 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3031 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273032
[email protected]022af742011-12-28 18:37:253033 return pending_entry_;
3034}
3035
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573036int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273037 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273038 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553039 return pending_entry_index_;
3040}
3041
avi25764702015-06-23 15:43:373042void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573043 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363044 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313045 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003046 bool in_fenced_frame_tree,
3047 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313048 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3049 // set because:
3050 // 1) They don't influence the history of the outer page.
3051 // 2) They are always replace only navigation (there is always only one entry
3052 // in their history stack).
3053 // 3) Are not top level navigations and appear similar to iframes.
3054 // Navigations of the fenced frame might create a new NavigationEntry, which
3055 // will call this function. Non fenced frame navigations will never have
3056 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3057 // InsertOrReplaceEntry.
3058 DCHECK_EQ(in_fenced_frame_tree,
3059 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3060 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203061
avi5cad4912015-06-19 05:25:443062 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3063 // need to keep continuity with the pending entry, so copy the pending entry's
3064 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3065 // then the renderer navigated on its own, independent of the pending entry,
3066 // so don't copy anything.
3067 if (pending_entry_ && pending_entry_index_ == -1)
3068 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203069
Rakina Zata Amnia4e27222021-12-22 01:05:003070 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203071
creisee17e932015-07-17 17:56:223072 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453073 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103074 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573075 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363076 // If the new entry is a post-commit error page, we store the current last
3077 // committed entry to the side so that we can put it back when navigating
3078 // away from the error.
3079 if (was_post_commit_error) {
3080 DCHECK(!entry_replaced_by_post_commit_error_);
3081 entry_replaced_by_post_commit_error_ =
3082 std::move(entries_[last_committed_entry_index_]);
3083 }
dcheng36b6aec92015-12-26 06:16:363084 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223085 return;
3086 }
[email protected]765b35502008-08-21 00:51:203087
creis37979a62015-08-04 19:48:183088 // We shouldn't see replace == true when there's no committed entries.
3089 DCHECK(!replace);
3090
Michael Thiessen9b14d512019-09-23 21:19:473091 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203092
Shivani Sharmad8c8d652019-02-13 17:27:573093 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203094
dcheng36b6aec92015-12-26 06:16:363095 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203096 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293097}
3098
Shivani Sharmad8c8d652019-02-13 17:27:573099void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163100 if (entries_.size() < max_entry_count())
3101 return;
3102
3103 DCHECK_EQ(max_entry_count(), entries_.size());
3104 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573105 CHECK_EQ(pending_entry_index_, -1);
3106
3107 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423108 // Retrieve the oldest skippable entry.
3109 for (; index < GetEntryCount(); index++) {
3110 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3111 break;
Shivani Sharmad8c8d652019-02-13 17:27:573112 }
3113
3114 // If there is no skippable entry or if it is the last committed entry then
3115 // fall back to pruning the oldest entry. It is not safe to prune the last
3116 // committed entry.
3117 if (index == GetEntryCount() || index == last_committed_entry_index_)
3118 index = 0;
3119
3120 bool should_succeed = RemoveEntryAtIndex(index);
3121 DCHECK_EQ(true, should_succeed);
3122
3123 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253124}
3125
William Liu62ae26c2024-08-08 14:28:163126std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273127NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163128 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203129 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373130 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133131 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203132 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503133 TRACE_EVENT0("navigation",
3134 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273135 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023136 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363137 if (pending_entry_index_ != -1) {
3138 // The pending entry may not be in entries_ if a post-commit error page is
3139 // showing.
3140 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3141 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3142 }
Gyuyoung Kim107c2a02021-04-13 01:49:303143 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573144 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013145 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033146 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573147 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133148 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3149 // the same as the top level frame being navigated.
3150 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373151 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133152 }
Arthur Sonzogni620cec62018-12-13 13:08:573153
[email protected]83c2e232011-10-07 21:36:463154 // If we were navigating to a slow-to-commit page, and the user performs
3155 // a session history navigation to the last committed page, RenderViewHost
3156 // will force the throbber to start, but WebKit will essentially ignore the
3157 // navigation, and won't send a message to stop the throbber. To prevent this
3158 // from happening, we drop the navigation here and stop the slow-to-commit
3159 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023160 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083161 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273162 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033163 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123164
[email protected]83c2e232011-10-07 21:36:463165 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163166 return {};
[email protected]83c2e232011-10-07 21:36:463167 }
3168
Arthur Sonzognic686e8f2024-01-11 08:36:373169 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333170 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3171 if (initiator_rfh) {
3172 initiator_frame_token = initiator_rfh->GetFrameToken();
Emily Andrewsd15fd762024-12-10 20:41:543173 initiator_process_id = initiator_rfh->GetProcess()->GetDeprecatedID();
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333174 DCHECK(initiator_frame_token);
3175 }
3176
creisce0ef3572017-01-26 17:53:083177 // Compare FrameNavigationEntries to see which frames in the tree need to be
3178 // navigated.
clamy3cb9bea92018-07-10 12:42:023179 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3180 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333181 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3182 initiator_process_id, soft_navigation_heuristics_task_id,
3183 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303184
3185 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573186 // We were unable to match any frames to navigate. This can happen if a
3187 // history navigation targets a subframe that no longer exists
3188 // (https://crbug.com/705550). In this case, we need to update the current
3189 // history entry to the pending one but keep the main document loaded. We
3190 // also need to ensure that observers are informed about the updated
3191 // current history entry (e.g., for greying out back/forward buttons), and
3192 // that renderer processes update their history offsets. The easiest way
3193 // to do all that is to schedule a "redundant" same-document navigation in
3194 // the main frame.
3195 //
3196 // Note that we don't want to remove this history entry, as it might still
3197 // be valid later, since a frame that it's targeting may be recreated.
3198 //
3199 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3200 // need to repeat history navigations until finding the one that works.
3201 // Consider changing this behavior to keep looking for the first valid
3202 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023203 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423204 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573205 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573206 ReloadType::NONE /* reload_type */,
3207 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433208 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333209 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023210 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573211 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023212 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163213 return {};
clamy3cb9bea92018-07-10 12:42:023214 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573215 same_document_loads.push_back(std::move(navigation_request));
3216
3217 // Sanity check that we never take this branch for any kinds of reloads,
3218 // as those should've queued a different-document load in the main frame.
3219 DCHECK(!is_forced_reload);
3220 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303221 }
3222
Nate Chapinbf682fa32022-09-26 22:41:203223 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163224 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203225 if (initiator_rfh && initiator_rfh->IsSandboxed(
3226 network::mojom::WebSandboxFlags::kTopNavigation)) {
3227 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3228 initiator_rfh, same_document_loads) &&
3229 DoesSandboxNavigationStayWithinSubtree(
3230 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503231 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163232 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203233 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3234 initiator_rfh,
3235 navigates_inside_tree
3236 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3237 : blink::mojom::WebFeature::
3238 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523239
3240 // If the navigation occurred outside the tree discard it because
3241 // the sandboxed frame didn't have permission to navigate outside
3242 // its tree. If it is possible that the navigation is both inside and
3243 // outside the frame tree and we discard it entirely because we don't
3244 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143245 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203246 // If a |navigation_api_key| was provided, this navigation originated from
3247 // the navigation API. Notify the renderer that the navigation was
3248 // cancelled so the navigation API can fire an error event and reject the
3249 // relevant promise.
3250 if (navigation_api_key) {
3251 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3252 *navigation_api_key,
3253 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3254 }
Dave Tapuska855c1e12019-08-23 20:45:523255 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133256
3257 for (auto& unused_request : same_document_loads) {
3258 unused_request->set_navigation_discard_reason(
3259 NavigationDiscardReason::kNeverStarted);
3260 }
3261 for (auto& unused_request : different_document_loads) {
3262 unused_request->set_navigation_discard_reason(
3263 NavigationDiscardReason::kNeverStarted);
3264 }
William Liu62ae26c2024-08-08 14:28:163265 return {};
Dave Tapuska855c1e12019-08-23 20:45:523266 }
Dave Tapuska8bfd84c2019-03-26 20:47:163267 }
3268
Nate Chapin6c43c022023-02-13 23:32:423269 // If it is possible that this traverse may involve a same-document navigation
3270 // in the initiator and there is a Navigation API key involved, then we may
3271 // need to notify the initiator if it fails. (The early returns above either
3272 // do not involve these cases or already notify the initiator.)
3273 // The event only needs to fire for the initiator, and only if the initiator
3274 // itself is performing a same-document navigation (because the event will not
3275 // fire if it navigates cross-document).
3276 if (navigation_api_key) {
3277 for (auto& item : same_document_loads) {
3278 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3279 item->set_pending_navigation_api_key(*navigation_api_key);
3280 break;
3281 }
3282 }
3283 }
3284
Carlos Caballero539a421c2020-07-06 10:25:573285 // BackForwardCache:
3286 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563287 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573288 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3289 DCHECK_EQ(reload_type, ReloadType::NONE);
3290 auto navigation_request = CreateNavigationRequestFromEntry(
3291 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3292 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333293 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3294 initiator_process_id);
William Liuec04e382024-05-23 18:03:273295 base::WeakPtr<NavigationRequest> request = navigation_request->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053296 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Rakina Zata Amni58681c62024-06-25 06:32:133297
3298 for (auto& unused_request : same_document_loads) {
3299 unused_request->set_navigation_discard_reason(
3300 NavigationDiscardReason::kNeverStarted);
3301 }
3302 for (auto& unused_request : different_document_loads) {
3303 unused_request->set_navigation_discard_reason(
3304 NavigationDiscardReason::kNeverStarted);
3305 }
3306
William Liu62ae26c2024-08-08 14:28:163307 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_request;
3308 if (request) {
3309 bf_cache_request.push_back(std::move(request));
3310 }
3311 return bf_cache_request;
Carlos Caballero539a421c2020-07-06 10:25:573312 }
3313
3314 // History navigation might try to reuse a specific BrowsingInstance, already
3315 // used by a page in the cache. To avoid having two different main frames that
3316 // live in the same BrowsingInstance, evict the all pages with this
3317 // BrowsingInstance from the cache.
3318 //
3319 // For example, take the following scenario:
3320 //
3321 // A1 = Some page on a.com
3322 // A2 = Some other page on a.com
3323 // B3 = An uncacheable page on b.com
3324 //
3325 // Then the following navigations occur:
3326 // A1->A2->B3->A1
3327 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3328 // take its place) and A1 will be created in the same BrowsingInstance (and
3329 // SiteInstance), as A2.
3330 //
3331 // If we didn't do anything, both A1 and A2 would remain alive in the same
3332 // BrowsingInstance/SiteInstance, which is unsupported by
3333 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3334 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483335 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3336 pending_entry_->site_instance()
3337 ? pending_entry_->site_instance()->GetId().value()
3338 : -1);
3339 SCOPED_CRASH_KEY_NUMBER(
3340 "rvh_double", "pending_entry_bi",
3341 pending_entry_->site_instance()
3342 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3343 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573344 if (pending_entry_->site_instance()) {
3345 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3346 pending_entry_->site_instance());
3347 }
3348
Rakina Zata Amnid605d462022-06-01 10:17:033349 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3350 pending_entry_ && pending_entry_->IsRestored());
3351 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3352 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3353 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3354 pending_entry_index_);
3355 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3356 last_committed_entry_index_);
3357 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3358 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3359 pending_entry_ && pending_entry_->IsInitialEntry());
3360 SCOPED_CRASH_KEY_BOOL(
3361 "nav_reentrancy", "pending_entry_initial2",
3362 pending_entry_ &&
3363 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3364 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3365 IsInitialNavigation());
3366 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3367 IsInitialBlankNavigation());
3368 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3369 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3370 (int)pending_reload_);
3371
clamy3cb9bea92018-07-10 12:42:023372 // This call does not support re-entrancy. See http://crbug.com/347742.
3373 CHECK(!in_navigate_to_pending_entry_);
3374 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303375
Rakina Zata Amnid605d462022-06-01 10:17:033376 // If the navigation-reentrancy is caused by calling
3377 // NavigateToExistingPendingEntry twice, this will note the previous call's
3378 // pending entry's ID.
3379 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3380 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3381
arthursonzogni66f711c2019-10-08 14:40:363382 // It is not possible to delete the pending NavigationEntry while navigating
3383 // to it. Grab a reference to delay potential deletion until the end of this
3384 // function.
3385 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3386
Nate Chapin154b14b2023-02-17 18:28:163387 // If there is a main-frame same-document history navigation, we may defer
3388 // the subframe history navigations in order to give JS in the main frame the
3389 // opportunity to cancel the entire traverse via the navigate event. In that
3390 // case, we need to stash the main frame request's navigation token on the
3391 // subframes, so they can look up the main frame request and defer themselves
3392 // until it completes.
3393 if (!same_document_loads.empty() &&
3394 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3395 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3396 // The token will only be returned in cases where deferring the navigation
3397 // is necessary.
3398 if (auto main_frame_same_document_token =
3399 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3400 for (auto& item : same_document_loads) {
3401 if (item.get() != main_frame_request) {
3402 item->set_main_frame_same_document_history_token(
3403 main_frame_same_document_token);
3404 }
3405 }
3406 for (auto& item : different_document_loads) {
3407 item->set_main_frame_same_document_history_token(
3408 main_frame_same_document_token);
3409 }
3410 }
3411 }
3412
William Liu122754942024-01-18 22:34:393413 if (!initiator_rfh) {
3414 // A browser-initiated navigation won't have a `initiator_rfh`.
3415 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3416 different_document_loads, same_document_loads);
3417 }
3418
William Liu62ae26c2024-08-08 14:28:163419 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3420 all_requests.reserve(same_document_loads.size() +
3421 different_document_loads.size());
3422 bool seen_primary_main_frame_request = false;
3423
creis4e2ecb72015-06-20 00:46:303424 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023425 for (auto& item : same_document_loads) {
3426 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273427 // The request could be destroyed before `navigator().Navigate()` returns.
3428 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053429 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163430 if (request) {
3431 // Can only have one primary main frame request.
3432 CHECK(!seen_primary_main_frame_request ||
3433 !request->IsInPrimaryMainFrame());
3434 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3435 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273436 }
creis4e2ecb72015-06-20 00:46:303437 }
clamy3cb9bea92018-07-10 12:42:023438 for (auto& item : different_document_loads) {
3439 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273440 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053441 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163442 if (request) {
3443 // Can only have one primary main frame request.
3444 CHECK(!seen_primary_main_frame_request ||
3445 !request->IsInPrimaryMainFrame());
3446 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3447 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273448 }
creis4e2ecb72015-06-20 00:46:303449 }
clamy3cb9bea92018-07-10 12:42:023450
3451 in_navigate_to_pending_entry_ = false;
William Liuec04e382024-05-23 18:03:273452
William Liu62ae26c2024-08-08 14:28:163453 return all_requests;
creis4e2ecb72015-06-20 00:46:303454}
3455
Alex Moshchuk3a4e77a2020-05-29 21:32:573456NavigationControllerImpl::HistoryNavigationAction
3457NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303458 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573459 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423460 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583461 // Only active and prerendered documents are allowed to navigate in their
3462 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423463 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013464 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583465 // - If the document is in pending deletion, the browser already committed
3466 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3467 // - If the document is in back-forward cache, it's not allowed to navigate
3468 // as it should remain frozen. Ignore the request and evict the document
3469 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423470 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583471 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423472 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113473 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3474 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423475 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113476 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423477 }
arthursonzogni03f76152019-02-12 10:35:203478
Alex Moshchuk3a4e77a2020-05-29 21:32:573479 // Reloads should result in a different-document load. Note that reloads may
3480 // also happen via the |needs_reload_| mechanism where the reload_type is
3481 // NONE, so detect this by comparing whether we're going to the same
3482 // entry that we're currently on. Similarly to above, only main frames
3483 // should reach this. Note that subframes support reloads, but that's done
3484 // via a different path that doesn't involve FindFramesToNavigate (see
3485 // RenderFrameHost::Reload()).
3486 if (reload_type != ReloadType::NONE ||
3487 pending_entry_index_ == last_committed_entry_index_) {
3488 DCHECK(frame->IsMainFrame());
3489 return HistoryNavigationAction::kDifferentDocument;
3490 }
3491
Alex Moshchuk47d1a4bd2020-06-01 22:15:343492 // If there is no new FrameNavigationEntry for the frame, ignore the
3493 // load. For example, this may happen when going back to an entry before a
3494 // frame was created. Suppose we commit a same-document navigation that also
3495 // results in adding a new subframe somewhere in the tree. If we go back,
3496 // the new subframe will be missing a FrameNavigationEntry in the previous
3497 // NavigationEntry, but we shouldn't delete or change what's loaded in
3498 // it.
3499 //
Alex Moshchuke65c39272020-06-03 17:55:373500 // Note that in this case, there is no need to keep looking for navigations
3501 // in subframes, which would be missing FrameNavigationEntries as well.
3502 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343503 // It's important to check this before checking |old_item| below, since both
3504 // might be null, and in that case we still shouldn't change what's loaded in
3505 // this frame. Note that scheduling any loads assumes that |new_item| is
3506 // non-null. See https://crbug.com/1088354.
3507 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3508 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373509 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343510
Charlie Reisa474fb62022-03-17 02:31:363511 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3512 // which history item it is currently on, since this may be different than the
3513 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3514 // (e.g., if a history navigation is targeting multiple frames and only some
3515 // have committed so far).
creis4e2ecb72015-06-20 00:46:303516 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363517 frame->current_frame_host()->last_committed_frame_entry();
3518 if (!old_item) {
3519 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3520 // fall back to the last committed NavigationEntry's record for this frame.
3521 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583522 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363523 // accurate FrameNavigationEntry and eliminate this case.
3524 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3525 }
3526 // If neither approach finds a FrameNavigationEntry, schedule a
3527 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583528 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573529 if (!old_item)
3530 return HistoryNavigationAction::kDifferentDocument;
3531
Alex Moshchuk3a4e77a2020-05-29 21:32:573532 // If the new item is not in the same SiteInstance, schedule a
3533 // different-document load. Newly restored items may not have a SiteInstance
3534 // yet, in which case it will be assigned on first commit.
3535 if (new_item->site_instance() &&
3536 new_item->site_instance() != old_item->site_instance())
3537 return HistoryNavigationAction::kDifferentDocument;
3538
Charlie Reis71e4ae32025-01-29 21:37:573539 // If the origins of the new and old items are both present but don't match,
3540 // schedule a different document load even if the document sequence numbers
3541 // somehow match.
3542 // TODO(crbug.com/40051596): Also handle session restore cases that lack a
3543 // committed origin on `new_item`, and update the Blink DSN computation to
3544 // avoid a cross-origin DSN match when possible.
3545 if (new_item->committed_origin().has_value() &&
3546 old_item->committed_origin().has_value() &&
3547 !new_item->committed_origin()->IsSameOriginWith(
3548 old_item->committed_origin().value())) {
3549 return HistoryNavigationAction::kDifferentDocument;
3550 }
3551
Alex Moshchuk3a4e77a2020-05-29 21:32:573552 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313553 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3554 // that we do this even if the history navigation would not be modifying this
3555 // frame were it live.
3556 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573557 return HistoryNavigationAction::kDifferentDocument;
3558
3559 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313560 // Starting a navigation after a crash early-promotes the speculative
3561 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3562 // committed yet, so we can not possibly perform a same-document history
3563 // navigation. The frame would need to be reloaded with a cross-document
3564 // navigation.
3565 if (!frame->current_frame_host()->has_committed_any_navigation())
3566 return HistoryNavigationAction::kDifferentDocument;
3567
creis54131692016-08-12 18:32:253568 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493569 // sequence number but different item sequence number.
3570 if (new_item->document_sequence_number() ==
3571 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573572 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493573 }
avib48cb312016-05-05 21:35:003574
Alex Moshchuk3a4e77a2020-05-29 21:32:573575 // Otherwise, if both item and document sequence numbers differ, this
3576 // should be a different document load.
3577 return HistoryNavigationAction::kDifferentDocument;
3578 }
3579
3580 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373581 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573582 DCHECK_EQ(new_item->document_sequence_number(),
3583 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373584 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573585}
3586
3587void NavigationControllerImpl::FindFramesToNavigate(
3588 FrameTreeNode* frame,
3589 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373590 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333591 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373592 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133593 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573594 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3595 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3596 DCHECK(pending_entry_);
3597 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3598
3599 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3600
3601 if (action == HistoryNavigationAction::kSameDocument) {
3602 std::unique_ptr<NavigationRequest> navigation_request =
3603 CreateNavigationRequestFromEntry(
3604 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133605 /*is_same_document_history_load=*/true,
3606 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333607 initiator_frame_token, initiator_process_id,
3608 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573609 if (navigation_request) {
3610 // Only add the request if was properly created. It's possible for the
3611 // creation to fail in certain cases, e.g. when the URL is invalid.
3612 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303613 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573614 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473615 std::unique_ptr<NavigationRequest> navigation_request =
3616 CreateNavigationRequestFromEntry(
3617 frame, pending_entry_, new_item, reload_type,
3618 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433619 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333620 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473621 if (navigation_request) {
3622 // Only add the request if was properly created. It's possible for the
3623 // creation to fail in certain cases, e.g. when the URL is invalid.
3624 different_document_loads->push_back(std::move(navigation_request));
3625 }
3626 // For a different document, the subframes will be destroyed, so there's
3627 // no need to consider them.
3628 return;
Alex Moshchuke65c39272020-06-03 17:55:373629 } else if (action == HistoryNavigationAction::kStopLooking) {
3630 return;
creis4e2ecb72015-06-20 00:46:303631 }
3632
Yoav Weiss8c573952022-11-17 17:35:133633 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3634 // we currently only support soft navigation heuristics for the top level
3635 // frame.
creis4e2ecb72015-06-20 00:46:303636 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333637 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3638 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373639 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433640 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303641 }
3642}
3643
Harkiran Bolariaba823e42021-05-21 18:30:363644base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243645 const LoadURLParams& params) {
3646 // Find the appropriate FrameTreeNode.
3647 FrameTreeNode* node = nullptr;
Avi Drissmanbd153642024-09-03 18:58:053648 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3649 node = params.frame_tree_node_id
Ali Hijazid87307d2022-11-07 20:15:033650 ? frame_tree_->FindByID(params.frame_tree_node_id)
3651 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503652 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243653 }
3654
3655 // If no FrameTreeNode was specified, navigate the main frame.
3656 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033657 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243658
Camille Lamy5193caa2018-10-12 11:59:423659 // Compute overrides to the LoadURLParams for |override_user_agent|,
3660 // |should_replace_current_entry| and |has_user_gesture| that will be used
3661 // both in the creation of the NavigationEntry and the NavigationRequest.
3662 // Ideally, the LoadURLParams themselves would be updated, but since they are
3663 // passed as a const reference, this is not possible.
3664 // TODO(clamy): When we only create a NavigationRequest, move this to
3665 // CreateNavigationRequestFromLoadURLParams.
3666 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3667 GetLastCommittedEntry());
3668
Rakina Zata Amnie2d31312022-11-18 03:38:453669 // An entry replacement must happen if the current browsing context should
3670 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333671 bool should_replace_current_entry =
3672 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453673 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423674
clamy21718cc22018-06-13 13:34:243675 // Javascript URLs should not create NavigationEntries. All other navigations
3676 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243677 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373678 std::unique_ptr<NavigationEntryImpl> entry =
3679 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3680 should_replace_current_entry,
3681 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243682 DiscardPendingEntry(false);
3683 SetPendingEntry(std::move(entry));
3684 }
3685
Tim Judkins59548192023-05-17 17:51:203686 // Renderer-debug URLs are sent to the current renderer process immediately
3687 // for processing and don't need to create a NavigationRequest. Note: this
3688 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243689 // renderer-debug URLs.
3690 // Note: we intentionally leave the pending entry in place for renderer debug
3691 // URLs, unlike the cases below where we clear it if the navigation doesn't
3692 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303693 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483694 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3695 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153696 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203697 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483698 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363699 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483700 }
3701
clamy21718cc22018-06-13 13:34:243702 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363703 return nullptr;
clamy21718cc22018-06-13 13:34:243704 }
3705
Antonio Sartori78a749f2020-11-30 12:03:393706 DCHECK(pending_entry_);
3707
clamy21718cc22018-06-13 13:34:243708 // Convert navigations to the current URL to a reload.
3709 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3710 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3711 // DevTools sometimes issues navigations to main frames that they do not
3712 // expect to see treated as reload, and it only works because they pass a
3713 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3714 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543715 ReloadType reload_type = params.reload_type;
3716 if (reload_type == ReloadType::NONE &&
3717 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043718 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243719 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243720 params.load_type ==
3721 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543722 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243723 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473724 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393725
3726 // If this is a reload of an existing FrameNavigationEntry and we had a
3727 // policy container for it, then we should copy it into the pending entry,
3728 // so that it is copied to the navigation request in
3729 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453730 FrameNavigationEntry* previous_frame_entry =
3731 GetLastCommittedEntry()->GetFrameEntry(node);
3732 if (previous_frame_entry &&
3733 previous_frame_entry->policy_container_policies()) {
3734 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3735 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393736 }
3737 }
3738
3739 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173740 // document, then we should copy the document polices from RenderFrameHost's
3741 // PolicyContainerHost. The NavigationRequest will create a new
3742 // PolicyContainerHost with the document policies from the |pending_entry_|,
3743 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3744 // the navigation. This way, we ensure that we keep enforcing the right
3745 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453746 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393747 if (node->current_frame_host() &&
3748 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193749 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163750 node->current_frame_host()
3751 ->policy_container_host()
3752 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233753 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393754 }
clamy21718cc22018-06-13 13:34:243755 }
3756
3757 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263758 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243759
Tsuyoshi Horo167ca6432022-03-09 05:16:393760 // This will be used to set the Navigation Timing API navigationStart
3761 // parameter for browser navigations in new tabs (intents, tabs opened through
3762 // "Open link in new tab"). If the navigation must wait on the current
3763 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3764 // will be updated when the BeforeUnload ack is received.
3765 const auto navigation_start_time = base::TimeTicks::Now();
3766
Camille Lamy5193caa2018-10-12 11:59:423767 std::unique_ptr<NavigationRequest> request =
3768 CreateNavigationRequestFromLoadParams(
3769 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143770 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393771 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3772 navigation_start_time);
clamy21718cc22018-06-13 13:34:243773
3774 // If the navigation couldn't start, return immediately and discard the
3775 // pending NavigationEntry.
3776 if (!request) {
3777 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363778 return nullptr;
clamy21718cc22018-06-13 13:34:243779 }
3780
Camille Lamy5193caa2018-10-12 11:59:423781#if DCHECK_IS_ON()
3782 // Safety check that NavigationRequest and NavigationEntry match.
3783 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3784#endif
3785
clamy21718cc22018-06-13 13:34:243786 // This call does not support re-entrancy. See http://crbug.com/347742.
3787 CHECK(!in_navigate_to_pending_entry_);
3788 in_navigate_to_pending_entry_ = true;
3789
arthursonzogni66f711c2019-10-08 14:40:363790 // It is not possible to delete the pending NavigationEntry while navigating
3791 // to it. Grab a reference to delay potential deletion until the end of this
3792 // function.
3793 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3794
Harkiran Bolariaba823e42021-05-21 18:30:363795 base::WeakPtr<NavigationHandle> created_navigation_handle(
3796 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053797 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243798
3799 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363800 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243801}
3802
clamyea99ea12018-05-28 13:54:233803void NavigationControllerImpl::HandleRendererDebugURL(
3804 FrameTreeNode* frame_tree_node,
3805 const GURL& url) {
3806 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243807 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3808 // the renderer process is not live, unless it is the initial navigation
3809 // of the tab.
clamyea99ea12018-05-28 13:54:233810 if (!IsInitialNavigation()) {
3811 DiscardNonCommittedEntries();
3812 return;
3813 }
Fergal Dalyecd3b0202020-06-25 01:57:373814 // The current frame is always a main frame. If IsInitialNavigation() is
3815 // true then there have been no navigations and any frames of this tab must
3816 // be in the same renderer process. If that has crashed then the only frame
3817 // that can be revived is the main frame.
3818 frame_tree_node->render_manager()
3819 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233820 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223821
3822 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3823 // notification, so set is loading to true here to properly surface it when
3824 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313825 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223826 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223827 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223828 }
clamyea99ea12018-05-28 13:54:233829 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3830}
3831
clamy21718cc22018-06-13 13:34:243832std::unique_ptr<NavigationEntryImpl>
3833NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3834 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423835 const LoadURLParams& params,
3836 bool override_user_agent,
3837 bool should_replace_current_entry,
3838 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393839 // Browser initiated navigations might not have a blob_url_loader_factory set
3840 // in params even if the navigation is to a blob URL. If that happens, lookup
3841 // the correct url loader factory to use here.
3842 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483843 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473844 // Resolve the blob URL in the storage partition associated with the target
3845 // frame. This is the storage partition the URL will be loaded in, and only
3846 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393847 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473848 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393849 }
3850
clamy21718cc22018-06-13 13:34:243851 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443852 // extra_headers in params are \n separated; navigation entries want \r\n.
3853 std::string extra_headers_crlf;
3854 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243855
3856 // For subframes, create a pending entry with a corresponding frame entry.
3857 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453858 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243859 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083860 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243861 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373862 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213863 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3864 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393865 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163866 // a conversion of a new navigation into a reload, we will set the right
3867 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193868 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243869 } else {
3870 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173871 // If `node` is the outermost main frame, it rewrites a virtual url in order
3872 // to adjust the original input url if needed. For inner frames such as
3873 // fenced frames or subframes, they don't rewrite urls as the urls are not
3874 // input urls by users.
3875 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323876 scoped_refptr<SiteInstance> source_site_instance =
3877 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373878 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323879 if (source_site_instance && source_site_instance->HasProcess()) {
3880 source_process_site_url =
3881 source_site_instance->GetProcess()->GetProcessLock().site_url();
3882 }
clamy21718cc22018-06-13 13:34:243883 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063884 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323885 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213886 params.transition_type, params.is_renderer_initiated,
3887 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3888 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243889 entry->set_source_site_instance(
3890 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3891 entry->SetRedirectChain(params.redirect_chain);
3892 }
3893
3894 // Set the FTN ID (only used in non-site-per-process, for tests).
3895 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243896 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423897 entry->SetIsOverridingUserAgent(override_user_agent);
3898 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543899 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243900
clamy21718cc22018-06-13 13:34:243901 switch (params.load_type) {
3902 case LOAD_TYPE_DEFAULT:
3903 break;
3904 case LOAD_TYPE_HTTP_POST:
3905 entry->SetHasPostData(true);
3906 entry->SetPostData(params.post_data);
3907 break;
3908 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:543909 // LoadDataWithBaseURL is a special case that needs to assign both a base
3910 // URL and a virtual URL, while loading the actual content from a data
3911 // URL.
clamy21718cc22018-06-13 13:34:243912 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:543913 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:283914#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243915 entry->SetDataURLAsString(params.data_url_as_string);
3916#endif
3917 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3918 break;
Shu Yang112ad492024-07-25 17:11:543919#if BUILDFLAG(IS_ANDROID)
3920 case LOAD_TYPE_PDF_ANDROID:
3921 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
3922 // internal URL is used for the navigation URL.
3923 entry->SetVirtualURL(params.virtual_url_for_special_cases);
3924 break;
3925#endif
clamy21718cc22018-06-13 13:34:243926 }
3927
3928 // TODO(clamy): NavigationEntry is meant for information that will be kept
3929 // after the navigation ended and therefore is not appropriate for
3930 // started_from_context_menu. Move started_from_context_menu to
3931 // NavigationUIData.
3932 entry->set_started_from_context_menu(params.started_from_context_menu);
3933
3934 return entry;
3935}
3936
clamyea99ea12018-05-28 13:54:233937std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423938NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3939 FrameTreeNode* node,
3940 const LoadURLParams& params,
3941 bool override_user_agent,
3942 bool should_replace_current_entry,
3943 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143944 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423945 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573946 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393947 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223948 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493949 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453950 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583951 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343952 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:373953 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573954 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:523955
3956 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
3957 // subframes have FrameNavigationEntries associated with them. Until then,
3958 // there may be cases where a subframe navigation is missing `frame_entry`
3959 // (e.g., see https://crbug.com/358084015).
3960
Nasko Oskov3c2f9e252019-01-10 17:45:533961 // All renderer-initiated navigations must have an initiator_origin.
3962 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513963
Camille Lamy5193caa2018-10-12 11:59:423964 GURL url_to_load;
3965 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323966
Camille Lamy2baa8022018-10-19 16:43:173967 // For main frames, rewrite the URL if necessary and compute the virtual URL
3968 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263969 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423970 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173971 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423972 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423973
Shu Yang112ad492024-07-25 17:11:543974 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
3975 // that need to define a virtual URL to display, which differs from the
3976 // navigation URL.
3977 if (params.load_type == LOAD_TYPE_DATA) {
3978 virtual_url = params.virtual_url_for_special_cases;
3979 }
3980#if BUILDFLAG(IS_ANDROID)
3981 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
3982 virtual_url = params.virtual_url_for_special_cases;
3983 }
3984#endif
Camille Lamy5193caa2018-10-12 11:59:423985
Camille Lamy2baa8022018-10-19 16:43:173986 if (virtual_url.is_empty())
3987 virtual_url = url_to_load;
3988
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573989 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283990
Aran Gilman249eb122019-12-02 23:32:463991 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3992 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3993 // return different results, leading to a different URL in the
3994 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3995 // pending NavigationEntry, as we'll only make one call to
3996 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:523997 if (frame_entry) {
3998 VLOG_IF(1, (url_to_load != frame_entry->url()))
3999 << "NavigationRequest and FrameEntry have different URLs: "
4000 << url_to_load << " vs " << frame_entry->url();
4001 }
Camille Lamyb9ed3c52018-11-19 15:34:284002
Camille Lamy2baa8022018-10-19 16:43:174003 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:424004 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:174005 // NavigationRequest.
4006 } else {
4007 url_to_load = params.url;
4008 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:244009 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:174010 }
Camille Lamy5193caa2018-10-12 11:59:424011
Ehsan Karamad44fc72112019-02-26 18:15:474012 if (node->render_manager()->is_attaching_inner_delegate()) {
4013 // Avoid starting any new navigations since this node is now preparing for
4014 // attaching an inner delegate.
4015 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204016 }
Camille Lamy5193caa2018-10-12 11:59:424017
Alex Moshchuk99242832023-05-22 17:21:444018 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424019 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444020 }
Camille Lamy5193caa2018-10-12 11:59:424021
danakjd83d706d2020-11-25 22:11:124022 // Look for a pending commit that is to another document in this
4023 // FrameTreeNode. If one exists, then the last committed URL will not be the
4024 // current URL by the time this navigation commits.
4025 bool has_pending_cross_document_commit =
4026 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214027 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124028
Minggang Wangb9f3fa92021-07-01 15:30:314029 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494030 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524031 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494032 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134033 /*is_same_document_history_load=*/false,
4034 is_embedder_initiated_fenced_frame_navigation,
4035 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424036
4037 // Create the NavigationParams based on |params|.
4038
Hiroki Nakagawa4ed61282021-06-18 05:37:234039 bool is_view_source_mode = entry->IsViewSourceMode();
4040 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294041
Antonio Sartori6984c742021-08-26 08:03:414042 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294043
Hiroki Nakagawa4ed61282021-06-18 05:37:234044 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294045 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254046 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294047
Charlie Reisf21cd182024-08-09 21:44:524048 std::string page_state_data =
4049 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4050
Minggang Wangb9f3fa92021-07-01 15:30:314051 blink::mojom::CommonNavigationParamsPtr common_params =
4052 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214053 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514054 blink::mojom::Referrer::New(params.referrer.url,
4055 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214056 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514057 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:394058 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514059 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144060 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414061 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274062 false /* has_text_fragment_token */,
4063 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4064 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514065 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054066 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424067
Minggang Wangb9f3fa92021-07-01 15:30:314068 blink::mojom::CommitNavigationParamsPtr commit_params =
4069 blink::mojom::CommitNavigationParams::New(
Arthur Sonzognic686e8f2024-01-11 08:36:374070 std::nullopt,
Ari Chivukulac7533522024-05-14 21:52:344071 // The correct storage key will be computed before committing the
4072 // navigation.
4073 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324074 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504075 std::vector<net::RedirectInfo>(), params.post_content_type,
4076 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524077 params.can_load_local_resources, page_state_data,
4078 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134079 /*intended_as_new_entry=*/true,
4080 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144081 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4082 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134083 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314084 params.should_clear_history_list,
4085 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224086 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134087 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514088 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284089#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134090 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144091#endif
Yoav Weiss8c573952022-11-17 17:35:134092 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154093 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134094 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074095 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134096 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4097 /*origin_agent_cluster=*/false,
4098 /*origin_agent_cluster_left_as_default=*/true,
4099 /*enabled_client_hints=*/
4100 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264101 /*is_cross_site_cross_browsing_context_group=*/false,
4102 /*should_have_sticky_user_activation=*/false,
4103 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134104 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014105 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134106 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584107 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134108 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134109 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284110 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134111 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444112 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424113 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374114 /*view_transition_state=*/std::nullopt,
4115 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054116 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464117 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374118 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054119 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094120 /*load_with_storage_access=*/
4121 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374122 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374123 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484124 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314125 /*visited_link_salt=*/std::nullopt,
Thomas Nguyen42fa4c22024-11-06 14:29:164126 /*local_surface_id=*/std::nullopt,
Aldo Culquicondor17b73f72025-01-29 21:02:174127 node->current_frame_host()->GetCachedPermissionStatuses(),
4128 /*should_skip_screentshot=*/false);
Xiaohan Wang7f8052e02022-01-14 18:44:284129#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424130 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564131 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424132 }
4133#endif
4134
Lucas Furukawa Gadania9c45682019-07-31 22:05:144135 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074136 commit_params->navigation_timing->system_entropy_at_navigation_start =
4137 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4138 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424139
Camille Lamy5193caa2018-10-12 11:59:424140 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4141 std::string extra_headers_crlf;
4142 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094143
Alex Moshchuk9321e6a2022-12-07 21:58:314144 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144145 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084146 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094147 params.initiator_frame_token, params.initiator_process_id,
4148 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214149 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294150 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454151 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344152 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034153 embedder_shared_storage_context);
Liam Bradyedb866e2025-01-22 22:28:134154
4155 if (!navigation_request) {
4156 return nullptr;
4157 }
4158
Yao Xiaodc5ed102019-06-04 19:19:094159 navigation_request->set_from_download_cross_origin_redirect(
4160 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554161 navigation_request->set_force_new_browsing_instance(
4162 params.force_new_browsing_instance);
Steve Kobes8d111ba2024-11-12 15:23:514163 navigation_request->set_force_new_compositor(params.force_new_compositor);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434164 if (params.force_no_https_upgrade) {
4165 navigation_request->set_force_no_https_upgrade();
4166 }
Yao Xiaodc5ed102019-06-04 19:19:094167 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424168}
4169
4170std::unique_ptr<NavigationRequest>
4171NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234172 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574173 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234174 FrameNavigationEntry* frame_entry,
4175 ReloadType reload_type,
4176 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434177 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374178 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334179 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374180 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134181 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344182 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234183 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434184 // We should never navigate to an existing initial NavigationEntry that is the
4185 // initial NavigationEntry for the initial empty document that hasn't been
4186 // overridden by the synchronous about:blank commit, to preserve previous
4187 // behavior where trying to reload when the main frame is on the initial empty
4188 // document won't result in a navigation.
4189 // See also https://crbug.com/1277414.
4190 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324191
clamyea99ea12018-05-28 13:54:234192 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234193
Ehsan Karamad44fc72112019-02-26 18:15:474194 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4195 // Avoid starting any new navigations since this node is now preparing for
4196 // attaching an inner delegate.
4197 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204198 }
4199
Alex Moshchuk99242832023-05-22 17:21:444200 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4201 dest_url)) {
clamyea99ea12018-05-28 13:54:234202 return nullptr;
4203 }
4204
clamyea99ea12018-05-28 13:54:234205 // This will be used to set the Navigation Timing API navigationStart
4206 // parameter for browser navigations in new tabs (intents, tabs opened through
4207 // "Open link in new tab"). If the navigation must wait on the current
4208 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4209 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074210
clamyea99ea12018-05-28 13:54:234211 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074212 const auto navigation_start_system_entropy =
4213 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4214 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234215
danakjd83d706d2020-11-25 22:11:124216 // Look for a pending commit that is to another document in this
4217 // FrameTreeNode. If one exists, then the last committed URL will not be the
4218 // current URL by the time this navigation commits.
4219 bool has_pending_cross_document_commit =
4220 frame_tree_node->render_manager()
4221 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494222 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214223 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124224
Minggang Wangb9f3fa92021-07-01 15:30:314225 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124226 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524227 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494228 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494229 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134230 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494231 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424232
4233 // A form submission may happen here if the navigation is a
4234 // back/forward/reload navigation that does a form resubmission.
4235 scoped_refptr<network::ResourceRequestBody> request_body;
4236 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394237 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504238 // entry. This way, it could be directly retrieved here. Right now, it is only
4239 // partially recovered when request.method == "POST" and request.body exists.
4240 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424241 if (frame_entry->method() == "POST") {
4242 request_body = frame_entry->GetPostData(&post_content_type);
4243 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304244 post_content_type = std::string(
4245 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504246 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424247 }
4248
4249 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314250 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514251 entry->ConstructCommonNavigationParams(
4252 *frame_entry, request_body, dest_url,
4253 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384254 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534255 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514256 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554257 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424258
4259 // TODO(clamy): |intended_as_new_entry| below should always be false once
4260 // Reload no longer leads to this being called for a pending NavigationEntry
4261 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314262 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144263 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404264 *frame_entry, common_params->url, common_params->method,
4265 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144266 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534267 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484268 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134269 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074270 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144271 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074272 commit_params->navigation_timing->system_entropy_at_navigation_start =
4273 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4274 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Thomas Nguyen42fa4c22024-11-06 14:29:164275 commit_params->initial_permission_statuses =
4276 frame_tree_node->current_frame_host()->GetCachedPermissionStatuses();
Camille Lamy5193caa2018-10-12 11:59:424277
W. James MacLeanb7d6092682022-10-05 15:23:264278 if (common_params->url.IsAboutSrcdoc()) {
4279 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4280 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594281 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264282 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334283 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314284 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144285 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434286 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334287 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4288 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374289 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294290 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4291 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474292 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234293}
4294
[email protected]d202a7c2012-01-04 07:53:474295void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214296 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274297 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404298
Takashi Toyoshimaea534ef22021-07-21 03:27:594299 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404300 // location bar will have up-to-date information about the security style
4301 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134302 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404303
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374304 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574305 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294306}
4307
initial.commit09911bf2008-07-26 23:55:294308// static
[email protected]d202a7c2012-01-04 07:53:474309size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234310 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154311 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214312 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234313}
4314
[email protected]d202a7c2012-01-04 07:53:474315void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224316 if (is_active && needs_reload_)
4317 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214318
4319 if (frame_tree_->is_primary();
4320 auto* cache = GetNavigationEntryScreenshotCache()) {
4321 cache->SetVisible(is_active);
4322 }
initial.commit09911bf2008-07-26 23:55:294323}
4324
[email protected]d202a7c2012-01-04 07:53:474325void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034326 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4327 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294328 if (!needs_reload_)
4329 return;
4330
Bo Liucdfa4b12018-11-06 00:21:444331 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4332 needs_reload_type_);
4333
initial.commit09911bf2008-07-26 23:55:294334 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004335 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294336 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004337 if (entry_replaced_by_post_commit_error_) {
4338 // If the current entry is a post commit error, we reload the entry it
4339 // replaced instead. We leave the error entry in place until a commit
4340 // replaces it, but the pending entry points to the original entry in the
4341 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4342 // case that pending_entry_ != entries_[pending_entry_index_].
4343 // Note that this handling is similar to
4344 // `NavigationControllerImpl::Reload()`.
4345 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4346 pending_entry_index_ = GetCurrentEntryIndex();
4347 NavigateToExistingPendingEntry(
4348 ReloadType::NONE,
4349 /*initiator_rfh=*/nullptr,
4350 /*soft_navigation_heuristics_task_id=*/std::nullopt,
4351 /*navigation_api_key=*/nullptr);
4352 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134353 NavigateToExistingPendingEntry(
4354 ReloadType::NONE,
4355 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374356 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134357 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454358 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434359 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274360 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344361 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134362 NavigateToExistingPendingEntry(
4363 ReloadType::NONE,
4364 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374365 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134366 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344367 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434368 // We should never navigate to an existing initial NavigationEntry that is
4369 // the initial NavigationEntry for the initial empty document that hasn't
4370 // been overridden by the synchronous about:blank commit, to preserve
4371 // legacy behavior where trying to reload when the main frame is on the
4372 // initial empty document won't result in a navigation. See also
4373 // https://crbug.com/1277414. If there is something to reload, the
4374 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4375 // it here.
avicc872d7242015-08-19 21:26:344376 needs_reload_ = false;
4377 }
initial.commit09911bf2008-07-26 23:55:294378}
4379
Kevin McNeeccca6172021-10-19 17:11:144380base::WeakPtr<NavigationHandle>
4381NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364382 RenderFrameHost* render_frame_host,
4383 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364384 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134385 RenderFrameHostImpl* rfhi =
4386 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584387
4388 // Only active documents can load post-commit error pages:
4389 // - If the document is in pending deletion, the browser already committed to
4390 // destroying this RenderFrameHost so ignore loading the error page.
4391 // - If the document is in back-forward cache, it's not allowed to navigate as
4392 // it should remain frozen. Ignore the request and evict the document from
4393 // back-forward cache.
4394 // - If the document is prerendering, it can navigate but when loading error
4395 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114396 if (rfhi->IsInactiveAndDisallowActivation(
4397 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144398 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114399 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584400
Rakina Zata Amni919b7922020-12-11 09:03:134401 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414402
Minggang Wangb9f3fa92021-07-01 15:30:314403 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434404 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594405 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4406 // the frame actually committed (e.g. iframe with "src" set to a
4407 // slow-responding URL). We should rewrite the URL to about:blank in this
4408 // case, as the renderer will only think a page is an error page if it has a
4409 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134410 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314411 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434412 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334413 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414414
Mike Jacksone2aa7af2023-05-17 06:45:074415 commit_params->navigation_timing->system_entropy_at_navigation_start =
4416 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4417 node, blink::mojom::SystemEntropy::kNormal);
4418
arthursonzogni70ac7302020-05-28 08:49:054419 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4420 // error pages.
Liam Brady34639ec92023-10-13 19:50:454421 commit_params->frame_policy = node->pending_frame_policy();
arthursonzogni70ac7302020-05-28 08:49:054422
John Delaney131ad362019-08-08 21:57:414423 std::unique_ptr<NavigationRequest> navigation_request =
4424 NavigationRequest::CreateBrowserInitiated(
4425 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094426 false /* was_opener_suppressed */, "" /* extra_headers */,
4427 nullptr /* frame_entry */, nullptr /* entry */,
4428 false /* is_form_submission */, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374429 std::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364430 navigation_request->set_post_commit_error_page_html(error_page_html);
Lei Zhanga4770832023-07-19 18:02:364431 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
Charlie Reis09952ee2022-12-08 16:35:074432 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414433 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144434
4435 // Calling BeginNavigation may destroy the NavigationRequest.
4436 base::WeakPtr<NavigationRequest> created_navigation_request(
4437 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414438 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144439 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414440}
4441
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574442void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214443 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094444 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154445 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144446 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294447}
4448
[email protected]d202a7c2012-01-04 07:53:474449void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364450 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584451 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474452 // represent a no-committed-entry state.
4453 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364454 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584455 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474456 // if `entries_` contains pre-existing entries from the NavigationController
4457 // before restore, which would not be removed and will be at the front of the
4458 // entries list, causing the index to be off by the amount of pre-existing
4459 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294460 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294461}
[email protected]765b35502008-08-21 00:51:204462
arthursonzogni69a6a1b2019-09-17 09:23:004463void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004464 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4465}
4466
4467void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4468 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474469 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104470 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4471 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294472 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474473 return;
Michael Thiessenc5676d22019-09-25 22:32:104474 }
avi45a72532015-04-07 21:01:454475 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314476
4477 if (!delegate_)
4478 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374479 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484480}
4481
avi7c6f35e2015-05-08 17:52:384482int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4483 int nav_entry_id) const {
4484 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4485 if (entries_[i]->GetUniqueID() == nav_entry_id)
4486 return i;
4487 }
4488 return -1;
4489}
4490
[email protected]d202a7c2012-01-04 07:53:474491void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574492 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254493 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574494 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594495 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254496 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374497 // Normally, cloning a NavigationEntryImpl results in sharing
4498 // FrameNavigationEntries between the original and the clone. However, when
4499 // cloning from a different NavigationControllerImpl, we want to fork the
4500 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374501 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594502 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254503 }
Rakina Zata Amnie2d31312022-11-18 03:38:454504 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274505 DCHECK(pending_entry_index_ == -1 ||
4506 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254507}
[email protected]c5b88d82012-10-06 17:03:334508
4509void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184510 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334511 get_timestamp_callback_ = get_timestamp_callback;
4512}
[email protected]8ff00d72012-10-23 19:12:214513
Shivani Sharmaffb32b82019-04-09 16:58:474514// History manipulation intervention:
4515void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474516 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564517 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404518 bool is_renderer_initiated,
4519 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564520 // Note that for a subframe,
4521 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454522 // gesture happened in any subframe (propagated to main frame) or in the main
4523 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564524 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274525 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474526 return;
4527 }
4528 if (last_committed_entry_index_ == -1)
4529 return;
4530
Shivani Sharmac4cc8922019-04-18 03:11:174531 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474532
Alexander Timine3ec4192020-04-20 16:39:404533 // Log UKM with the URL we are navigating away from.
4534 ukm::builders::HistoryManipulationIntervention(
4535 previous_page_load_ukm_source_id)
4536 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474537}
4538
Shivani Sharmac4cc8922019-04-18 03:11:174539void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4540 int reference_index,
4541 bool skippable) {
4542 auto* reference_entry = GetEntryAtIndex(reference_index);
4543 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4544
4545 int64_t document_sequence_number =
4546 reference_entry->root_node()->frame_entry->document_sequence_number();
4547 for (int index = 0; index < GetEntryCount(); index++) {
4548 auto* entry = GetEntryAtIndex(index);
4549 if (entry->root_node()->frame_entry->document_sequence_number() ==
4550 document_sequence_number) {
4551 entry->set_should_skip_on_back_forward_ui(skippable);
4552 }
4553 }
4554}
4555
arthursonzogni66f711c2019-10-08 14:40:364556std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4557NavigationControllerImpl::ReferencePendingEntry() {
4558 DCHECK(pending_entry_);
4559 auto pending_entry_ref =
4560 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4561 pending_entry_refs_.insert(pending_entry_ref.get());
4562 return pending_entry_ref;
4563}
4564
4565void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4566 // Ignore refs that don't correspond to the current pending entry.
4567 auto it = pending_entry_refs_.find(ref);
4568 if (it == pending_entry_refs_.end())
4569 return;
4570 pending_entry_refs_.erase(it);
4571
4572 if (!pending_entry_refs_.empty())
4573 return;
4574
4575 // The pending entry may be deleted before the last PendingEntryRef.
4576 if (!pending_entry_)
4577 return;
4578
4579 // We usually clear the pending entry when the matching NavigationRequest
4580 // fails, so that an arbitrary URL isn't left visible above a committed page.
4581 //
4582 // However, we do preserve the pending entry in some cases, such as on the
4583 // initial navigation of an unmodified blank tab. We also allow the delegate
4584 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4585 // user edit the URL and try again. This may be useful in cases that the
4586 // committed page cannot be attacker-controlled. In these cases, we still
4587 // allow the view to clear the pending entry and typed URL if the user
4588 // requests (e.g., hitting Escape with focus in the address bar).
4589 //
4590 // Do not leave the pending entry visible if it has an invalid URL, since this
4591 // might be formatted in an unexpected or unsafe way.
4592 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364593 bool should_preserve_entry =
4594 (pending_entry_ == GetVisibleEntry()) &&
4595 pending_entry_->GetURL().is_valid() &&
4596 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4597 if (should_preserve_entry)
4598 return;
4599
4600 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374601 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364602}
4603
Titouan Rigoudy6ec70402021-02-02 15:42:194604std::unique_ptr<PolicyContainerPolicies>
4605NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394606 RenderFrameHostImpl* rfh,
4607 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214608 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174609 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214610 if (navigation_encountered_error) {
4611 // We should never reload the policy container of an error page from
4612 // history, see https://crbug.com/364773822.
4613 return nullptr;
4614 }
4615
Antonio Sartori78a749f2020-11-30 12:03:394616 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454617 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394618 FrameNavigationEntry* previous_frame_entry =
4619 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4620
Alison Gale770f3fc2024-04-27 00:39:584621 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394622 // ensure we always have a FrameNavigationEntry here.
4623 if (!previous_frame_entry)
4624 return nullptr;
4625
Titouan Rigoudy6ec70402021-02-02 15:42:194626 const PolicyContainerPolicies* previous_policies =
4627 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394628
Titouan Rigoudy6ec70402021-02-02 15:42:194629 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394630 return nullptr;
4631
4632 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234633 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394634 }
4635
Titouan Rigoudy72f892d2022-05-02 18:21:234636 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394637}
4638
Hayato Ito2c8c08d02021-06-23 03:38:434639void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504640 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434641 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4642 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4643 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504644
Kevin McNee7705fe82024-11-07 18:56:314645 int history_offset = GetLastCommittedEntryIndex();
4646 int history_length = GetEntryCount();
4647 auto callback = [history_offset, history_length](RenderViewHostImpl* rvh) {
4648 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4649 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4650 }
4651 };
Ali Hijazid87307d2022-11-07 20:15:034652 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504653}
4654
4655void NavigationControllerImpl::DidAccessInitialMainDocument() {
4656 // We may have left a failed browser-initiated navigation in the address bar
4657 // to let the user edit it and try again. Clear it now that content might
4658 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034659 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504660 DiscardPendingEntry(false);
4661
4662 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374663 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504664}
4665
4666void NavigationControllerImpl::UpdateStateForFrame(
4667 RenderFrameHostImpl* rfhi,
4668 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564669 OPTIONAL_TRACE_EVENT1("content",
4670 "NavigationControllerImpl::UpdateStateForFrame",
4671 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504672 // The state update affects the last NavigationEntry associated with the given
4673 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4674 // in the case of an UpdateState from a frame being swapped out). We track
4675 // which entry this is in the RenderFrameHost's nav_entry_id.
4676 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4677 if (!entry)
4678 return;
4679
4680 FrameNavigationEntry* frame_entry =
4681 entry->GetFrameEntry(rfhi->frame_tree_node());
4682 if (!frame_entry)
4683 return;
4684
4685 // The SiteInstance might not match if we do a cross-process navigation with
4686 // replacement (e.g., auto-subframe), in which case the swap out of the old
4687 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4688 // has already been replaced and destroyed.
4689 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4690 return;
4691
4692 if (page_state == frame_entry->page_state())
4693 return; // Nothing to update.
4694
4695 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4696
4697 // The document_sequence_number and item_sequence_number recorded in the
4698 // FrameNavigationEntry should not differ from the one coming with the update,
4699 // since it must come from the same document. Do not update it if a difference
4700 // is detected, as this indicates that |frame_entry| is not the correct one.
4701 blink::ExplodedPageState exploded_state;
4702 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4703 return;
4704
4705 if (exploded_state.top.document_sequence_number !=
4706 frame_entry->document_sequence_number() ||
4707 exploded_state.top.item_sequence_number !=
4708 frame_entry->item_sequence_number()) {
4709 return;
4710 }
4711
4712 frame_entry->SetPageState(page_state);
4713 NotifyEntryChanged(entry);
4714}
4715
Nate Chapina2c881f52023-11-07 17:02:094716namespace {
4717
4718// The caller is responsible for ensuring the entry is same-origin to the
4719// origin to be committed.
4720blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4721 FrameNavigationEntry* frame_entry,
4722 int64_t pending_document_sequence_number) {
4723 blink::ExplodedPageState exploded_state;
4724 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4725 &exploded_state)) {
4726 return nullptr;
4727 }
4728 blink::ExplodedFrameState frame_state = exploded_state.top;
4729
4730 // If the document represented by this FNE hid its full url from appearing in
4731 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4732 // in the navigation API as well (unless we're navigating to that document).
4733 std::u16string url;
4734 if (pending_document_sequence_number ==
4735 frame_entry->document_sequence_number() ||
4736 !frame_entry->protect_url_in_navigation_api()) {
4737 url = frame_state.url_string.value_or(std::u16string());
4738 }
4739
4740 return blink::mojom::NavigationApiHistoryEntry::New(
4741 frame_state.navigation_api_key.value_or(std::u16string()),
4742 frame_state.navigation_api_id.value_or(std::u16string()), url,
4743 frame_state.item_sequence_number, frame_state.document_sequence_number,
4744 frame_state.navigation_api_state);
4745}
4746
4747} // namespace
4748
Domenic Denicolacd30f5f82022-03-16 21:48:014749std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4750NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574751 Direction direction,
4752 int entry_index,
4753 const url::Origin& pending_origin,
4754 FrameTreeNode* node,
4755 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304756 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094757 int64_t pending_document_sequence_number,
4758 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014759 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454760 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174761 // Don't process the initial entry.
4762 DCHECK_EQ(GetEntryCount(), 1);
4763 return entries;
4764 }
Nate Chapind1fe3612021-04-16 20:45:574765 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304766 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574767 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4768 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094769 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574770 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414771 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574772 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014773 // An entry should only appear in the navigation API entries if it is for
4774 // the same origin as the document being committed. Check the committed
4775 // origin, or if that is not available (during restore), check against the
4776 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584777 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094778 // once we can be sure that entries with the same ISN will never be
4779 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414780 url::Origin frame_entry_origin =
4781 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4782 frame_entry->url(),
4783 frame_entry->initiator_origin().value_or(url::Origin())));
4784 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574785 break;
4786 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4787 continue;
Nate Chapina2c881f52023-11-07 17:02:094788 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4789 ToNavigationApiHistoryEntry(frame_entry,
4790 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304791 DCHECK(entry->url.empty() ||
4792 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574793 entries.push_back(std::move(entry));
4794 previous_item_sequence_number = frame_entry->item_sequence_number();
4795 }
4796 }
4797 // If |entries| was constructed by iterating backwards from
4798 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4799 // earliest-at-the-front. Reverse it.
4800 if (direction == Direction::kBack)
4801 std::reverse(entries.begin(), entries.end());
4802 return entries;
4803}
4804
Domenic Denicolacd30f5f82022-03-16 21:48:014805blink::mojom::NavigationApiHistoryEntryArraysPtr
4806NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554807 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574808 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404809 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444810 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404811 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574812
Nate Chapind1fe3612021-04-16 20:45:574813 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554814 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574815
Nate Chapine82339d02022-05-03 23:48:254816 // NOTE: |entry_index| is the index where this entry will commit if no
4817 // modifications are made between now and DidCommitNavigation. This is used to
4818 // walk |entries_| and determine which entries should be exposed by the
4819 // navigation API. It is important to calculate this correctly, because blink
4820 // will cancel a same-document history commit if it's not present in the
4821 // entries blink knows about.
4822 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574823 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304824 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254825 bool will_create_new_entry = false;
4826 if (GetPendingEntryIndex() != -1) {
4827 entry_index = GetPendingEntryIndex();
4828 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4829 pending_item_sequence_number = frame_entry->item_sequence_number();
4830 pending_document_sequence_number =
4831 frame_entry->document_sequence_number();
4832 }
4833 } else if (request &&
4834 !NavigationTypeUtils::IsReload(
4835 request->common_params().navigation_type) &&
4836 !NavigationTypeUtils::IsHistory(
4837 request->common_params().navigation_type) &&
4838 !request->common_params().should_replace_current_entry &&
4839 !request->common_params()
4840 .is_history_navigation_in_new_child_frame) {
4841 will_create_new_entry = true;
4842 entry_index = GetLastCommittedEntryIndex() + 1;
4843 // Don't set pending_item_sequence_number or
4844 // pending_document_sequence_number in this case - a new unique isn/dsn will
4845 // be calculated in the renderer later.
4846 } else if (GetLastCommittedEntryIndex() != -1) {
4847 entry_index = GetLastCommittedEntryIndex();
4848 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574849 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304850 pending_document_sequence_number =
4851 frame_entry->document_sequence_number();
4852 }
Nate Chapind1fe3612021-04-16 20:45:574853 }
4854
Domenic Denicolacd30f5f82022-03-16 21:48:014855 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254856 if (entry_index == -1) {
4857 // TODO(rakina): Exit early when there is no last committed entry.
4858 // Remove when InitialNavigationEntry ships.
4859 return entry_arrays;
4860 }
4861
Nate Chapina2c881f52023-11-07 17:02:094862 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014863 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574864 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094865 pending_item_sequence_number, pending_document_sequence_number,
4866 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574867
4868 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094869 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574870 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014871 entry_arrays->forward_entries =
4872 PopulateSingleNavigationApiHistoryEntryVector(
4873 Direction::kForward, entry_index, pending_origin, node,
4874 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094875 pending_document_sequence_number, forwardmost_index);
4876 }
4877
4878 // If the previous entry is within the block of contiguous entries being
4879 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254880 FrameNavigationEntry* previous_entry = nullptr;
4881 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:054882 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4883 .initiator_frame_tree_node_id();
4884 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:254885 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4886 previous_entry = initiator_node->frame_tree()
4887 .controller()
4888 .GetLastCommittedEntry()
4889 ->GetFrameEntry(initiator_node);
4890 }
4891 } else if (GetLastCommittedEntryIndex() != -1 &&
4892 GetLastCommittedEntryIndex() >= backmost_index &&
4893 GetLastCommittedEntryIndex() <= forwardmost_index) {
4894 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4895 }
4896 if (previous_entry) {
4897 url::Origin previous_entry_origin =
4898 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4899 previous_entry->url(),
4900 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:584901 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:254902 // once we can be sure that entries with the same ISN will never be
4903 // cross-origin.
4904 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4905 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4906 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094907 }
Nate Chapind1fe3612021-04-16 20:45:574908 }
Nate Chapinc06cf80a2023-11-18 01:12:254909
Nate Chapin4e657a472022-02-06 03:38:374910 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574911}
4912
Nate Chapinfbfe5af2021-06-10 17:22:084913NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574914NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084915 FrameNavigationEntry* current_entry,
4916 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574917 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084918 if (!target_entry || !target_entry->committed_origin())
4919 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084920 if (!current_entry->committed_origin()->IsSameOriginWith(
4921 *target_entry->committed_origin())) {
4922 return HistoryNavigationAction::kStopLooking;
4923 }
4924
4925 // NOTE: We don't actually care between kSameDocument and
4926 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574927 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084928 return HistoryNavigationAction::kDifferentDocument;
4929 return HistoryNavigationAction::kKeepLooking;
4930}
4931
Domenic Denicolacc094fb2022-03-16 23:40:574932void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204933 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374934 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144935 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574936 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204937 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084938 FrameNavigationEntry* current_entry =
4939 GetLastCommittedEntry()->GetFrameEntry(node);
4940 if (!current_entry)
4941 return;
4942
Alison Gale47d1537d2024-04-19 21:31:464943 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:134944 // when `navigation.traverseTo()` is called.
4945
Nate Chapinfbfe5af2021-06-10 17:22:084946 // We want to find the nearest matching entry that is contiguously
4947 // same-instance and same-origin. Check back first, then forward.
4948 // TODO(japhet): Link spec here once it exists.
4949 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574950 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084951 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4952 if (result == HistoryNavigationAction::kStopLooking)
4953 break;
4954 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144955 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084956 return;
4957 }
4958 }
4959 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574960 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084961 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4962 if (result == HistoryNavigationAction::kStopLooking)
4963 break;
4964 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144965 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084966 return;
4967 }
4968 }
Nate Chapinbf682fa32022-09-26 22:41:204969
4970 // If we fall through to here, a matching NavigationEntry couldn't be found.
4971 // Notify the renderer that the navigation was cancelled.
4972 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4973 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084974}
4975
Domenic Denicolacc094fb2022-03-16 23:40:574976bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304977 network::mojom::ReferrerPolicy referrer_policy) {
4978 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4979 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4980}
4981
shivanigithubf405bf0d2021-11-05 17:58:334982bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4983 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:314984 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:334985 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544986 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:464987 // The preview mode appears as prerendered page in renderers, and
4988 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:034989 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:514990 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:334991 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544992}
4993
Julie Jeongeun Kim0e242242022-11-30 10:45:094994void NavigationControllerImpl::DidChangeReferrerPolicy(
4995 FrameTreeNode* node,
4996 network::mojom::ReferrerPolicy referrer_policy) {
4997 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4998 if (!entry)
4999 return;
5000
5001 // The FrameNavigationEntry may want to change whether to protect its url
5002 // in the navigation API when the referrer policy changes.
5003 entry->set_protect_url_in_navigation_api(
5004 ShouldProtectUrlInNavigationApi(referrer_policy));
5005}
5006
[email protected]8ff00d72012-10-23 19:12:215007} // namespace content