blob: 689fa93d24769ed291d574c228f8cf19d38f33a8 [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öm8472105d2024-05-15 04:36:02168 NOTREACHED_IN_MIGRATION();
Camille Lamy5193caa2018-10-12 11:59:42169 return false;
170}
171
Rakina Zata Amni312822d72021-06-04 16:13:37172// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28173// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37174// link which results in a navigation to the last committed URL (but wasn't
175// converted to do a replacement navigation in the renderer), etc.
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
ananta3bdd8ae2016-12-22 17:11:55200 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
201 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
202 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28203 bool transition_type_can_be_converted = false;
204 if (ui::PageTransitionCoreTypeIs(transition_type,
205 ui::PAGE_TRANSITION_RELOAD) &&
206 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
207 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55208 }
clamy0a656e42018-02-06 18:18:28209 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55210 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28211 transition_type_can_be_converted = true;
212 }
213 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
214 transition_type_can_be_converted = true;
215 if (!transition_type_can_be_converted)
216 return false;
217
218 // This check is required for cases like view-source:, etc. Here the URL of
219 // the navigation entry would contain the url of the page, while the virtual
220 // URL contains the full URL including the view-source prefix.
221 if (virtual_url != last_committed_entry->GetVirtualURL())
222 return false;
223
Fergal Daly766177d2020-07-07 07:54:04224 // Check that the URLs match.
225 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
226 // If there's no frame entry then by definition the URLs don't match.
227 if (!frame_entry)
228 return false;
229
230 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28231 return false;
232
233 // This check is required for Android WebView loadDataWithBaseURL. Apps
234 // can pass in anything in the base URL and we need to ensure that these
235 // match before classifying it as a reload.
236 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
237 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
238 return false;
ananta3bdd8ae2016-12-22 17:11:55239 }
240
clamy0a656e42018-02-06 18:18:28241 // Skip entries with SSL errors.
242 if (last_committed_entry->ssl_error())
243 return false;
244
245 // Don't convert to a reload when the last navigation was a POST or the new
246 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04247 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28248 return false;
249
250 return true;
ananta3bdd8ae2016-12-22 17:11:55251}
252
Arthur Sonzognic686e8f2024-01-11 08:36:37253std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12254 const mojom::DidCommitProvisionalLoadParams& params,
255 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32256 // Error pages commit in an opaque origin, yet have the real URL that resulted
257 // in an error as the |params.url|. Since successful reload of an error page
258 // should commit in the correct origin, setting the opaque origin on the
259 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17260 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37261 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32262
Arthur Sonzognic686e8f2024-01-11 08:36:37263 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32264}
265
Alex Moshchuk99242832023-05-22 17:21:44266bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42267 const GURL& virtual_url,
268 const GURL& dest_url) {
269 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44270 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
271 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42272 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
273 << virtual_url.possibly_invalid_spec();
274 return false;
275 }
276
277 // Don't attempt to navigate to non-empty invalid URLs.
278 if (!dest_url.is_valid() && !dest_url.is_empty()) {
279 LOG(WARNING) << "Refusing to load invalid URL: "
280 << dest_url.possibly_invalid_spec();
281 return false;
282 }
283
284 // The renderer will reject IPC messages with URLs longer than
285 // this limit, so don't attempt to navigate with a longer URL.
286 if (dest_url.spec().size() > url::kMaxURLChars) {
287 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
288 << " characters.";
289 return false;
290 }
291
Aaron Colwell33109c592020-04-21 21:31:19292 // Reject renderer debug URLs because they should have been handled before
293 // we get to this point. This check handles renderer debug URLs
294 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
295 // provides defense-in-depth if a renderer debug URL manages to get here via
296 // some other path. We want to reject the navigation here so it doesn't
297 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30298 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19299 LOG(WARNING) << "Refusing to load renderer debug URL: "
300 << dest_url.possibly_invalid_spec();
301 return false;
302 }
303
Alex Moshchuk99242832023-05-22 17:21:44304 // Guests only support navigations to known-safe schemes. This check already
305 // exists in the extensions layer, where it also dispatches proper events to
306 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
307 // for defense-in-depth to ensure that no other places in the codebase
308 // accidentally navigate guests to schemes such as WebUI, which is not
309 // supported. See https://crbug.com/1444221.
310 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
311 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
312 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
313 !dest_url.SchemeIs(url::kAboutScheme)) {
314 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
315 << dest_url.possibly_invalid_spec();
316 return false;
317 }
318 }
319
Camille Lamy5193caa2018-10-12 11:59:42320 return true;
321}
322
Mikel Astizba9cf2fd2017-12-17 10:38:10323// See replaced_navigation_entry_data.h for details: this information is meant
324// to ensure |*output_entry| keeps track of its original URL (landing page in
325// case of server redirects) as it gets replaced (e.g. history.replaceState()),
326// without overwriting it later, for main frames.
327void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57328 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10329 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17330 if (output_entry->GetReplacedEntryData().has_value() ||
331 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10332 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17333 }
Mikel Astizba9cf2fd2017-12-17 10:38:10334
335 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57336 data.first_committed_url = replaced_entry->GetURL();
337 data.first_timestamp = replaced_entry->GetTimestamp();
338 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29339 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10340}
341
Minggang Wangb9f3fa92021-07-01 15:30:31342blink::mojom::NavigationType GetNavigationType(
343 const GURL& old_url,
344 const GURL& new_url,
345 ReloadType reload_type,
346 NavigationEntryImpl* entry,
Charlie Reisf21cd182024-08-09 21:44:52347 FrameNavigationEntry* frame_entry,
Minggang Wangb9f3fa92021-07-01 15:30:31348 bool has_pending_cross_document_commit,
349 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49350 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13351 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49352 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23353 // Reload navigations
354 switch (reload_type) {
355 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31356 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23357 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31358 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23359 case ReloadType::NONE:
360 break; // Fall through to rest of function.
361 }
362
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08363 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31364 return entry->GetHasPostData()
365 ? blink::mojom::NavigationType::RESTORE_WITH_POST
366 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23367 }
368
danakjb952ef12021-01-14 19:58:49369 const bool can_be_same_document =
370 // A pending cross-document commit means this navigation will not occur in
371 // the current document, as that document would end up being replaced in
372 // the meantime.
373 !has_pending_cross_document_commit &&
374 // If the current document is an error page, we should always treat it as
375 // a different-document navigation so that we'll attempt to load the
376 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49377 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13378 // If the navigation is an embedder-initiated navigation of a fenced
379 // frame root (i.e. enters a fenced frame tree from outside),
380 // same-document navigations should be disabled because we don't want to
381 // allow information to be joined across multiple embedder-initiated
382 // fenced frame navigations (which may contain separate cross-site data).
383 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49384 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
385 // same-document navigations should be disabled because we want to force
386 // the creation of a new browsing context group.
387 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12388
clamyea99ea12018-05-28 13:54:23389 // History navigations.
Charlie Reisf21cd182024-08-09 21:44:52390 if (frame_entry && frame_entry->page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12391 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31392 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
393 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23394 }
395 DCHECK(!is_same_document_history_load);
396
397 // A same-document fragment-navigation happens when the only part of the url
398 // that is modified is after the '#' character.
399 //
400 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12401 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23402 //
403 // Note: this check is only valid for navigations that are not history
404 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
405 // history navigation from 'A#foo' to 'A#bar' is not a same-document
406 // navigation, but a different-document one. This is why history navigation
407 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47408 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
Charlie Reisf21cd182024-08-09 21:44:52409 frame_entry && frame_entry->method() == "GET";
danakjd83d706d2020-11-25 22:11:12410
411 // The one case where we do the wrong thing here and incorrectly choose
412 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
413 // the renderer is a frameset. All frameset navigations should be
414 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
415 // navigation would do the right thing, as it would send it to the browser and
416 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
417 // into this method). But since we can't tell that case here for browser-
418 // initiated navigations, we have to get the renderer involved. In that case
419 // the navigation would be restarted due to the renderer spending a reply of
420 // mojom::CommitResult::RestartCrossDocument.
421
422 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31423 ? blink::mojom::NavigationType::SAME_DOCUMENT
424 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23425}
426
Camille Lamy5193caa2018-10-12 11:59:42427// Adjusts the original input URL if needed, to get the URL to actually load and
428// the virtual URL, which may differ.
429void RewriteUrlForNavigation(const GURL& original_url,
430 BrowserContext* browser_context,
431 GURL* url_to_load,
432 GURL* virtual_url,
433 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42434 // Allow the browser URL handler to rewrite the URL. This will, for example,
435 // remove "view-source:" from the beginning of the URL to get the URL that
436 // will actually be loaded. This real URL won't be shown to the user, just
437 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31438 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42439 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
440 url_to_load, browser_context, reverse_on_redirect);
441}
442
443#if DCHECK_IS_ON()
444// Helper sanity check function used in debug mode.
445void ValidateRequestMatchesEntry(NavigationRequest* request,
446 NavigationEntryImpl* entry) {
447 if (request->frame_tree_node()->IsMainFrame()) {
448 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
449 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31450 ui::PageTransitionFromInt(request->common_params().transition),
451 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42452 }
Nasko Oskovc36327d2019-01-03 23:23:04453 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42454 entry->should_clear_history_list());
455 DCHECK_EQ(request->common_params().has_user_gesture,
456 entry->has_user_gesture());
457 DCHECK_EQ(request->common_params().base_url_for_data_url,
458 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04459 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42460 entry->GetCanLoadLocalResources());
461 DCHECK_EQ(request->common_params().started_from_context_menu,
462 entry->has_started_from_context_menu());
463
464 FrameNavigationEntry* frame_entry =
465 entry->GetFrameEntry(request->frame_tree_node());
466 if (!frame_entry) {
Charlie Reisf21cd182024-08-09 21:44:52467 // TODO(https://crbug.com/40467594): This case should be unreachable once
468 // all subframes have FrameNavigationEntries associated with them.
Camille Lamy5193caa2018-10-12 11:59:42469 return;
470 }
471
Camille Lamy5193caa2018-10-12 11:59:42472 DCHECK_EQ(request->common_params().method, frame_entry->method());
473
Nasko Oskovc36327d2019-01-03 23:23:04474 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42475 if (redirect_size == frame_entry->redirect_chain().size()) {
476 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04477 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42478 frame_entry->redirect_chain()[i]);
479 }
480 } else {
Peter Boström8472105d2024-05-15 04:36:02481 NOTREACHED_IN_MIGRATION();
Camille Lamy5193caa2018-10-12 11:59:42482 }
483}
484#endif // DCHECK_IS_ON()
485
Dave Tapuska8bfd84c2019-03-26 20:47:16486// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20487// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16488bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20489 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16490 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20491 DCHECK(sandboxed_initiator_rfh);
492 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
493 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16494 for (auto& item : navigations) {
495 bool within_subtree = false;
496 // Check whether this NavigationRequest affects a frame within the
497 // sandboxed frame's subtree by walking up the tree looking for the
498 // sandboxed frame.
499 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03500 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20501 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16502 within_subtree = true;
503 break;
504 }
505 }
506 if (!within_subtree)
507 return false;
508 }
509 return true;
510}
511
William Liu122754942024-01-18 22:34:39512// Used for "Navigation.SessionHistoryCount" histogram.
513enum class HistoryNavTypeForHistogram {
514 // A same-doc or cross-doc navigation of the main frame. We can only have one
515 // main frame request per `NavigationController::GoToIndex()`.
516 kMainFrame = 0,
517 // `NavigationController::GoToIndex()` creates one main frame request and
518 // one or more subframe requests.
519 kMainFrameAndSubframe,
520 // `NavigationController::GoToIndex()` creates one or more subframe requests.
521 kSubframe,
522 // Used for histogram boundary.
523 kCount
524};
525
526void CountRequests(
527 const std::vector<std::unique_ptr<NavigationRequest>>& requests,
528 int& mutable_main_frame_cnt,
529 int& mutable_subframe_cnt) {
530 for (const auto& req : requests) {
531 if (req->IsInPrimaryMainFrame()) {
532 // We can only have one main frame navigation at a time.
533 CHECK_EQ(mutable_main_frame_cnt, 0);
534 ++mutable_main_frame_cnt;
535 } else if (req->GetNavigatingFrameType() == FrameType::kSubframe) {
536 ++mutable_subframe_cnt;
537 }
538 }
539}
540
541// Record the number of different types of navigations as histograms. See
542// `HistoryNavTypeForHistogram` for the types.
543void CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
544 const std::vector<std::unique_ptr<NavigationRequest>>& cross_doc_requests,
545 const std::vector<std::unique_ptr<NavigationRequest>>& same_doc_requests) {
546 // We must have one request.
547 CHECK(!cross_doc_requests.empty() || !same_doc_requests.empty());
548
549 int main_frame_cnt = 0;
550 int subframe_cnt = 0;
551 CountRequests(cross_doc_requests, main_frame_cnt, subframe_cnt);
552 CountRequests(same_doc_requests, main_frame_cnt, subframe_cnt);
553
554 std::optional<HistoryNavTypeForHistogram> history_nav_type;
555 if (main_frame_cnt > 0) {
556 if (subframe_cnt == 0) {
557 history_nav_type = HistoryNavTypeForHistogram::kMainFrame;
558 } else {
559 history_nav_type = HistoryNavTypeForHistogram::kMainFrameAndSubframe;
560 }
561 } else if (subframe_cnt > 0) {
562 history_nav_type = HistoryNavTypeForHistogram::kSubframe;
563 }
564 if (history_nav_type.has_value()) {
565 UMA_HISTOGRAM_ENUMERATION("Navigation.BrowserInitiatedSessionHistoryCount",
566 history_nav_type.value(),
567 HistoryNavTypeForHistogram::kCount);
568 }
569}
570
[email protected]e9ba4472008-09-14 15:42:43571} // namespace
572
arthursonzogni66f711c2019-10-08 14:40:36573// NavigationControllerImpl::PendingEntryRef------------------------------------
574
575NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
576 base::WeakPtr<NavigationControllerImpl> controller)
577 : controller_(controller) {}
578
579NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
580 if (!controller_) // Can be null with interstitials.
581 return;
582
583 controller_->PendingEntryRefDeleted(this);
584}
585
[email protected]d202a7c2012-01-04 07:53:47586// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29587
[email protected]23a918b2014-07-15 09:51:36588const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23589
[email protected]765b35502008-08-21 00:51:20590// static
[email protected]d202a7c2012-01-04 07:53:47591size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23592 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20593
[email protected]e6fec472013-05-14 05:29:02594// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20595// when testing.
596static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29597
[email protected]71fde352011-12-29 03:29:56598// static
dcheng9bfa5162016-04-09 01:00:57599std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
600 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10601 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37602 std::optional<url::Origin> initiator_origin,
603 std::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10604 ui::PageTransition transition,
605 bool is_renderer_initiated,
606 const std::string& extra_headers,
607 BrowserContext* browser_context,
608 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
609 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21610 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Arthur Sonzognic686e8f2024-01-11 08:36:37611 std::nullopt /* source_process_site_url */, transition,
Sharon Yang242ef822023-05-15 21:07:32612 is_renderer_initiated, extra_headers, browser_context,
613 std::move(blob_url_loader_factory), true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10614}
615
616// static
617std::unique_ptr<NavigationEntryImpl>
618NavigationControllerImpl::CreateNavigationEntry(
619 const GURL& url,
620 Referrer referrer,
Arthur Sonzognic686e8f2024-01-11 08:36:37621 std::optional<url::Origin> initiator_origin,
622 std::optional<GURL> initiator_base_url,
623 std::optional<GURL> source_process_site_url,
dcheng9bfa5162016-04-09 01:00:57624 ui::PageTransition transition,
625 bool is_renderer_initiated,
626 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09627 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17628 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
629 bool rewrite_virtual_urls) {
630 GURL url_to_load = url;
631 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56632 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17633 if (rewrite_virtual_urls) {
634 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
635 &reverse_on_redirect);
636 }
Lukasz Anforowicz641234d52019-11-07 21:07:10637 // Let the NTP override the navigation params and pretend that this is a
638 // browser-initiated, bookmark-like navigation.
639 GetContentClient()->browser()->OverrideNavigationParams(
Sharon Yang242ef822023-05-15 21:07:32640 source_process_site_url, &transition, &is_renderer_initiated, &referrer,
Scott Violetcf6ea7e2021-06-09 21:09:21641 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10642
Patrick Monettef507e982019-06-19 20:18:06643 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28644 nullptr, // The site instance for tabs is sent on navigation
645 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21646 url_to_load, referrer, initiator_origin, initiator_base_url,
647 std::u16string(), transition, is_renderer_initiated,
648 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17649 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42650 entry->SetVirtualURL(virtual_url);
651 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56652 entry->set_update_virtual_url_with_url(reverse_on_redirect);
653 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06654 return entry;
[email protected]71fde352011-12-29 03:29:56655}
656
[email protected]cdcb1dee2012-01-04 00:46:20657// static
658void NavigationController::DisablePromptOnRepost() {
659 g_check_for_repost = false;
660}
661
[email protected]c5b88d82012-10-06 17:03:33662base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
663 base::Time t) {
664 // If |t| is between the water marks, we're in a run of duplicates
665 // or just getting out of it, so increase the high-water mark to get
666 // a time that probably hasn't been used before and return it.
667 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35668 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33669 return high_water_mark_;
670 }
671
672 // Otherwise, we're clear of the last duplicate run, so reset the
673 // water marks.
674 low_water_mark_ = high_water_mark_ = t;
675 return t;
676}
677
ckitagawa0faa5e42020-06-17 17:30:54678NavigationControllerImpl::ScopedShowRepostDialogForTesting::
679 ScopedShowRepostDialogForTesting()
680 : was_disallowed_(g_check_for_repost) {
681 g_check_for_repost = true;
682}
683
684NavigationControllerImpl::ScopedShowRepostDialogForTesting::
685 ~ScopedShowRepostDialogForTesting() {
686 g_check_for_repost = was_disallowed_;
687}
688
Nate Chapin9eb16be72022-09-23 22:54:31689NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
690 base::SafeRef<NavigationControllerImpl> controller)
691 : controller_(controller) {
692 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
693 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
694 frame_tree_node_id_to_keys_.insert(
695 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
696 if (auto* frame_entry = frame_tree_node->current_frame_host()
697 ->last_committed_frame_entry()) {
698 frame_tree_node_id_to_doc_seq_nos_.insert(
699 {frame_tree_node->frame_tree_node_id(),
700 frame_entry->document_sequence_number()});
701 }
702 }
703 PopulateKeySet(Direction::kBack);
704 PopulateKeySet(Direction::kForward);
705}
706
707void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
708 Direction direction) {
709 // Keep track of which FrameTreeNodes may still have relevant API keys in
710 // additional FrameNavigationEntries.
711 std::set<FrameTreeNode*> nodes_to_process;
712 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
713 nodes_to_process.insert(node);
714 }
715
716 const int offset = direction == Direction::kForward ? 1 : -1;
717 const int start = direction == Direction::kForward
718 ? controller_->GetLastCommittedEntryIndex()
719 : controller_->GetLastCommittedEntryIndex() - 1;
720 for (int i = start;
721 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
722 i += offset) {
723 std::set<FrameTreeNode*> nodes_to_continue_processing;
724
725 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
726 entry->ForEachFrameEntry([this, &nodes_to_process,
727 &nodes_to_continue_processing,
728 &entry](FrameNavigationEntry* frame_entry) {
729 // Find the |node| that matches |frame_entry|, if any.
730 FrameTreeNode* node = nullptr;
731 if (frame_entry == entry->root_node()->frame_entry) {
732 node = controller_->frame_tree().root();
733 } else {
734 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
735 if (it == names_to_nodes_.end())
736 return;
737 node = it->second;
738 }
739
740 // Skip this node if a previous step determine there are no longer
741 // relevant navigation API keys in this direction.
742 if (nodes_to_process.find(node) == nodes_to_process.end())
743 return;
744
745 // Stop processing |node| if we reach a point where it's cross-origin.
746 // See also PopulateSingleNavigationApiHistoryEntryVector().
747 url::Origin frame_entry_origin =
748 frame_entry->committed_origin().value_or(url::Origin::Resolve(
749 frame_entry->url(),
750 frame_entry->initiator_origin().value_or(url::Origin())));
751 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
752 return;
753
754 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
755 frame_entry->navigation_api_key());
756 // Mark |node| as needing more processing for the next entry.
757 nodes_to_continue_processing.insert(node);
758
759 // Check whether |node| went cross-document. If so, its children are
760 // no longer the same conceptual iframe as the current one, and
761 // should no longer be processed. This check is intentionally done
762 // after processing the current |node|, which may still have relevant
763 // discarded API keys.
764 if (frame_entry->document_sequence_number() !=
765 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50766 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31767 nodes_to_process.erase(descendant);
768 }
769 });
770
771 nodes_to_process.swap(nodes_to_continue_processing);
772 }
773}
774
775NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
776 std::set<std::string> all_keys;
777 // Find all remaining navigation API keys after some entries have been
778 // removed.
779 for (auto& entry : controller_->entries_) {
780 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
781 all_keys.insert(frame_entry->navigation_api_key());
782 });
783 }
784
785 // Notify each frame in the renderer of any disposed navigation API keys.
786 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
787 std::vector<std::string> disposed_keys;
788 for (const auto& key : id_to_keys.second) {
789 if (all_keys.find(key) == all_keys.end())
790 disposed_keys.push_back(key);
791 }
792 if (disposed_keys.empty())
793 continue;
794
795 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
796 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
797 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
798 }
799}
800
[email protected]d202a7c2012-01-04 07:53:47801NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00802 BrowserContext* browser_context,
803 FrameTree& frame_tree,
804 NavigationControllerDelegate* delegate)
805 : frame_tree_(frame_tree),
806 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57807 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22808 ssl_manager_(this),
Mingyu Lei68f34412023-08-21 07:31:37809 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)),
810 back_forward_cache_(browser_context) {
[email protected]3d7474ff2011-07-27 17:47:37811 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29812}
813
[email protected]d202a7c2012-01-04 07:53:47814NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00815 // The NavigationControllerImpl might be called inside its delegate
816 // destructor. Calling it is not valid anymore.
817 delegate_ = nullptr;
818 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29819}
820
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57821BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55822 return browser_context_;
823}
824
[email protected]d202a7c2012-01-04 07:53:47825void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30826 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36827 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57828 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47829 // Note that it's possible for `entries_` to contain multiple entries at this
830 // point, as Restore() might be called on a NavigationController that is
831 // already used (e.g. due to WebView's restoreState() API), not only for fresh
832 // NavigationControllers. These entries are not cleared to preserve legacy
833 // behavior and also because `pending_entry_` might point to one of the
834 // pre-existing entries. An exception for this is when `entries_` contains
835 // only the initial NavigationEntry, which must be removed.
836
837 // Do not proceed if selected_navigation will be out of bounds for the updated
838 // entries_ list, since it will be assigned to last_committed_entry_index_ and
839 // used to index entries_.
Alison Gale770f3fc2024-04-27 00:39:58840 // TODO(crbug.com/40816356): Consider also returning early if entries
Charlie Reis23c26da2022-01-29 00:57:47841 // is empty, since there should be no work to do (rather than marking the
842 // existing entries as needing reload). Also consider returning early if the
843 // selected index is -1, which represents a no-committed-entry state.
844 if (selected_navigation < -1 ||
845 selected_navigation >=
846 base::checked_cast<int>(entries->size() + entries_.size())) {
847 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24848 }
Charlie Reis23c26da2022-01-29 00:57:47849
Rakina Zata Amni46087a12022-11-11 08:28:38850 // There will always be at least one entry (new NavigationControllers will
851 // have the initial NavigationEntry).
852 if (selected_navigation == -1)
853 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47854
Rakina Zata Amni46087a12022-11-11 08:28:38855 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
856 // If we are on the initial NavigationEntry, it must be the only entry in
857 // the list. Since it's impossible to do a history navigation to the
858 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
859 // `pending_entry` might be set for a new non-history navigation).
860 // Note that we should not clear `entries_` if `entries` is empty (when
861 // InitialNavigationEntry mode is enabled), since that would leave us
862 // without any NavigationEntry.
863 CHECK_EQ(1, GetEntryCount());
864 CHECK_EQ(-1, pending_entry_index_);
865 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47866 }
[email protected]ce3fa3c2009-04-20 19:55:57867
[email protected]ce3fa3c2009-04-20 19:55:57868 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44869 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03870 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47871 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43872 if (entry->GetURL().is_empty()) {
873 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01874 // persisting the initial NavigationEntry [which is no longer possible but
875 // some old persisted sessions might still contain it] or when the
876 // serializer failed to write the URL because it's too long). Trying to
877 // restore and navigate to an entry with an empty URL will result in
878 // crashes, so change the URL to about:blank. See also
879 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43880 entry->SetURL(GURL(url::kAboutBlankURL));
881 }
dcheng36b6aec92015-12-26 06:16:36882 entries_.push_back(
883 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47884 }
avif16f85a72015-11-13 18:25:03885
886 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
887 // cleared out safely.
888 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57889
890 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36891 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57892}
893
toyoshim6142d96f2016-12-19 09:07:25894void NavigationControllerImpl::Reload(ReloadType reload_type,
895 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03896 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
897 (int)reload_type);
898 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
899 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28900 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28901 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32902 int current_index = -1;
903
Carlos IL42b416592019-10-07 23:10:36904 if (entry_replaced_by_post_commit_error_) {
905 // If there is an entry that was replaced by a currently active post-commit
906 // error navigation, this can't be the initial navigation.
907 DCHECK(!IsInitialNavigation());
908 // If the current entry is a post commit error, we reload the entry it
909 // replaced instead. We leave the error entry in place until a commit
910 // replaces it, but the pending entry points to the original entry in the
911 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
912 // case that pending_entry_ != entries_[pending_entry_index_].
913 entry = entry_replaced_by_post_commit_error_.get();
914 current_index = GetCurrentEntryIndex();
915 } else if (IsInitialNavigation() && pending_entry_) {
916 // If we are reloading the initial navigation, just use the current
917 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32918 entry = pending_entry_;
919 // The pending entry might be in entries_ (e.g., after a Clone), so we
920 // should also update the current_index.
921 current_index = pending_entry_index_;
922 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00923 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32924 current_index = GetCurrentEntryIndex();
925 if (current_index != -1) {
creis3da03872015-02-20 21:12:32926 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32927 }
[email protected]979a4bc2013-04-24 01:27:15928 }
[email protected]241db352013-04-22 18:04:05929
[email protected]59167c22013-06-03 18:07:32930 // If we are no where, then we can't reload. TODO(darin): We should add a
931 // CanReload method.
932 if (!entry)
933 return;
934
Rakina Zata Amnif297a802022-01-18 03:53:43935 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
936 // We should never navigate to an existing initial NavigationEntry that is
937 // the initial NavigationEntry for the initial empty document that hasn't
938 // been overridden by the synchronous about:blank commit, to preserve
939 // legacy behavior where trying to reload when the main frame is on the
940 // initial empty document won't result in a navigation. See also
941 // https://crbug.com/1277414.
942 return;
943 }
944
Aran Gilman37d11632019-10-08 23:07:15945 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30946 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07947 // they really want to do this. If they do, the dialog will call us back
948 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57949 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02950
[email protected]106a0812010-03-18 00:15:12951 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57952 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47953 return;
initial.commit09911bf2008-07-26 23:55:29954 }
Lei Zhang96031532019-10-10 19:05:47955
Wang Huia25efabc2022-09-24 17:27:22956 // Set ReloadType for |entry|.
957 entry->set_reload_type(reload_type);
958
Lei Zhang96031532019-10-10 19:05:47959 if (!IsInitialNavigation())
960 DiscardNonCommittedEntries();
961
962 pending_entry_ = entry;
963 pending_entry_index_ = current_index;
964 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
965
Nate Chapin45f620582021-09-30 17:45:43966 // location.reload() goes through BeginNavigation, so all reloads triggered
967 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13968 NavigateToExistingPendingEntry(
969 reload_type,
970 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:37971 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:13972 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29973}
974
[email protected]d202a7c2012-01-04 07:53:47975void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48976 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12977}
978
[email protected]d202a7c2012-01-04 07:53:47979void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49980 // If the pending reload type has been cleared by another navigation
981 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48982 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49983 return;
[email protected]106a0812010-03-18 00:15:12984 }
Wang Hui96ab1012022-10-11 02:05:49985 Reload(pending_reload_, false);
986 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12987}
988
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57989bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09990 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11991}
992
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57993bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38994 // Check that we're on the initial NavigationEntry and that this is not a
995 // cloned tab.
996 return IsInitialNavigation() && GetEntryCount() == 1 &&
997 GetLastCommittedEntry()->IsInitialEntry() &&
998 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40999}
1000
Aran Gilman37d11632019-10-08 23:07:151001NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1002 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581003 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031004 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581005}
1006
Adithya Srinivasan9b0c99c2021-08-10 15:19:451007NavigationEntryImpl*
1008NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1009 int nav_entry_id) const {
1010 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1011 if (entry)
1012 return entry;
1013 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521014 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451015 : nullptr;
1016}
1017
W. James MacLeanc07dc41b2022-07-25 18:52:161018void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571019 const url::Origin& origin) {
1020 for (int i = 0; i < GetEntryCount(); i++) {
1021 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161022 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571023 }
1024 if (entry_replaced_by_post_commit_error_) {
1025 // It's possible we could come back to this entry if the error
1026 // page/interstitial goes away.
1027 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161028 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571029 }
W. James MacLean1c40862c2020-04-27 21:05:571030}
1031
avi25764702015-06-23 15:43:371032void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571033 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001034 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371035 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271036 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201037}
1038
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571039NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471040 if (pending_entry_)
1041 return pending_entry_;
1042 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201043}
1044
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571045NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321046 // The pending entry is safe to return for new (non-history), browser-
1047 // initiated navigations. Most renderer-initiated navigations should not
1048 // show the pending entry, to prevent URL spoof attacks.
1049 //
1050 // We make an exception for renderer-initiated navigations in new tabs, as
1051 // long as no other page has tried to access the initial empty document in
1052 // the new tab. If another page modifies this blank page, a URL spoof is
1053 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321054 bool safe_to_show_pending =
1055 pending_entry_ &&
1056 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091057 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321058 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461059 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321060
1061 // Also allow showing the pending entry for history navigations in a new tab,
1062 // such as Ctrl+Back. In this case, no existing page is visible and no one
1063 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151064 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1065 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321066 safe_to_show_pending = true;
1067
1068 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191069 return pending_entry_;
1070 return GetLastCommittedEntry();
1071}
1072
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571073int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201074 if (pending_entry_index_ != -1)
1075 return pending_entry_index_;
1076 return last_committed_entry_index_;
1077}
1078
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571079NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381080 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031081 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201082}
1083
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571084bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351085 const std::string& mime_type = frame_tree_->root()
1086 ->current_frame_host()
1087 ->GetPage()
1088 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531089 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1090 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271091 NavigationEntry* visible_entry = GetVisibleEntry();
1092 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391093 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161094}
1095
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571096int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271097 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451098 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271099 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551100 return last_committed_entry_index_;
1101}
1102
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571103int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451104 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291105 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551106 return static_cast<int>(entries_.size());
1107}
1108
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571109NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371110 if (index < 0 || index >= GetEntryCount())
1111 return nullptr;
1112
avif16f85a72015-11-13 18:25:031113 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251114}
1115
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571116NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471117 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201118}
1119
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571120int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461121 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031122}
1123
Arthur Sonzognic686e8f2024-01-11 08:36:371124std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031125 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591126 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1127 return index;
1128 }
Shivani Sharma298d12852019-01-22 20:04:031129 }
Arthur Sonzognic686e8f2024-01-11 08:36:371130 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591131}
1132
1133bool NavigationControllerImpl::CanGoBack() {
1134 return GetIndexForGoBack().has_value();
1135}
1136
Arthur Sonzognic686e8f2024-01-11 08:36:371137std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591138 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1139 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1140 return index;
1141 }
1142 }
Arthur Sonzognic686e8f2024-01-11 08:36:371143 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201144}
1145
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571146bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591147 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201148}
1149
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571150bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031151 int index = GetIndexForOffset(offset);
1152 return index >= 0 && index < GetEntryCount();
1153}
1154
Xiaohan Wang7f8052e02022-01-14 18:44:281155#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151156bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151157 if (offset == 0)
1158 return true;
1159 int increment = offset > 0 ? 1 : -1;
1160 int non_skippable_entries = 0;
1161 for (int index = GetIndexForOffset(increment);
1162 index >= 0 && index < GetEntryCount(); index += increment) {
1163 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1164 non_skippable_entries++;
1165
1166 if (non_skippable_entries == std::abs(offset))
1167 return true;
1168 }
1169 return false;
1170}
1171#endif
1172
[email protected]d202a7c2012-01-04 07:53:471173void NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371174 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061175
Kevin McNeeedc481c2023-04-27 22:30:581176 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211177
Kevin McNee3b3a56192023-03-17 14:40:591178 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201179}
1180
[email protected]d202a7c2012-01-04 07:53:471181void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161182 // Note that at least one entry (the last one) will be non-skippable since
1183 // entries are marked skippable only when they add another entry because of
1184 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371185 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591186
Kevin McNeeedc481c2023-04-27 22:30:581187 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591188
1189 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201190}
1191
[email protected]d202a7c2012-01-04 07:53:471192void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131193 GoToIndex(index, /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371194 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:131195 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161196}
1197
William Liu62ae26c2024-08-08 14:28:161198std::vector<base::WeakPtr<NavigationRequest>>
1199NavigationControllerImpl::GoToIndex(
Nate Chapinbf682fa32022-09-26 22:41:201200 int index,
1201 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371202 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131203 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201204 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441205 TRACE_EVENT0("browser,navigation,benchmark",
1206 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501207 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1208 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1209 entries_.size());
1210 // Indices should have have been validated by the caller.
1211 CHECK_GE(index, 0);
1212 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201213
Rakina Zata Amnif297a802022-01-18 03:53:431214 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1215 // We should never navigate to an existing initial NavigationEntry that is
1216 // the initial NavigationEntry for the initial empty document that hasn't
1217 // been overridden by the synchronous about:blank commit, to preserve
1218 // legacy behavior where trying to reload when the main frame is on the
1219 // initial empty document won't result in a navigation. See also
1220 // https://crbug.com/1277414.
William Liu62ae26c2024-08-08 14:28:161221 return {};
Rakina Zata Amnif297a802022-01-18 03:53:431222 }
1223
[email protected]cbab76d2008-10-13 22:42:471224 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201225
arthursonzogni5c4c202d2017-04-25 23:41:271226 DCHECK_EQ(nullptr, pending_entry_);
1227 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431228
arthursonzogni5c4c202d2017-04-25 23:41:271229 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201230 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271231 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1232 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
William Liuec04e382024-05-23 18:03:271233 return NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
1234 soft_navigation_heuristics_task_id,
1235 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201236}
1237
[email protected]d202a7c2012-01-04 07:53:471238void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121239 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031240 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201241 return;
1242
[email protected]9ba14052012-06-22 23:50:031243 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201244}
1245
Nate Chapinbf682fa32022-09-26 22:41:201246void NavigationControllerImpl::GoToOffsetFromRenderer(
1247 int offset,
Yoav Weiss8c573952022-11-17 17:35:131248 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371249 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131250 soft_navigation_heuristics_task_id) {
Nate Chapinbb74c5a52023-07-21 23:13:351251 // Note: This is actually reached in unit tests.
1252 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431253 return;
1254
Nate Chapinbf682fa32022-09-26 22:41:201255 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131256 soft_navigation_heuristics_task_id,
1257 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431258}
1259
William Liu62ae26c2024-08-08 14:28:161260std::vector<base::WeakPtr<NavigationRequest>>
1261NavigationControllerImpl::GoToIndexAndReturnAllRequests(int index) {
William Liuec04e382024-05-23 18:03:271262 return GoToIndex(index, /*initiator_rfh=*/nullptr,
1263 /*soft_navigation_heuristics_task_id=*/std::nullopt,
1264 /*navigation_api_key=*/nullptr);
1265}
1266
Xiaohan Wang7f8052e02022-01-14 18:44:281267#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151268void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1269 // Note: This is actually reached in unit tests.
1270 if (!CanGoToOffsetWithSkipping(offset))
1271 return;
1272
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421273 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151274 GoToIndex(GetIndexForOffset(offset));
1275 return;
1276 }
1277 int increment = offset > 0 ? 1 : -1;
1278 // Find the offset without counting skippable entries.
1279 int target_index = GetIndexForOffset(increment);
1280 int non_skippable_entries = 0;
1281 for (int index = target_index; index >= 0 && index < GetEntryCount();
1282 index += increment) {
1283 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1284 non_skippable_entries++;
1285
1286 if (non_skippable_entries == std::abs(offset)) {
1287 target_index = index;
1288 break;
1289 }
1290 }
1291
1292 GoToIndex(target_index);
1293}
1294#endif
1295
[email protected]41374f12013-07-24 02:49:281296bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151297 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281298 return false;
[email protected]6a13a6c2011-12-20 21:47:121299
[email protected]43032342011-03-21 14:10:311300 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281301 return true;
[email protected]cbab76d2008-10-13 22:42:471302}
1303
Michael Thiessen9b14d512019-09-23 21:19:471304void NavigationControllerImpl::PruneForwardEntries() {
1305 DiscardNonCommittedEntries();
1306 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471307 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471308 if (num_removed <= 0)
1309 return;
Nate Chapin9eb16be72022-09-23 22:54:311310 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471311 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1312 NotifyPrunedEntries(this, remove_start_index /* start index */,
1313 num_removed /* count */);
1314}
1315
Aran Gilman37d11632019-10-08 23:07:151316void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1317 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321318 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311319 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511320 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1321 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321322 }
1323}
1324
Harkiran Bolariaba823e42021-05-21 18:30:361325base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1326 const GURL& url,
1327 const Referrer& referrer,
1328 ui::PageTransition transition,
1329 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471330 LoadURLParams params(url);
1331 params.referrer = referrer;
1332 params.transition_type = transition;
1333 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361334 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471335}
1336
Harkiran Bolariaba823e42021-05-21 18:30:361337base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1338 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061339 if (params.is_renderer_initiated)
1340 DCHECK(params.initiator_origin.has_value());
1341
naskob8744d22014-08-28 17:07:431342 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151343 "NavigationControllerImpl::LoadURLWithParams", "url",
1344 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291345 bool is_explicit_navigation =
1346 GetContentClient()->browser()->IsExplicitNavigation(
1347 params.transition_type);
1348 if (HandleDebugURL(params.url, params.transition_type,
1349 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431350 // If Telemetry is running, allow the URL load to proceed as if it's
1351 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491352 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
Peter Kasting6e6af3c2024-10-15 00:13:181353 switches::kEnableGpuBenchmarking)) {
Harkiran Bolariaba823e42021-05-21 18:30:361354 return nullptr;
Peter Kasting6e6af3c2024-10-15 00:13:181355 }
[email protected]47752982014-07-29 08:01:431356 }
[email protected]8bf1048012012-02-08 01:22:181357
[email protected]cf002332012-08-14 19:17:471358 // Checks based on params.load_type.
1359 switch (params.load_type) {
1360 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431361 case LOAD_TYPE_HTTP_POST:
Shu Yang112ad492024-07-25 17:11:541362#if BUILDFLAG(IS_ANDROID)
1363 case LOAD_TYPE_PDF_ANDROID:
1364#endif
[email protected]cf002332012-08-14 19:17:471365 break;
1366 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261367 if (!params.url.SchemeIs(url::kDataScheme)) {
Peter Boström8472105d2024-05-15 04:36:021368 NOTREACHED_IN_MIGRATION() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361369 return nullptr;
[email protected]cf002332012-08-14 19:17:471370 }
1371 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461372 }
[email protected]e47ae9472011-10-13 19:48:341373
[email protected]e47ae9472011-10-13 19:48:341374 // The user initiated a load, we don't need to reload anymore.
1375 needs_reload_ = false;
1376
Harkiran Bolariaba823e42021-05-21 18:30:361377 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441378}
1379
Charlie Reis4c53a962023-06-21 23:17:531380void NavigationControllerImpl::LoadOriginalRequestURL() {
1381 // If the original request URL is not valid, matches the current URL, or
1382 // involves POST data, then simply reload. The POST check avoids issues with
1383 // sending data to the wrong page.
1384 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1385 const GURL& original_request_url =
1386 GetLastCommittedEntry()->GetOriginalRequestURL();
1387 if (!original_request_url.is_valid() ||
1388 original_request_url == last_committed_url ||
1389 GetLastCommittedEntry()->GetHasPostData()) {
1390 Reload(ReloadType::NORMAL, true);
1391 return;
1392 }
1393
1394 // Otherwise, attempt to load the original request URL without any of the
1395 // other data from the current NavigationEntry, replacing the current entry.
1396 // Loading the original URL is useful in cases such as modifying the user
1397 // agent.
1398 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1399 std::make_unique<NavigationController::LoadURLParams>(
1400 original_request_url);
1401 load_params->should_replace_current_entry = true;
1402 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1403 LoadURLWithParams(*load_params.get());
1404}
1405
Mohamed Abdelhalim833de902019-09-16 17:41:451406bool NavigationControllerImpl::PendingEntryMatchesRequest(
1407 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191408 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451409 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191410}
1411
[email protected]d202a7c2012-01-04 07:53:471412bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321413 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071414 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331415 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441416 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251417 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561418 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131419 NavigationRequest* navigation_request) {
1420 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331421
1422 // Note: validation checks and renderer kills due to invalid commit messages
1423 // must happen before getting here, in
1424 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1425 // effects of the navigation have already occurred.
1426
[email protected]cd2e15742013-03-08 04:08:311427 is_initial_navigation_ = false;
1428
Wang Hui96ab1012022-10-11 02:05:491429 // Any pending request to repost a form submission is no longer valid, since a
1430 // different NavigationEntry is committing.
1431 pending_reload_ = ReloadType::NONE;
1432
[email protected]0e8db942008-09-24 21:21:481433 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431434 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451435 if (entry_replaced_by_post_commit_error_) {
1436 // Same document navigation events with a post-commit error should already
1437 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1438 // reaching here.
1439 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331440
Xinghui Lub9e86a352024-05-17 16:29:421441 if (pending_entry_) {
1442 // Before `entry_replaced_by_post_commit_error_` is moved back, make sure
1443 // `pending_entry_` isn't pointing to the last committed entry.
1444 // Instead, all reload approaches (e.g., in `Reload` and
1445 // `LoadIfNecessary`) should attempt to load the
1446 // `entry_replaced_by_post_commit_error_` instead of the post commit error
1447 // entry itself.
1448 CHECK_NE(pending_entry_, entries_[last_committed_entry_index_].get())
1449 << "Incorrectly reloading the post commit error page entry.";
1450 }
Xinghui Lue4e50be2024-05-15 21:46:001451
Rakina Zata Amnie2d31312022-11-18 03:38:451452 // Any commit while a post-commit error page is showing should put the
1453 // original entry back, replacing the error page's entry. This includes
1454 // reloads, where the original entry was used as the pending entry and
1455 // should now be at the correct index at commit time.
1456 entries_[last_committed_entry_index_] =
1457 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481458 }
Rakina Zata Amnie2d31312022-11-18 03:38:451459 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1460 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001461 // Must honor user agent overrides in the |navigation_request|, such as
1462 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1463 // result, besides comparing |pending_entry_|'s user agent against
1464 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1465 // agent against LastCommittedEntry's.
1466 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541467 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1468 (PendingEntryMatchesRequest(navigation_request) &&
1469 pending_entry_->GetIsOverridingUserAgent() !=
1470 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001471 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451472 }
[email protected]ecd9d8702008-08-28 22:10:171473
Dave Tapuskaa2ab4f252021-07-08 21:31:281474 bool is_main_frame_navigation = !rfh->GetParent();
1475
Alexander Timind2f2e4f22019-04-02 20:04:531476 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1477 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281478 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141479 // BackForwardCacheMetrics to be associated with the new navigation's
1480 // NavigationEntry, by either creating a new object or reusing the previous
1481 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281482 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211483 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141484 back_forward_cache_metrics = BackForwardCacheMetrics::
1485 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281486 GetLastCommittedEntry(), is_main_frame_navigation,
1487 params.document_sequence_number);
1488 }
Yuzu Saijo29f96ca92022-12-08 04:54:121489
Alexander Timind2f2e4f22019-04-02 20:04:531490 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281491 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451492 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1493 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531494 }
1495 }
1496
Rakina Zata Amnifd8370b2022-11-14 13:32:251497 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1498 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091499 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251500 details->did_replace_entry =
1501 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091502
fdegans9caf66a2015-07-30 21:10:421503 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111504 // except for restored entries. This should be true even if the current commit
1505 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291506 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481507 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081508 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111509
1510 // Only make changes based on the pending entry if the NavigationRequest
1511 // matches it. Otherwise, the pending entry may be for a different request
1512 // (e.g., if a slow history navigation is pending while an auto-subframe
1513 // commit occurs).
1514 if (PendingEntryMatchesRequest(navigation_request)) {
1515 // It is no longer necessary to consider the pending entry as restored.
1516 if (pending_entry_->IsRestored()) {
1517 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1518 was_restored = true;
1519 }
[email protected]e9ba4472008-09-14 15:42:431520
Charlie Reisf8cde712022-10-20 16:25:091521 // If the SiteInstance has changed from the matching pending entry, this
1522 // must be treated as a new navigation with replacement. Set the replacement
1523 // bit here and ClassifyNavigation will identify this case and return
1524 // NEW_ENTRY.
1525 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1526 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1527 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251528 // TODO(nasko,creis,rakina): Move this to happen before committing the
1529 // navigation. This is a bit complicated because we don't currently
1530 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091531 details->did_replace_entry = true;
1532 }
Nasko Oskovaee2f862018-06-15 00:05:521533 }
[email protected]bcd904482012-02-01 01:54:221534
[email protected]e9ba4472008-09-14 15:42:431535 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101536 NavigationType navigation_type =
1537 ClassifyNavigation(rfh, params, navigation_request);
1538 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451539
Rakina Zata Amnie2d31312022-11-18 03:38:451540 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451541 // Ensure that this navigation does not add a navigation entry, since
1542 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1543 // beyond the last committed one. Therefore, `should_replace_current_entry`
1544 // should be set, which replaces the current entry, or this should be a
1545 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251546 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331547 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451548 }
1549
Rakina Zata Amnie2d31312022-11-18 03:38:451550 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551551 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241552 // This is a subframe navigation on the initial empty document, which used
1553 // to not have a NavigationEntry to attach to. Now it can attach to the
1554 // initial NavigationEntry, and we must ensure that its NavigationEntry
1555 // will keep the "initial NavigationEntry" status and won't append a new
1556 // NavigationEntry (it should always do replacement instead).
1557 // See also https://crbug.com/1277414.
1558 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551559 // Subframe navigation on initial NavigationEntry must not append a new
1560 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1561 // means every subframe navigation that happens while we're on the initial
1562 // NavigationEntry will always reuse the existing NavigationEntry and
1563 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101564 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1565 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551566 // This is a navigation that modifies the initial NavigationEntry, either
1567 // for a replacement or a reload. The initial NavigationEntry should
1568 // retain its "initial NavigationEntry" status in this case.
1569 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241570 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251571 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1572 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241573 // This is a synchronous about:blank navigation on the main frame, which
1574 // used to not create a NavigationEntry when we have no NavigationEntry on
1575 // FrameTree creation. We now have the initial NavigationEntry and are on
1576 // the initial NavigationEntry. To preserve old behavior, we should still
1577 // keep the "initial" status for the new NavigationEntry that we will
1578 // create for this navigation, so that subframe navigations under the
1579 // synchronously committed about:blank document will never append new
1580 // NavigationEntry, and instead will just reuse the initial
1581 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1582 // See also https://crbug.com/1277414.
1583 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551584 }
1585 }
1586 DCHECK(!details->should_stay_as_initial_entry ||
1587 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201588
eugenebutee08663a2017-04-27 17:43:121589 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441590 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121591
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071592 details->is_prerender_activation =
1593 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241594 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1595 ->GetOutermostMainFrame()
1596 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071597
Peter Boströmd7592132019-01-30 04:50:311598 // Make sure we do not discard the pending entry for a different ongoing
1599 // navigation when a same document commit comes in unexpectedly from the
1600 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1601 // other navigation types. See https://crbug.com/900036.
Alison Gale770f3fc2024-04-27 00:39:581602 // TODO(crbug.com/41437754): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061603 bool keep_pending_entry =
1604 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101605 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061606 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311607
Miyoung Shin3299cbf2022-11-22 01:41:101608 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061609 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491610 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051611 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561612 previous_document_had_history_intervention_activation,
1613 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431614 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061615 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491616 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1617 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001618 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431619 break;
[email protected]8ff00d72012-10-23 19:12:211620 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471621 RendererDidNavigateNewSubframe(
1622 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561623 previous_document_had_history_intervention_activation,
1624 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431625 break;
[email protected]8ff00d72012-10-23 19:12:211626 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391627 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251628 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001629 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081630 // We don't send a notification about auto-subframe PageState during
1631 // UpdateStateForFrame, since it looks like nothing has changed. Send
1632 // it here at commit time instead.
1633 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431634 return false;
creis59d5a47cb2016-08-24 23:57:191635 }
[email protected]e9ba4472008-09-14 15:42:431636 break;
Aran Gilman37d11632019-10-08 23:07:151637 case NAVIGATION_TYPE_UNKNOWN:
Peter Boström8472105d2024-05-15 04:36:021638 NOTREACHED_IN_MIGRATION();
Aran Gilman37d11632019-10-08 23:07:151639 break;
[email protected]765b35502008-08-21 00:51:201640 }
1641
[email protected]688aa65c62012-09-28 04:32:221642 // At this point, we know that the navigation has just completed, so
1643 // record the time.
1644 //
1645 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261646 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331647 base::Time timestamp =
1648 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1649 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131650 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221651
Peter Boströmd7592132019-01-30 04:50:311652 // If we aren't keeping the pending entry, there shouldn't be one at this
1653 // point. Clear it again in case any error cases above forgot to do so.
1654 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1655 // been cleared instead of protecting against it.
1656 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551657 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141658
[email protected]e9ba4472008-09-14 15:42:431659 // All committed entries should have nonempty content state so WebKit doesn't
1660 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471661 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321662 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221663 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441664 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141665
Alexander Timind2f2e4f22019-04-02 20:04:531666 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1667 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281668 if (back_forward_cache_metrics &&
1669 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531670 active_entry->set_back_forward_cache_metrics(
1671 std::move(back_forward_cache_metrics));
1672 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281673
1674 // `back_forward_cache_metrics()` may return null as we do not record
1675 // back-forward cache metrics for navigations in non-primary frame trees.
1676 if (active_entry->back_forward_cache_metrics()) {
Alison Gale770f3fc2024-04-27 00:39:581677 // TODO(crbug.com/40229455): Remove this.
Fergal Daly0686c0e2022-06-28 02:08:141678 // These are both only available from details at this point, so we capture
1679 // them here.
1680 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101681 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141682 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1683 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281684 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1685 navigation_request,
Rakina Zata Amni84a859df2024-06-07 15:56:321686 IsBackForwardCacheEnabled() &&
1687 rfh->delegate()->IsBackForwardCacheSupported() &&
1688 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
Dave Tapuskaa2ab4f252021-07-08 21:31:281689 }
naskoc7533512016-05-06 17:01:121690
Charles Reisc0507202017-09-21 00:40:021691 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1692 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1693 // A mismatch can occur if the renderer lies or due to a unique name collision
1694 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121695 FrameNavigationEntry* frame_entry =
1696 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021697 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1698 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031699 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081700 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1701 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031702 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201703
1704 // Remember the bindings the renderer process has at this point, so that
1705 // we do not grant this entry additional bindings if we come back to it.
1706 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301707 }
[email protected]132e281a2012-07-31 18:32:441708
[email protected]97d8f0d2013-10-29 16:49:211709 // Once it is committed, we no longer need to track several pieces of state on
1710 // the entry.
naskoc7533512016-05-06 17:01:121711 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131712
[email protected]49bd30e62011-03-22 20:12:591713 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221714 // TODO(creis): This check won't pass for subframes until we create entries
1715 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001716 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421717 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591718
[email protected]e9ba4472008-09-14 15:42:431719 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001720 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001721 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311722 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531723
arthursonzogni7ddc6542021-04-09 09:16:501724 active_entry->SetIsOverridingUserAgent(
1725 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031726
[email protected]93f230e02011-06-01 14:40:001727 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291728
aelias100c9192017-01-13 00:01:431729 if (overriding_user_agent_changed)
1730 delegate_->UpdateOverridingUserAgent();
1731
creis03b48002015-11-04 00:54:561732 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1733 // one knows the latest NavigationEntry it is showing (whether it has
1734 // committed anything in this navigation or not). This allows things like
1735 // state and title updates from RenderFrames to apply to the latest relevant
1736 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381737 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031738 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381739 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431740
1741 if (navigation_request->IsPrerenderedPageActivation()) {
1742 BroadcastHistoryOffsetAndLength();
Alison Gale47d1537d2024-04-19 21:31:461743 // TODO(crbug.com/40187392): Broadcasting happens after the prerendered page
Hayato Ito2c8c08d02021-06-23 03:38:431744 // is activated. As a result, a "prerenderingchange" event listener sees the
1745 // history.length which is not updated yet. We should guarantee that
1746 // history's length and offset should be updated before a
1747 // "prerenderingchange" event listener runs. One possible approach is to use
1748 // the same IPC which "prerenderingchange" uses, and propagate history's
1749 // length and offset together with that.
1750 }
1751
[email protected]e9ba4472008-09-14 15:42:431752 return true;
initial.commit09911bf2008-07-26 23:55:291753}
1754
[email protected]8ff00d72012-10-23 19:12:211755NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321756 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101757 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241758 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591759 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511760 "ClassifyNavigation");
1761
avi7c6f35e2015-05-08 17:52:381762 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241763 // A new entry. We may or may not have a corresponding pending entry, and
1764 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001765 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491766 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061767 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381768 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241769 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511770 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381771 return NAVIGATION_TYPE_NEW_SUBFRAME;
1772 }
1773
Charlie Reisc0f17d2d2021-01-12 18:52:491774 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381775 DCHECK(!params.history_list_was_cleared);
1776
avi39c1edd32015-06-04 20:06:001777 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381778 // All manual subframes would be did_create_new_entry and handled above, so
1779 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081780 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1781 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381782 }
1783
Rakina Zata Amnif6950d552020-11-24 03:26:101784 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1785 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381786 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1787 // create a new page.
1788
Hayato Ito2ae49442021-07-02 02:59:251789 // This main frame navigation is not a history navigation (since
1790 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1791 // reload or a replacement navigation, which will modify the existing entry.
1792 //
Nasko Oskov332593c2018-08-16 17:21:341793 // TODO(nasko): With error page isolation, reloading an existing session
1794 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491795 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341796 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511797 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491798 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061799 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381800 }
1801
Charlie Reisf8cde712022-10-20 16:25:091802 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521803 // If the SiteInstance of the |pending_entry_| does not match the
1804 // SiteInstance that got committed, treat this as a new navigation with
1805 // replacement. This can happen if back/forward/reload encounters a server
1806 // redirect to a different site or an isolated error page gets successfully
1807 // reloaded into a different SiteInstance.
1808 if (pending_entry_->site_instance() &&
1809 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491810 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061811 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521812 }
creis77c9aa32015-09-25 19:59:421813
Nasko Oskovaee2f862018-06-15 00:05:521814 if (pending_entry_index_ == -1) {
1815 // In this case, we have a pending entry for a load of a new URL but Blink
1816 // didn't do a new navigation (params.did_create_new_entry). First check
1817 // to make sure Blink didn't treat a new cross-process navigation as
1818 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161819 // we must treat it as NEW rather than the converted reload case below,
1820 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451821 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161822 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061823 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521824 }
1825
1826 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161827 // We will create a pending entry, but NavigateWithoutEntry will convert
1828 // it to a reload since it's the same page and not create a new entry for
1829 // it. (The user doesn't want to have a new back/forward entry when they
1830 // do this.) Therefore we want to just ignore the pending entry and go
1831 // back to where we were (the "existing entry").
1832 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061833 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521834 }
avi7c6f35e2015-05-08 17:52:381835 }
1836
Rakina Zata Amni153d5702021-09-13 22:48:001837 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381838 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491839 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1840 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161841 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061842 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381843 }
1844
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121845 if (navigation_request->DidEncounterError() &&
1846 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101847 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381848 // If the renderer was going to a new pending entry that got cleared because
1849 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491850 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381851 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511852 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491853 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061854 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381855 }
1856
Charlie Reisc0f17d2d2021-01-12 18:52:491857 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101858 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511859 trace_return.traced_value()->SetInteger("existing_entry_index",
1860 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381861 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441862 // The renderer has committed a navigation to an entry that no longer
1863 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491864 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061865 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381866 }
1867
avi7c6f35e2015-05-08 17:52:381868 // Since we weeded out "new" navigations above, we know this is an existing
1869 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491870 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061871 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381872}
1873
Rakina Zata Amni3460d382021-10-29 00:43:371874void NavigationControllerImpl::UpdateNavigationEntryDetails(
1875 NavigationEntryImpl* entry,
1876 RenderFrameHostImpl* rfh,
1877 const mojom::DidCommitProvisionalLoadParams& params,
1878 NavigationRequest* request,
1879 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001880 bool is_new_entry,
1881 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371882 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171883 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371884 entry->AddOrUpdateFrameEntry(
1885 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571886 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371887 rfh->GetSiteInstance(), nullptr, params.url,
1888 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171889 Referrer(*params.referrer),
1890 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371891 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171892 request ? request->GetRedirectChain() : redirects, params.page_state,
1893 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371894 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171895 rfh, request && request->IsSameDocument(),
Antonio Sartorib8addf62024-09-16 07:59:211896 request ? request->DidEncounterError() : false,
Rakina Zata Amniafd3c6582021-11-30 06:19:171897 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371898
1899 if (rfh->GetParent()) {
1900 // Only modify the NavigationEntry for main frame navigations.
1901 return;
1902 }
1903 if (entry->update_virtual_url_with_url())
1904 UpdateVirtualURLToURL(entry, params.url);
1905 // Don't use the page type from the pending entry. Some interstitial page
1906 // may have set the type to interstitial. Once we commit, however, the page
1907 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171908 entry->set_page_type((request && request->DidEncounterError())
1909 ? PAGE_TYPE_ERROR
1910 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431911 if (commit_details && commit_details->should_stay_as_initial_entry) {
1912 // Retain the "initial NavigationEntry" status.
1913 if (request->IsSameDocument()) {
1914 // If this is for a same-document navigation, the NavigationEntry must be
1915 // reused and should already be marked as the initial NavigationEntry.
1916 DCHECK(entry->IsInitialEntry());
1917 } else {
1918 // If this is for a cross-document navigation, it can be caused by a
1919 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1920 // "for synchronous about:blank" in the latter case, and also when it is
1921 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1922 // is not for a synchronous about:blank commit.
1923 NavigationEntryImpl::InitialNavigationEntryState new_state =
1924 NavigationEntryImpl::InitialNavigationEntryState::
1925 kInitialNotForSynchronousAboutBlank;
1926 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1927 request->is_synchronous_renderer_commit()) {
1928 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1929 kInitialForSynchronousAboutBlank;
1930 }
1931 entry->set_initial_navigation_entry_state(new_state);
1932 }
1933 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1934 // Remove the "initial NavigationEntry" status.
1935 entry->set_initial_navigation_entry_state(
1936 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001937 }
Rakina Zata Amniddf10502022-01-15 02:56:551938
Rakina Zata Amni3460d382021-10-29 00:43:371939 if (is_new_entry) {
1940 // Some properties of the NavigationEntry are only set when the entry is
1941 // new (we aren't reusing it).
1942 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171943 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:401944 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:011945 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
1946 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:371947 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1948 } else {
1949 // We are reusing the NavigationEntry. The site instance will normally be
1950 // the same except for a few cases:
1951 // 1) session restore, when no site instance will be assigned or
1952 // 2) redirect, when the site instance is reset.
1953 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1954 entry->site_instance() == rfh->GetSiteInstance());
1955 }
1956}
1957
Rakina Zata Amniafd3c6582021-11-30 06:19:171958void NavigationControllerImpl::CreateInitialEntry() {
1959 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031960 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171961 auto params = mojom::DidCommitProvisionalLoadParams::New();
1962 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1963 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1964 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:401965 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:171966 params->http_status_code = 0;
1967 params->url_is_unreachable = false;
1968 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171969 params->post_id = -1;
1970 params->embedding_token = base::UnguessableToken::Create();
1971 params->navigation_token = base::UnguessableToken::Create();
1972 params->did_create_new_entry = true;
1973 params->origin = rfh->GetLastCommittedOrigin();
1974 params->should_update_history = true;
1975 params->item_sequence_number = 0;
1976 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151977 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171978 params->transition = is_in_fenced_frame_tree
1979 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1980 : ui::PAGE_TRANSITION_LINK;
1981 params->referrer = blink::mojom::Referrer::New();
1982
Rakina Zata Amniafd3c6582021-11-30 06:19:171983 auto new_entry = std::make_unique<NavigationEntryImpl>(
1984 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381985 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211986 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1987 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1988 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171989 UpdateNavigationEntryDetails(
1990 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001991 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1992 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171993
1994 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1995 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001996 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171997}
1998
Charlie Reisc0f17d2d2021-01-12 18:52:491999void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:322000 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072001 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362002 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:442003 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562004 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002005 NavigationRequest* request,
2006 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:572007 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:372008 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452009 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372010 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522011 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2012 initiator_base_url = request->common_params().initiator_base_url;
2013 }
Lukasz Anforowicz435bcb582019-07-12 20:50:062014
creisf49dfc92016-07-26 17:05:182015 // First check if this is an in-page navigation. If so, clone the current
2016 // entry instead of looking at the pending entry, because the pending entry
2017 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:452018 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:302019 FrameNavigationEntry* previous_frame_entry =
2020 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:452021 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482022 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572023 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082024 rfh->GetSiteInstance(), nullptr, params.url,
2025 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212026 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092027 request->GetRedirectChain(), params.page_state, params.method,
2028 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392029 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302030 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572031 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302032 // FrameNavigationEntry.
2033 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572034 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032035
creisf49dfc92016-07-26 17:05:182036 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032037 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522038 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2039 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572040 // TODO(jam): we had one report of this with a URL that was redirecting to
2041 // only tildes. Until we understand that better, don't copy the cert in
2042 // this case.
2043 new_entry->GetSSL() = SSLStatus();
2044 }
creisf49dfc92016-07-26 17:05:182045
Patrick Monette50e8bd82019-06-13 22:40:452046 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2047 // that |frame_entry| should now have a reference count of exactly 2: one
2048 // due to the local variable |frame_entry|, and another due to |new_entry|
2049 // also retaining one. This should never fail, because it's the main frame.
2050 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182051 }
2052
Harkiran Bolaria59290d62021-03-17 01:53:012053 // If this is an activation navigation from a prerendered page, transfer the
2054 // new entry from an entry already created and stored in the
2055 // NavigationRequest. |new_entry| will not have been set prior to this as
2056 // |is_same_document| is mutually exclusive with
2057 // |IsPrerenderedPageActivation|.
2058 if (request->IsPrerenderedPageActivation()) {
2059 DCHECK(!is_same_document);
2060 DCHECK(!new_entry);
2061 new_entry = request->TakePrerenderNavigationEntry();
2062 DCHECK(new_entry);
2063 }
2064
Charlie Reisc0f17d2d2021-01-12 18:52:492065 // Only make a copy of the pending entry if it is appropriate for the new
2066 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452067 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042068 // 1. The SiteInstance hasn't been assigned to something else.
2069 // 2. The pending entry was intended as a new entry, rather than being a
2070 // history navigation that was interrupted by an unrelated,
2071 // renderer-initiated navigation.
2072 // TODO(csharrison): Investigate whether we can remove some of the coarser
2073 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452074 if (!new_entry && PendingEntryMatchesRequest(request) &&
2075 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342076 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432077 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352078 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432079
Camille Lamy62b826012019-02-26 09:15:472080 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452081 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182082 }
2083
Charlie Reisc0f17d2d2021-01-12 18:52:492084 // For cross-document commits with no matching pending entry, create a new
2085 // entry.
creisf49dfc92016-07-26 17:05:182086 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062087 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072088 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212089 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582090 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452091 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172092 nullptr, // blob_url_loader_factory
2093 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242094
2095 // Find out whether the new entry needs to update its virtual URL on URL
2096 // change and set up the entry accordingly. This is needed to correctly
2097 // update the virtual URL when replaceState is called after a pushState.
2098 GURL url = params.url;
2099 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492100 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412101 // update the virtual URL based on the new URL. For example, this is needed
2102 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2103 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372104 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2105 &url, browser_context_, &needs_update);
2106 new_entry->set_update_virtual_url_with_url(needs_update);
2107
Camille Lamy62b826012019-02-26 09:15:472108 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452109 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432110 }
2111
Alison Gale770f3fc2024-04-27 00:39:582112 // TODO(crbug.com/40169536) - determine which parts of the entry need to be
2113 // set for prerendered contents, if any. This is because
2114 // prerendering/activation technically won't be creating a new document.
2115 // Unlike BFCache, prerendering creates a new NavigationEntry rather than
2116 // using an existing one.
Harkiran Bolaria59290d62021-03-17 01:53:012117 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372118 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2119 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002120 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082121
Harkiran Bolaria59290d62021-03-17 01:53:012122 // history.pushState() is classified as a navigation to a new page, but sets
2123 // is_same_document to true. In this case, we already have the title and
2124 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452125 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012126 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2127 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2128 }
[email protected]3a868f212014-08-09 10:41:192129 }
[email protected]ff64b3e2014-05-31 04:07:332130
[email protected]60d6cca2013-04-30 08:47:132131 DCHECK(!params.history_list_was_cleared || !replace_entry);
2132 // The browser requested to clear the session history when it initiated the
2133 // navigation. Now we know that the renderer has updated its state accordingly
2134 // and it is safe to also clear the browser side history.
2135 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552136 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132137 entries_.clear();
2138 last_committed_entry_index_ = -1;
2139 }
2140
Nasko Oskovaee2f862018-06-15 00:05:522141 // If this is a new navigation with replacement and there is a
2142 // pending_entry_ which matches the navigation reported by the renderer
2143 // process, then it should be the one replaced, so update the
2144 // last_committed_entry_index_ to use it.
2145 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092146 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522147 last_committed_entry_index_ = pending_entry_index_;
2148 }
2149
Alexander Timine3ec4192020-04-20 16:39:402150 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562151 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402152 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052153
Yuzu Saijoa725585f2022-11-28 04:14:032154 // If this is a history navigation and the old entry has an existing
2155 // back/forward cache metrics object, keep using the old one so that the
2156 // reasons logged from the last time the page navigated gets preserved.
2157 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2158 request)) {
2159 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2160 // because some tests do not have a pending entry.
2161 NavigationEntryImpl* entry =
2162 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2163 if (entry && entry->back_forward_cache_metrics()) {
2164 scoped_refptr<BackForwardCacheMetrics> metrics =
2165 entry->TakeBackForwardCacheMetrics();
2166 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2167 }
2168 }
2169
Carlos IL42b416592019-10-07 23:10:362170 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312171 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152172 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432173}
2174
Charlie Reisc0f17d2d2021-01-12 18:52:492175void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322176 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072177 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362178 bool is_same_document,
jam48cea9082017-02-15 06:13:292179 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452180 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002181 bool keep_pending_entry,
2182 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562183 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2184 << "that a last committed entry exists.";
2185
[email protected]e9ba4472008-09-14 15:42:432186 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002187 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432188
Charlie Reis7e2cb6d2021-01-26 01:27:162189 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002190 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162191 // We're guaranteed to have a last committed entry if intended_as_new_entry
2192 // is true.
avicbdc4c12015-07-01 16:07:112193 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162194
2195 // If the NavigationRequest matches a new pending entry and is classified as
2196 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2197 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092198 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162199 // Note: The pending entry will usually have a real ReloadType here, but
2200 // it can still be ReloadType::NONE in cases that
2201 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2202
2203 // If we classified this correctly, the SiteInstance should not have
2204 // changed.
2205 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2206
2207 // For converted reloads, we assign the entry's unique ID to be that of
2208 // the new one. Since this is always the result of a user action, we want
2209 // to dismiss infobars, etc. like a regular user-initiated navigation.
2210 entry->set_unique_id(pending_entry_->GetUniqueID());
2211
2212 // The extra headers may have changed due to reloading with different
2213 // headers.
2214 entry->set_extra_headers(pending_entry_->extra_headers());
2215 }
2216 // Otherwise, this was intended as a new entry but the pending entry was
2217 // lost in the meantime and no new entry was created. We are stuck at the
2218 // last committed entry.
2219
2220 // Even if this is a converted reload from pressing enter in the omnibox,
2221 // the server could redirect, requiring an update to the SSL status. If this
2222 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452223 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162224 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472225 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452226 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162227 }
Rakina Zata Amnif6950d552020-11-24 03:26:102228 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112229 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102230 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162231
eugenebut604866f2017-05-10 21:35:362232 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452233 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362234 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2235 // this was a restored same document navigation entry, then it won't have
2236 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2237 // navigated it.
jam48cea9082017-02-15 06:13:292238 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522239 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2240 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292241 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2242 was_restored) {
2243 entry->GetSSL() = last_entry->GetSSL();
2244 }
2245 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452246 // In rapid back/forward navigations |request| sometimes won't have a cert
2247 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192248 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452249 if (request->GetSSLInfo().has_value() &&
2250 request->GetSSLInfo()->is_valid()) {
2251 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522252 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2253 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192254 entry->GetSSL() = SSLStatus();
2255 }
jam48cea9082017-02-15 06:13:292256 }
avicbdc4c12015-07-01 16:07:112257 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272258 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572259 // navigations that are EXISTING_ENTRY are same-document navigations that
2260 // result in replacement (e.g. history.replaceState(), location.replace(),
2261 // forced replacements for trivial session history contexts). For these
2262 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112263 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102264
Alison Gale81f4f2c72024-04-22 19:33:312265 // TODO(crbug.com/40532777): Set page transition type to
2266 // PAGE_TRANSITION_LINK to avoid misleading interpretations (e.g. URLs
2267 // paired with PAGE_TRANSITION_TYPED that haven't actually been typed) as
2268 // well as to fix the inconsistency with what we report to observers
2269 // (PAGE_TRANSITION_LINK | PAGE_TRANSITION_CLIENT_REDIRECT).
Mikel Astizba9cf2fd2017-12-17 10:38:102270
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572271 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102272
eugenebut604866f2017-05-10 21:35:362273 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452274 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362275 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472276 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452277 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112278 }
2279 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432280
Rakina Zata Amni3460d382021-10-29 00:43:372281 UpdateNavigationEntryDetails(entry, rfh, params, request,
2282 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002283 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302284
[email protected]5ccd4dc2012-10-24 02:28:142285 // The redirected to page should not inherit the favicon from the previous
2286 // page.
eugenebut604866f2017-05-10 21:35:362287 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482288 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142289
Charlie Reis951f43372023-05-05 00:30:072290 // Update the last committed index to reflect the committed entry. Do this
2291 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2292 // delegate sees the correct committed index when notified of navigation
2293 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2294 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212295 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072296
Peter Boströmd7592132019-01-30 04:50:312297 // We should also usually discard the pending entry if it corresponds to a
2298 // different navigation, since that one is now likely canceled. In rare
2299 // cases, we leave the pending entry for another navigation in place when we
2300 // know it is still ongoing, to avoid a flicker in the omnibox (see
2301 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432302 //
2303 // Note that we need to use the "internal" version since we don't want to
2304 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312305 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002306 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432307}
2308
[email protected]d202a7c2012-01-04 07:53:472309void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322310 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072311 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362312 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472313 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562314 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002315 NavigationRequest* request,
2316 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262317 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2318 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552319 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2320 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112321
[email protected]e9ba4472008-09-14 15:42:432322 // Manual subframe navigations just get the current entry cloned so the user
2323 // can go back or forward to it. The actual subframe information will be
2324 // stored in the page state for each of those entries. This happens out of
2325 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092326 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2327 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382328
Mikel Astizba9cf2fd2017-12-17 10:38:102329 // The DCHECK below documents the fact that we don't know of any situation
2330 // where |replace_entry| is true for subframe navigations. This simplifies
2331 // reasoning about the replacement struct for subframes (see
2332 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2333 DCHECK(!replace_entry);
2334
Patrick Monette50e8bd82019-06-13 22:40:452335 // This FrameNavigationEntry might not end up being used in the
2336 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372337 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452338 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372339 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522340 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2341 initiator_base_url = request->common_params().initiator_base_url;
2342 }
Nate Chapin63db0d12022-01-20 22:03:302343 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2344 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:212345 request->DidEncounterError(),
Nate Chapin63db0d12022-01-20 22:03:302346 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572347 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302348 if (is_same_document) {
2349 FrameNavigationEntry* previous_frame_entry =
2350 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572351 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302352 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572353 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302354 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572355 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302356 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572357 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302358 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572359 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302360 policy_container_policies->referrer_policy);
2361 }
2362
Patrick Monette50e8bd82019-06-13 22:40:452363 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482364 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572365 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082366 rfh->GetSiteInstance(), nullptr, params.url,
2367 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212368 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2369 request->GetRedirectChain(), params.page_state, params.method,
2370 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572371 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032372
creisce0ef3572017-01-26 17:53:082373 std::unique_ptr<NavigationEntryImpl> new_entry =
2374 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452375 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032376 frame_tree_->root());
creise062d542015-08-25 02:01:552377
Alexander Timine3ec4192020-04-20 16:39:402378 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562379 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402380 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472381
creisce0ef3572017-01-26 17:53:082382 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452383 // to replace, which can happen due to a unique name change. See
2384 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2385 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382386
Dave Tapuska87696ae2021-11-18 18:48:312387 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152388 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432389}
2390
[email protected]d202a7c2012-01-04 07:53:472391bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322392 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072393 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392394 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252395 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002396 NavigationRequest* request,
2397 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292398 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2399 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2400
[email protected]e9ba4472008-09-14 15:42:432401 // We're guaranteed to have a previously committed entry, and we now need to
2402 // handle navigation inside of a subframe in it without creating a new entry.
2403 DCHECK(GetLastCommittedEntry());
2404
creis913c63ce2016-07-16 19:52:522405 // For newly created subframes, we don't need to send a commit notification.
2406 // This is only necessary for history navigations in subframes.
2407 bool send_commit_notification = false;
2408
Rakina Zata Amnif6950d552020-11-24 03:26:102409 // If |nav_entry_id| is non-zero and matches an existing entry, this
2410 // is a history navigation. Update the last committed index accordingly. If
2411 // we don't recognize the |nav_entry_id|, it might be a recently
2412 // pruned entry. We'll handle it below.
2413 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2414 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472415 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062416 // Make sure that a subframe commit isn't changing the main frame's
2417 // origin. Otherwise the renderer process may be confused, leading to a
2418 // URL spoof. We can't check the path since that may change
2419 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572420 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2421 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242422 // We should use checks similar to RenderFrameHostImpl's
2423 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2424 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572425 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2426 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2427 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2428 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522429 current_top_url.DeprecatedGetOriginAsURL() !=
2430 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442431 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512432 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062433 }
creis3cdc3b02015-05-29 23:00:472434
creis913c63ce2016-07-16 19:52:522435 // We only need to discard the pending entry in this history navigation
2436 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062437 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002438 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522439
2440 // History navigations should send a commit notification.
2441 send_commit_notification = true;
avi98405c22015-05-21 20:47:062442 }
[email protected]e9ba4472008-09-14 15:42:432443 }
[email protected]f233e4232013-02-23 00:55:142444
creisce0ef3572017-01-26 17:53:082445 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2446 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372447 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2448 // exists), or we may want to clobber it and create a new one. We update in
2449 // cases where the corresponding FrameNavigationEntry is conceptually similar
2450 // to the document described by the commit params: same-document
2451 // navigations, history traversal to an existing entry, and reloads (including
2452 // a "soft reload" where we navigate to the same url without flagging it as a
2453 // reload). But in the case of a different document that is not logically
2454 // related to the committed FrameNavigationEntry's document (cross-document,
2455 // not same url, not a reload, not a history traversal), we replace rather
2456 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252457 //
Nate Chapin9f169072021-06-09 19:32:372458 // In the case where we update, the FrameNavigationEntry will potentially be
2459 // shared across multiple NavigationEntries, and any updates will be reflected
2460 // in all of those NavigationEntries. In the replace case, any existing
2461 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252462 //
2463 // When navigating away from the initial empty document, we also update rather
2464 // than replace. Either update or replace will overwrite the initial empty
2465 // document state for |last_committed|, but if the FrameNavigationEntry for
2466 // the initial empty document is shared across multiple NavigationEntries (due
2467 // to a navigation in another frame), we want to make sure we overwrite the
2468 // initial empty document state everywhere this FrameNavigationEntry is used,
2469 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452470 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372471 FrameNavigationEntry* last_committed_frame_entry =
2472 last_committed->GetFrameEntry(rfh->frame_tree_node());
2473 NavigationEntryImpl::UpdatePolicy update_policy =
2474 NavigationEntryImpl::UpdatePolicy::kUpdate;
2475 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312476 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372477 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252478 last_committed_frame_entry->url() != params.url &&
2479 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372480 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2481 }
2482
Rakina Zata Amni3460d382021-10-29 00:43:372483 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002484 update_policy, false /* is_new_entry */,
2485 commit_details);
creis625a0c7d2015-03-24 23:17:122486
creis913c63ce2016-07-16 19:52:522487 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432488}
2489
[email protected]d202a7c2012-01-04 07:53:472490int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232491 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032492 for (size_t i = 0; i < entries_.size(); ++i) {
2493 if (entries_[i].get() == entry)
2494 return i;
2495 }
2496 return -1;
[email protected]765b35502008-08-21 00:51:202497}
2498
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572499void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242500 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572501 NavigationControllerImpl* source =
2502 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572503 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382504 DCHECK_EQ(1, GetEntryCount());
2505 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472506 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172507 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572508
Francois Dorayeaace782017-06-21 16:37:242509 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442510 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572511 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572512
Fergal Dalya1d569972021-03-16 03:24:532513 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302514 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532515 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2516 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302517 }
[email protected]4e6419c2010-01-15 04:50:342518
Lukasz Anforowicz0de0f452020-12-02 19:57:152519 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572520}
2521
[email protected]79368982013-11-13 01:11:012522bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
Adithya Srinivasane8094c82024-06-26 22:45:022523 // If there is no last committed entry, we cannot prune.
[email protected]474f8512013-05-31 22:31:162524 if (last_committed_entry_index_ == -1)
2525 return false;
[email protected]9350602e2013-02-26 23:27:442526
[email protected]474f8512013-05-31 22:31:162527 // We cannot prune if there is a pending entry at an existing entry index.
2528 // It may not commit, so we have to keep the last committed entry, and thus
2529 // there is no sensible place to keep the pending entry. It is ok to have
2530 // a new pending entry, which can optionally commit as a new navigation.
2531 if (pending_entry_index_ != -1)
2532 return false;
2533
[email protected]474f8512013-05-31 22:31:162534 return true;
2535}
2536
[email protected]79368982013-11-13 01:11:012537void NavigationControllerImpl::PruneAllButLastCommitted() {
2538 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162539
avi2b177592014-12-10 02:08:022540 DCHECK_EQ(0, last_committed_entry_index_);
2541 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442542
Hayato Ito2c8c08d02021-06-23 03:38:432543 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442544}
2545
[email protected]79368982013-11-13 01:11:012546void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162547 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012548 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262549
Nate Chapin9eb16be72022-09-23 22:54:312550 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2551
[email protected]474f8512013-05-31 22:31:162552 // Erase all entries but the last committed entry. There may still be a
2553 // new pending entry after this.
2554 entries_.erase(entries_.begin(),
2555 entries_.begin() + last_committed_entry_index_);
2556 entries_.erase(entries_.begin() + 1, entries_.end());
2557 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262558}
2559
Christian Dullweber1af31e62018-02-22 11:49:482560void NavigationControllerImpl::DeleteNavigationEntries(
2561 const DeletionPredicate& deletionPredicate) {
2562 // It is up to callers to check the invariants before calling this.
2563 CHECK(CanPruneAllButLastCommitted());
2564 std::vector<int> delete_indices;
2565 for (size_t i = 0; i < entries_.size(); i++) {
2566 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572567 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482568 delete_indices.push_back(i);
2569 }
2570 }
2571 if (delete_indices.empty())
2572 return;
2573
2574 if (delete_indices.size() == GetEntryCount() - 1U) {
2575 PruneAllButLastCommitted();
2576 } else {
2577 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382578 for (const auto& index : base::Reversed(delete_indices)) {
2579 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482580 }
Hayato Ito2c8c08d02021-06-23 03:38:432581 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482582 }
2583 delegate()->NotifyNavigationEntriesDeleted();
2584}
2585
Carlos Caballero35ce710c2019-09-19 10:59:452586BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2587 return back_forward_cache_;
2588}
2589
William Liu055a3542023-04-02 17:21:192590NavigationEntryScreenshotCache*
2591NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212592 CHECK(frame_tree_->is_primary());
Khushal Sagar94ea2dc2024-08-06 17:15:262593 if (!nav_entry_screenshot_cache_ &&
2594 NavigationTransitionConfig::AreBackForwardTransitionsEnabled()) {
William Liu055a3542023-04-02 17:21:192595 nav_entry_screenshot_cache_ =
2596 std::make_unique<NavigationEntryScreenshotCache>(
2597 BrowserContextImpl::From(browser_context_)
2598 ->GetNavigationEntryScreenshotManager()
2599 ->GetSafeRef(),
2600 this);
2601 }
2602 return nav_entry_screenshot_cache_.get();
2603}
2604
clamy987a3752018-05-03 17:36:262605void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2606 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2607 // progress, since this will cause a use-after-free. (We only allow this
2608 // when the tab is being destroyed for shutdown, since it won't return to
2609 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032610 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262611
2612 if (was_failure && pending_entry_) {
2613 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2614 } else {
2615 failed_pending_entry_id_ = 0;
2616 }
2617
2618 if (pending_entry_) {
2619 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332620 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262621 pending_entry_index_ = -1;
2622 pending_entry_ = nullptr;
2623 }
arthursonzogni66f711c2019-10-08 14:40:362624
2625 // Ensure any refs to the current pending entry are ignored if they get
2626 // deleted, by clearing the set of known refs. All future pending entries will
2627 // only be affected by new refs.
2628 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262629}
2630
2631void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2632 if (pending_entry_)
2633 pending_entry_->set_ssl_error(error);
2634}
2635
Xiaohan Wang7f8052e02022-01-14 18:44:282636#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422637// static
2638bool NavigationControllerImpl::ValidateDataURLAsString(
2639 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2640 if (!data_url_as_string)
2641 return false;
2642
2643 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2644 return false;
2645
2646 // The number of characters that is enough for validating a data: URI.
2647 // From the GURL's POV, the only important part here is scheme, it doesn't
2648 // check the actual content. Thus we can take only the prefix of the url, to
2649 // avoid unneeded copying of a potentially long string.
danakj529a3eba2024-04-18 20:14:562650 constexpr size_t kDataUriPrefixMaxLen = 64;
2651 const size_t len = std::min(data_url_as_string->size(), kDataUriPrefixMaxLen);
2652 GURL data_url(base::as_string_view(*data_url_as_string).substr(0u, len));
Camille Lamy5193caa2018-10-12 11:59:422653 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2654 return false;
2655
2656 return true;
2657}
2658#endif
2659
Shivani Sharma194877032019-03-07 17:52:472660void NavigationControllerImpl::NotifyUserActivation() {
2661 // When a user activation occurs, ensure that all adjacent entries for the
2662 // same document clear their skippable bit, so that the history manipulation
2663 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012664 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172665 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012666 // If the value of CanGoBack changes as a result of making some entries
2667 // non-skippable, then we must let the delegate know to update its UI state.
2668 // See https://crbug.com/1477784.
2669 if (!can_go_back && CanGoBack()) {
2670 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2671 }
Shivani Sharma194877032019-03-07 17:52:472672}
2673
clamy987a3752018-05-03 17:36:262674bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2675 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332676 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2677 blink::LocalFrameToken initiator_frame_token,
2678 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262679 NavigationEntryImpl* entry =
2680 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2681 if (!entry)
2682 return false;
2683
2684 FrameNavigationEntry* frame_entry =
2685 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2686 if (!frame_entry)
2687 return false;
2688
Camille Lamy5193caa2018-10-12 11:59:422689 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572690 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232691 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332692 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2693 initiator_process_id);
clamyea99ea12018-05-28 13:54:232694
2695 if (!request)
2696 return false;
2697
arthursonzognif046d4a2019-12-12 19:08:102698 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412699
Rakina Zata Amni1c83b082023-02-08 01:09:002700 SCOPED_CRASH_KEY_STRING256(
2701 "Bug1400009", "req_url",
2702 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2703 SCOPED_CRASH_KEY_NUMBER(
2704 "Bug1400009", "nav_entry_si",
2705 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2706 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2707 frame_entry->site_instance()
2708 ? ((int)frame_entry->site_instance()->GetId())
2709 : -1);
2710 bool has_sig =
2711 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2712 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2713 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2714 has_sig ? (!!frame_tree_->GetRenderViewHost(
2715 frame_entry->site_instance()->group()))
2716 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052717 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2718 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232719
2720 return true;
clamy987a3752018-05-03 17:36:262721}
2722
Tsuyoshi Horo52fd08e2020-07-07 07:03:452723bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2724 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2725 if (!entry)
2726 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432727
2728 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2729 // We should never navigate to an existing initial NavigationEntry that is
2730 // the initial NavigationEntry for the initial empty document that hasn't
2731 // been overridden by the synchronous about:blank commit, to preserve
2732 // legacy behavior where trying to reload when the main frame is on the
2733 // initial empty document won't result in a navigation. See also
2734 // https://crbug.com/1277414.
2735 return false;
2736 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452737 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2738 if (!frame_entry)
2739 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142740 ReloadType reload_type = ReloadType::NORMAL;
2741 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452742 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142743 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452744 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432745 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372746 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332747 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452748 if (!request)
2749 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052750 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452751 return true;
2752}
2753
clamy987a3752018-05-03 17:36:262754void NavigationControllerImpl::NavigateFromFrameProxy(
2755 RenderFrameHostImpl* render_frame_host,
2756 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022757 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452758 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372759 const std::optional<url::Origin>& initiator_origin,
2760 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262761 bool is_renderer_initiated,
2762 SiteInstance* source_site_instance,
2763 const Referrer& referrer,
2764 ui::PageTransition page_transition,
2765 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252766 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262767 const std::string& method,
2768 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092769 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142770 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212771 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502772 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372773 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292774 blink::mojom::NavigationInitiatorActivationAndAdStatus
2775 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222776 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492777 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462778 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452779 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582780 bool is_container_initiated,
Kevin McNee6455638a2024-06-27 22:05:032781 bool has_rel_opener,
W. James MacLean443ef3e2024-07-16 13:42:342782 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:372783 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582784 if (is_renderer_initiated)
2785 DCHECK(initiator_origin.has_value());
2786
clamy987a3752018-05-03 17:36:262787 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582788
Rakina Zata Amni2322f4f82022-01-24 13:24:242789 // Don't allow an entry replacement if there is no entry to replace.
2790 // http://crbug.com/457149
2791 if (GetEntryCount() == 0)
2792 should_replace_current_entry = false;
2793
clamy987a3752018-05-03 17:36:262794 // Create a NavigationEntry for the transfer, without making it the pending
2795 // entry. Subframe transfers should have a clone of the last committed entry
2796 // with a FrameNavigationEntry for the target frame. Main frame transfers
2797 // should have a new NavigationEntry.
2798 // TODO(creis): Make this unnecessary by creating (and validating) the params
2799 // directly, passing them to the destination RenderFrameHost. See
2800 // https://crbug.com/536906.
2801 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262802 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262803 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452804 DCHECK(GetLastCommittedEntry());
2805 entry = GetLastCommittedEntry()->Clone();
2806 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172807 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2808 // Renderer-initiated navigation that target a remote frame are currently
2809 // classified as browser-initiated when this one has already navigated.
2810 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372811 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2812 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2813 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2814 // same-document navigation), they will still be present in the
2815 // committed NavigationEntry that will be referenced to construct the new
2816 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262817 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082818 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582819 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372820 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212821 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152822 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262823 } else {
2824 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172825 // If `node` is the outermost main frame, it rewrites a virtual url in order
2826 // to adjust the original input url if needed. For inner frames such as
2827 // fenced frames or subframes, they don't rewrite urls as the urls are not
2828 // input urls by users.
2829 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372830 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322831 if (source_site_instance && source_site_instance->HasProcess()) {
2832 source_process_site_url =
2833 source_site_instance->GetProcess()->GetProcessLock().site_url();
2834 }
clamy987a3752018-05-03 17:36:262835 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212836 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322837 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212838 extra_headers, browser_context_, blob_url_loader_factory,
2839 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262840 entry->root_node()->frame_entry->set_source_site_instance(
2841 static_cast<SiteInstanceImpl*>(source_site_instance));
2842 entry->root_node()->frame_entry->set_method(method);
2843 }
clamy987a3752018-05-03 17:36:262844
Camille Lamy5193caa2018-10-12 11:59:422845 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452846 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262847 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422848 override_user_agent = true;
clamy987a3752018-05-03 17:36:262849 }
2850 // TODO(creis): Set user gesture and intent received timestamp on Android.
2851
2852 // We may not have successfully added the FrameNavigationEntry to |entry|
2853 // above (per https://crbug.com/608402), in which case we create it from
2854 // scratch. This works because we do not depend on |frame_entry| being inside
2855 // |entry| during NavigateToEntry. This will go away when we shortcut this
2856 // further in https://crbug.com/536906.
2857 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2858 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452859 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082860 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582861 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372862 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212863 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152864 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572865 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262866 }
2867
Camille Lamy5193caa2018-10-12 11:59:422868 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022869 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452870 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292871 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212872 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422873 params.source_site_instance = source_site_instance;
2874 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2875 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032876 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422877 params.referrer = referrer;
2878 /* params.redirect_chain: skip */
2879 params.extra_headers = extra_headers;
2880 params.is_renderer_initiated = is_renderer_initiated;
2881 params.override_user_agent = UA_OVERRIDE_INHERIT;
2882 /* params.base_url_for_data_url: skip */
Shu Yang112ad492024-07-25 17:11:542883 /* params.virtual_url_for_special_cases: skip */
Camille Lamy5193caa2018-10-12 11:59:422884 /* params.data_url_as_string: skip */
2885 params.post_data = post_body;
2886 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582887 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422888 /* params.frame_name: skip */
2889 // TODO(clamy): See if user gesture should be propagated to this function.
2890 params.has_user_gesture = false;
2891 params.should_clear_history_list = false;
2892 params.started_from_context_menu = false;
2893 /* params.navigation_ui_data: skip */
2894 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222895 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542896 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212897 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412898 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502899 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292900 params.initiator_activation_and_ad_status =
2901 initiator_activation_and_ad_status;
Kevin McNee6455638a2024-06-27 22:05:032902 params.has_rel_opener = has_rel_opener;
Camille Lamy5193caa2018-10-12 11:59:422903
2904 std::unique_ptr<NavigationRequest> request =
2905 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032906 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142907 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392908 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492909 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582910 is_unfenced_top_navigation, is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:342911 storage_access_api_status, embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232912
2913 if (!request)
2914 return;
2915
Garrett Tanzerbb8db412022-09-27 21:59:462916 // Force the navigation to take place in a new browsing instance.
2917 // This is used by _unfencedTop in fenced frames to ensure that navigations
2918 // leaving the fenced context create a new browsing instance.
2919 if (force_new_browsing_instance) {
2920 request->coop_status().ForceBrowsingInstanceSwap();
2921 }
2922
Arthur Hemery948742762019-09-18 10:06:242923 // At this stage we are proceeding with this navigation. If this was renderer
2924 // initiated with user gesture, we need to make sure we clear up potential
2925 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2926 DiscardNonCommittedEntries();
2927
Lukasz Anforowicz9ee83c272020-12-01 20:14:052928 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262929}
2930
[email protected]d1198fd2012-08-13 22:50:192931void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252932 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212933 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192934 if (!session_storage_namespace)
2935 return;
2936
2937 // We can't overwrite an existing SessionStorage without violating spec.
2938 // Attempts to do so may give a tab access to another tab's session storage
2939 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152940 bool successful_insert =
2941 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252942 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052943 static_cast<SessionStorageNamespaceImpl*>(
2944 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302945 .second;
2946 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192947}
2948
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572949bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452950 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032951 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462952}
2953
Aran Gilman37d11632019-10-08 23:07:152954SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252955 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302956 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252957 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032958 DOMStorageContextWrapper* context_wrapper =
2959 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2960
2961 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252962 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032963 if (it != session_storage_namespace_map_.end()) {
2964 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152965 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2966 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472967
michaelnbacbcbd2016-02-09 00:32:032968 return it->second.get();
2969 }
2970
2971 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102972 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2973 SessionStorageNamespaceImpl::Create(context_wrapper);
2974 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2975 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252976 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102977 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302978
Daniel Murphy31bbb8b12018-02-07 21:44:102979 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302980}
2981
2982SessionStorageNamespace*
2983NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252984 return GetSessionStorageNamespace(
2985 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302986}
2987
2988const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572989NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302990 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552991}
[email protected]d202a7c2012-01-04 07:53:472992
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572993bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562994 return needs_reload_;
2995}
[email protected]a26023822011-12-29 00:23:552996
[email protected]46bb5e9c2013-10-03 22:16:472997void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412998 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2999}
3000
3001void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473002 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413003 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543004
3005 if (last_committed_entry_index_ != -1) {
3006 entries_[last_committed_entry_index_]->SetTransitionType(
3007 ui::PAGE_TRANSITION_RELOAD);
3008 }
[email protected]46bb5e9c2013-10-03 22:16:473009}
3010
[email protected]d202a7c2012-01-04 07:53:473011void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573012 DCHECK_LT(index, GetEntryCount());
3013 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313014 DiscardNonCommittedEntries();
3015
Nate Chapin9eb16be72022-09-23 22:54:313016 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313017 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123018 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313019 last_committed_entry_index_--;
3020}
3021
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573022NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273023 // If there is no pending_entry_, there should be no pending_entry_index_.
3024 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3025
3026 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363027 // at that index. An exception is while a reload of a post commit error page
3028 // is ongoing; in that case pending entry will point to the entry replaced
3029 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273030 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363031 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3032 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273033
[email protected]022af742011-12-28 18:37:253034 return pending_entry_;
3035}
3036
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573037int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273038 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273039 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553040 return pending_entry_index_;
3041}
3042
avi25764702015-06-23 15:43:373043void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573044 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363045 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313046 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003047 bool in_fenced_frame_tree,
3048 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313049 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3050 // set because:
3051 // 1) They don't influence the history of the outer page.
3052 // 2) They are always replace only navigation (there is always only one entry
3053 // in their history stack).
3054 // 3) Are not top level navigations and appear similar to iframes.
3055 // Navigations of the fenced frame might create a new NavigationEntry, which
3056 // will call this function. Non fenced frame navigations will never have
3057 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3058 // InsertOrReplaceEntry.
3059 DCHECK_EQ(in_fenced_frame_tree,
3060 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3061 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203062
avi5cad4912015-06-19 05:25:443063 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3064 // need to keep continuity with the pending entry, so copy the pending entry's
3065 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3066 // then the renderer navigated on its own, independent of the pending entry,
3067 // so don't copy anything.
3068 if (pending_entry_ && pending_entry_index_ == -1)
3069 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203070
Rakina Zata Amnia4e27222021-12-22 01:05:003071 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203072
creisee17e932015-07-17 17:56:223073 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453074 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103075 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573076 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363077 // If the new entry is a post-commit error page, we store the current last
3078 // committed entry to the side so that we can put it back when navigating
3079 // away from the error.
3080 if (was_post_commit_error) {
3081 DCHECK(!entry_replaced_by_post_commit_error_);
3082 entry_replaced_by_post_commit_error_ =
3083 std::move(entries_[last_committed_entry_index_]);
3084 }
dcheng36b6aec92015-12-26 06:16:363085 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223086 return;
3087 }
[email protected]765b35502008-08-21 00:51:203088
creis37979a62015-08-04 19:48:183089 // We shouldn't see replace == true when there's no committed entries.
3090 DCHECK(!replace);
3091
Michael Thiessen9b14d512019-09-23 21:19:473092 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203093
Shivani Sharmad8c8d652019-02-13 17:27:573094 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203095
dcheng36b6aec92015-12-26 06:16:363096 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203097 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293098}
3099
Shivani Sharmad8c8d652019-02-13 17:27:573100void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163101 if (entries_.size() < max_entry_count())
3102 return;
3103
3104 DCHECK_EQ(max_entry_count(), entries_.size());
3105 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573106 CHECK_EQ(pending_entry_index_, -1);
3107
3108 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423109 // Retrieve the oldest skippable entry.
3110 for (; index < GetEntryCount(); index++) {
3111 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3112 break;
Shivani Sharmad8c8d652019-02-13 17:27:573113 }
3114
3115 // If there is no skippable entry or if it is the last committed entry then
3116 // fall back to pruning the oldest entry. It is not safe to prune the last
3117 // committed entry.
3118 if (index == GetEntryCount() || index == last_committed_entry_index_)
3119 index = 0;
3120
3121 bool should_succeed = RemoveEntryAtIndex(index);
3122 DCHECK_EQ(true, should_succeed);
3123
3124 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253125}
3126
William Liu62ae26c2024-08-08 14:28:163127std::vector<base::WeakPtr<NavigationRequest>>
William Liuec04e382024-05-23 18:03:273128NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163129 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203130 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373131 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133132 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203133 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503134 TRACE_EVENT0("navigation",
3135 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273136 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023137 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363138 if (pending_entry_index_ != -1) {
3139 // The pending entry may not be in entries_ if a post-commit error page is
3140 // showing.
3141 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3142 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3143 }
Gyuyoung Kim107c2a02021-04-13 01:49:303144 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573145 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013146 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033147 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573148 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133149 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3150 // the same as the top level frame being navigated.
3151 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373152 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133153 }
Arthur Sonzogni620cec62018-12-13 13:08:573154
[email protected]83c2e232011-10-07 21:36:463155 // If we were navigating to a slow-to-commit page, and the user performs
3156 // a session history navigation to the last committed page, RenderViewHost
3157 // will force the throbber to start, but WebKit will essentially ignore the
3158 // navigation, and won't send a message to stop the throbber. To prevent this
3159 // from happening, we drop the navigation here and stop the slow-to-commit
3160 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023161 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083162 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273163 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033164 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123165
[email protected]83c2e232011-10-07 21:36:463166 DiscardNonCommittedEntries();
William Liu62ae26c2024-08-08 14:28:163167 return {};
[email protected]83c2e232011-10-07 21:36:463168 }
3169
Arthur Sonzognic686e8f2024-01-11 08:36:373170 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333171 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3172 if (initiator_rfh) {
3173 initiator_frame_token = initiator_rfh->GetFrameToken();
3174 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3175 DCHECK(initiator_frame_token);
3176 }
3177
creisce0ef3572017-01-26 17:53:083178 // Compare FrameNavigationEntries to see which frames in the tree need to be
3179 // navigated.
clamy3cb9bea92018-07-10 12:42:023180 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3181 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333182 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3183 initiator_process_id, soft_navigation_heuristics_task_id,
3184 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303185
3186 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573187 // We were unable to match any frames to navigate. This can happen if a
3188 // history navigation targets a subframe that no longer exists
3189 // (https://crbug.com/705550). In this case, we need to update the current
3190 // history entry to the pending one but keep the main document loaded. We
3191 // also need to ensure that observers are informed about the updated
3192 // current history entry (e.g., for greying out back/forward buttons), and
3193 // that renderer processes update their history offsets. The easiest way
3194 // to do all that is to schedule a "redundant" same-document navigation in
3195 // the main frame.
3196 //
3197 // Note that we don't want to remove this history entry, as it might still
3198 // be valid later, since a frame that it's targeting may be recreated.
3199 //
3200 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3201 // need to repeat history navigations until finding the one that works.
3202 // Consider changing this behavior to keep looking for the first valid
3203 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023204 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423205 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573206 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573207 ReloadType::NONE /* reload_type */,
3208 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433209 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333210 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023211 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573212 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023213 DiscardPendingEntry(false);
William Liu62ae26c2024-08-08 14:28:163214 return {};
clamy3cb9bea92018-07-10 12:42:023215 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573216 same_document_loads.push_back(std::move(navigation_request));
3217
3218 // Sanity check that we never take this branch for any kinds of reloads,
3219 // as those should've queued a different-document load in the main frame.
3220 DCHECK(!is_forced_reload);
3221 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303222 }
3223
Nate Chapinbf682fa32022-09-26 22:41:203224 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163225 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203226 if (initiator_rfh && initiator_rfh->IsSandboxed(
3227 network::mojom::WebSandboxFlags::kTopNavigation)) {
3228 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3229 initiator_rfh, same_document_loads) &&
3230 DoesSandboxNavigationStayWithinSubtree(
3231 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503232 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163233 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203234 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3235 initiator_rfh,
3236 navigates_inside_tree
3237 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3238 : blink::mojom::WebFeature::
3239 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523240
3241 // If the navigation occurred outside the tree discard it because
3242 // the sandboxed frame didn't have permission to navigate outside
3243 // its tree. If it is possible that the navigation is both inside and
3244 // outside the frame tree and we discard it entirely because we don't
3245 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143246 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203247 // If a |navigation_api_key| was provided, this navigation originated from
3248 // the navigation API. Notify the renderer that the navigation was
3249 // cancelled so the navigation API can fire an error event and reject the
3250 // relevant promise.
3251 if (navigation_api_key) {
3252 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3253 *navigation_api_key,
3254 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3255 }
Dave Tapuska855c1e12019-08-23 20:45:523256 DiscardPendingEntry(false);
Rakina Zata Amni58681c62024-06-25 06:32:133257
3258 for (auto& unused_request : same_document_loads) {
3259 unused_request->set_navigation_discard_reason(
3260 NavigationDiscardReason::kNeverStarted);
3261 }
3262 for (auto& unused_request : different_document_loads) {
3263 unused_request->set_navigation_discard_reason(
3264 NavigationDiscardReason::kNeverStarted);
3265 }
William Liu62ae26c2024-08-08 14:28:163266 return {};
Dave Tapuska855c1e12019-08-23 20:45:523267 }
Dave Tapuska8bfd84c2019-03-26 20:47:163268 }
3269
Nate Chapin6c43c022023-02-13 23:32:423270 // If it is possible that this traverse may involve a same-document navigation
3271 // in the initiator and there is a Navigation API key involved, then we may
3272 // need to notify the initiator if it fails. (The early returns above either
3273 // do not involve these cases or already notify the initiator.)
3274 // The event only needs to fire for the initiator, and only if the initiator
3275 // itself is performing a same-document navigation (because the event will not
3276 // fire if it navigates cross-document).
3277 if (navigation_api_key) {
3278 for (auto& item : same_document_loads) {
3279 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3280 item->set_pending_navigation_api_key(*navigation_api_key);
3281 break;
3282 }
3283 }
3284 }
3285
Carlos Caballero539a421c2020-07-06 10:25:573286 // BackForwardCache:
3287 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563288 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573289 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3290 DCHECK_EQ(reload_type, ReloadType::NONE);
3291 auto navigation_request = CreateNavigationRequestFromEntry(
3292 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3293 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333294 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3295 initiator_process_id);
William Liuec04e382024-05-23 18:03:273296 base::WeakPtr<NavigationRequest> request = navigation_request->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053297 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Rakina Zata Amni58681c62024-06-25 06:32:133298
3299 for (auto& unused_request : same_document_loads) {
3300 unused_request->set_navigation_discard_reason(
3301 NavigationDiscardReason::kNeverStarted);
3302 }
3303 for (auto& unused_request : different_document_loads) {
3304 unused_request->set_navigation_discard_reason(
3305 NavigationDiscardReason::kNeverStarted);
3306 }
3307
William Liu62ae26c2024-08-08 14:28:163308 std::vector<base::WeakPtr<NavigationRequest>> bf_cache_request;
3309 if (request) {
3310 bf_cache_request.push_back(std::move(request));
3311 }
3312 return bf_cache_request;
Carlos Caballero539a421c2020-07-06 10:25:573313 }
3314
3315 // History navigation might try to reuse a specific BrowsingInstance, already
3316 // used by a page in the cache. To avoid having two different main frames that
3317 // live in the same BrowsingInstance, evict the all pages with this
3318 // BrowsingInstance from the cache.
3319 //
3320 // For example, take the following scenario:
3321 //
3322 // A1 = Some page on a.com
3323 // A2 = Some other page on a.com
3324 // B3 = An uncacheable page on b.com
3325 //
3326 // Then the following navigations occur:
3327 // A1->A2->B3->A1
3328 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3329 // take its place) and A1 will be created in the same BrowsingInstance (and
3330 // SiteInstance), as A2.
3331 //
3332 // If we didn't do anything, both A1 and A2 would remain alive in the same
3333 // BrowsingInstance/SiteInstance, which is unsupported by
3334 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3335 // A2 from the cache.
Rakina Zata Amni2cde21d2024-09-27 04:20:483336 SCOPED_CRASH_KEY_NUMBER("rvh_double", "pending_entry_si",
3337 pending_entry_->site_instance()
3338 ? pending_entry_->site_instance()->GetId().value()
3339 : -1);
3340 SCOPED_CRASH_KEY_NUMBER(
3341 "rvh_double", "pending_entry_bi",
3342 pending_entry_->site_instance()
3343 ? pending_entry_->site_instance()->GetBrowsingInstanceId().value()
3344 : -1);
Carlos Caballero539a421c2020-07-06 10:25:573345 if (pending_entry_->site_instance()) {
3346 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3347 pending_entry_->site_instance());
3348 }
3349
Rakina Zata Amnid605d462022-06-01 10:17:033350 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3351 pending_entry_ && pending_entry_->IsRestored());
3352 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3353 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3354 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3355 pending_entry_index_);
3356 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3357 last_committed_entry_index_);
3358 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3359 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3360 pending_entry_ && pending_entry_->IsInitialEntry());
3361 SCOPED_CRASH_KEY_BOOL(
3362 "nav_reentrancy", "pending_entry_initial2",
3363 pending_entry_ &&
3364 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3365 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3366 IsInitialNavigation());
3367 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3368 IsInitialBlankNavigation());
3369 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3370 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3371 (int)pending_reload_);
3372
clamy3cb9bea92018-07-10 12:42:023373 // This call does not support re-entrancy. See http://crbug.com/347742.
3374 CHECK(!in_navigate_to_pending_entry_);
3375 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303376
Rakina Zata Amnid605d462022-06-01 10:17:033377 // If the navigation-reentrancy is caused by calling
3378 // NavigateToExistingPendingEntry twice, this will note the previous call's
3379 // pending entry's ID.
3380 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3381 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3382
arthursonzogni66f711c2019-10-08 14:40:363383 // It is not possible to delete the pending NavigationEntry while navigating
3384 // to it. Grab a reference to delay potential deletion until the end of this
3385 // function.
3386 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3387
Nate Chapin154b14b2023-02-17 18:28:163388 // If there is a main-frame same-document history navigation, we may defer
3389 // the subframe history navigations in order to give JS in the main frame the
3390 // opportunity to cancel the entire traverse via the navigate event. In that
3391 // case, we need to stash the main frame request's navigation token on the
3392 // subframes, so they can look up the main frame request and defer themselves
3393 // until it completes.
3394 if (!same_document_loads.empty() &&
3395 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3396 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3397 // The token will only be returned in cases where deferring the navigation
3398 // is necessary.
3399 if (auto main_frame_same_document_token =
3400 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3401 for (auto& item : same_document_loads) {
3402 if (item.get() != main_frame_request) {
3403 item->set_main_frame_same_document_history_token(
3404 main_frame_same_document_token);
3405 }
3406 }
3407 for (auto& item : different_document_loads) {
3408 item->set_main_frame_same_document_history_token(
3409 main_frame_same_document_token);
3410 }
3411 }
3412 }
3413
William Liu122754942024-01-18 22:34:393414 if (!initiator_rfh) {
3415 // A browser-initiated navigation won't have a `initiator_rfh`.
3416 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3417 different_document_loads, same_document_loads);
3418 }
3419
William Liu62ae26c2024-08-08 14:28:163420 std::vector<base::WeakPtr<NavigationRequest>> all_requests;
3421 all_requests.reserve(same_document_loads.size() +
3422 different_document_loads.size());
3423 bool seen_primary_main_frame_request = false;
3424
creis4e2ecb72015-06-20 00:46:303425 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023426 for (auto& item : same_document_loads) {
3427 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273428 // The request could be destroyed before `navigator().Navigate()` returns.
3429 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053430 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163431 if (request) {
3432 // Can only have one primary main frame request.
3433 CHECK(!seen_primary_main_frame_request ||
3434 !request->IsInPrimaryMainFrame());
3435 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3436 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273437 }
creis4e2ecb72015-06-20 00:46:303438 }
clamy3cb9bea92018-07-10 12:42:023439 for (auto& item : different_document_loads) {
3440 FrameTreeNode* frame = item->frame_tree_node();
William Liuec04e382024-05-23 18:03:273441 base::WeakPtr<NavigationRequest> request = item->GetWeakPtr();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053442 frame->navigator().Navigate(std::move(item), reload_type);
William Liu62ae26c2024-08-08 14:28:163443 if (request) {
3444 // Can only have one primary main frame request.
3445 CHECK(!seen_primary_main_frame_request ||
3446 !request->IsInPrimaryMainFrame());
3447 seen_primary_main_frame_request = request->IsInPrimaryMainFrame();
3448 all_requests.push_back(std::move(request));
William Liuec04e382024-05-23 18:03:273449 }
creis4e2ecb72015-06-20 00:46:303450 }
clamy3cb9bea92018-07-10 12:42:023451
3452 in_navigate_to_pending_entry_ = false;
William Liuec04e382024-05-23 18:03:273453
William Liu62ae26c2024-08-08 14:28:163454 return all_requests;
creis4e2ecb72015-06-20 00:46:303455}
3456
Alex Moshchuk3a4e77a2020-05-29 21:32:573457NavigationControllerImpl::HistoryNavigationAction
3458NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303459 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573460 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423461 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583462 // Only active and prerendered documents are allowed to navigate in their
3463 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423464 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013465 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583466 // - If the document is in pending deletion, the browser already committed
3467 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3468 // - If the document is in back-forward cache, it's not allowed to navigate
3469 // as it should remain frozen. Ignore the request and evict the document
3470 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423471 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583472 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423473 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113474 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3475 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423476 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113477 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423478 }
arthursonzogni03f76152019-02-12 10:35:203479
Alex Moshchuk3a4e77a2020-05-29 21:32:573480 // Reloads should result in a different-document load. Note that reloads may
3481 // also happen via the |needs_reload_| mechanism where the reload_type is
3482 // NONE, so detect this by comparing whether we're going to the same
3483 // entry that we're currently on. Similarly to above, only main frames
3484 // should reach this. Note that subframes support reloads, but that's done
3485 // via a different path that doesn't involve FindFramesToNavigate (see
3486 // RenderFrameHost::Reload()).
3487 if (reload_type != ReloadType::NONE ||
3488 pending_entry_index_ == last_committed_entry_index_) {
3489 DCHECK(frame->IsMainFrame());
3490 return HistoryNavigationAction::kDifferentDocument;
3491 }
3492
Alex Moshchuk47d1a4bd2020-06-01 22:15:343493 // If there is no new FrameNavigationEntry for the frame, ignore the
3494 // load. For example, this may happen when going back to an entry before a
3495 // frame was created. Suppose we commit a same-document navigation that also
3496 // results in adding a new subframe somewhere in the tree. If we go back,
3497 // the new subframe will be missing a FrameNavigationEntry in the previous
3498 // NavigationEntry, but we shouldn't delete or change what's loaded in
3499 // it.
3500 //
Alex Moshchuke65c39272020-06-03 17:55:373501 // Note that in this case, there is no need to keep looking for navigations
3502 // in subframes, which would be missing FrameNavigationEntries as well.
3503 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343504 // It's important to check this before checking |old_item| below, since both
3505 // might be null, and in that case we still shouldn't change what's loaded in
3506 // this frame. Note that scheduling any loads assumes that |new_item| is
3507 // non-null. See https://crbug.com/1088354.
3508 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3509 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373510 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343511
Charlie Reisa474fb62022-03-17 02:31:363512 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3513 // which history item it is currently on, since this may be different than the
3514 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3515 // (e.g., if a history navigation is targeting multiple frames and only some
3516 // have committed so far).
creis4e2ecb72015-06-20 00:46:303517 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363518 frame->current_frame_host()->last_committed_frame_entry();
3519 if (!old_item) {
3520 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3521 // fall back to the last committed NavigationEntry's record for this frame.
3522 // This may happen in cases like the initial state of the RenderFrameHost.
Alison Gale770f3fc2024-04-27 00:39:583523 // TODO(crbug.com/40217743): Ensure the RenderFrameHost always has an
Charlie Reisa474fb62022-03-17 02:31:363524 // accurate FrameNavigationEntry and eliminate this case.
3525 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3526 }
3527 // If neither approach finds a FrameNavigationEntry, schedule a
3528 // different-document load.
Alison Gale770f3fc2024-04-27 00:39:583529 // TODO(crbug.com/40467594): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573530 if (!old_item)
3531 return HistoryNavigationAction::kDifferentDocument;
3532
Alex Moshchuk3a4e77a2020-05-29 21:32:573533 // If the new item is not in the same SiteInstance, schedule a
3534 // different-document load. Newly restored items may not have a SiteInstance
3535 // yet, in which case it will be assigned on first commit.
3536 if (new_item->site_instance() &&
3537 new_item->site_instance() != old_item->site_instance())
3538 return HistoryNavigationAction::kDifferentDocument;
3539
3540 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313541 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3542 // that we do this even if the history navigation would not be modifying this
3543 // frame were it live.
3544 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573545 return HistoryNavigationAction::kDifferentDocument;
3546
3547 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313548 // Starting a navigation after a crash early-promotes the speculative
3549 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3550 // committed yet, so we can not possibly perform a same-document history
3551 // navigation. The frame would need to be reloaded with a cross-document
3552 // navigation.
3553 if (!frame->current_frame_host()->has_committed_any_navigation())
3554 return HistoryNavigationAction::kDifferentDocument;
3555
creis54131692016-08-12 18:32:253556 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493557 // sequence number but different item sequence number.
3558 if (new_item->document_sequence_number() ==
3559 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573560 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493561 }
avib48cb312016-05-05 21:35:003562
Alex Moshchuk3a4e77a2020-05-29 21:32:573563 // Otherwise, if both item and document sequence numbers differ, this
3564 // should be a different document load.
3565 return HistoryNavigationAction::kDifferentDocument;
3566 }
3567
3568 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373569 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573570 DCHECK_EQ(new_item->document_sequence_number(),
3571 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373572 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573573}
3574
3575void NavigationControllerImpl::FindFramesToNavigate(
3576 FrameTreeNode* frame,
3577 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373578 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333579 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373580 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133581 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573582 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3583 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3584 DCHECK(pending_entry_);
3585 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3586
3587 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3588
3589 if (action == HistoryNavigationAction::kSameDocument) {
3590 std::unique_ptr<NavigationRequest> navigation_request =
3591 CreateNavigationRequestFromEntry(
3592 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133593 /*is_same_document_history_load=*/true,
3594 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333595 initiator_frame_token, initiator_process_id,
3596 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573597 if (navigation_request) {
3598 // Only add the request if was properly created. It's possible for the
3599 // creation to fail in certain cases, e.g. when the URL is invalid.
3600 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303601 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573602 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473603 std::unique_ptr<NavigationRequest> navigation_request =
3604 CreateNavigationRequestFromEntry(
3605 frame, pending_entry_, new_item, reload_type,
3606 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433607 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333608 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473609 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 different_document_loads->push_back(std::move(navigation_request));
3613 }
3614 // For a different document, the subframes will be destroyed, so there's
3615 // no need to consider them.
3616 return;
Alex Moshchuke65c39272020-06-03 17:55:373617 } else if (action == HistoryNavigationAction::kStopLooking) {
3618 return;
creis4e2ecb72015-06-20 00:46:303619 }
3620
Yoav Weiss8c573952022-11-17 17:35:133621 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3622 // we currently only support soft navigation heuristics for the top level
3623 // frame.
creis4e2ecb72015-06-20 00:46:303624 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333625 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3626 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373627 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433628 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303629 }
3630}
3631
Harkiran Bolariaba823e42021-05-21 18:30:363632base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243633 const LoadURLParams& params) {
3634 // Find the appropriate FrameTreeNode.
3635 FrameTreeNode* node = nullptr;
Avi Drissmanbd153642024-09-03 18:58:053636 if (params.frame_tree_node_id || !params.frame_name.empty()) {
3637 node = params.frame_tree_node_id
Ali Hijazid87307d2022-11-07 20:15:033638 ? frame_tree_->FindByID(params.frame_tree_node_id)
3639 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503640 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243641 }
3642
3643 // If no FrameTreeNode was specified, navigate the main frame.
3644 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033645 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243646
Camille Lamy5193caa2018-10-12 11:59:423647 // Compute overrides to the LoadURLParams for |override_user_agent|,
3648 // |should_replace_current_entry| and |has_user_gesture| that will be used
3649 // both in the creation of the NavigationEntry and the NavigationRequest.
3650 // Ideally, the LoadURLParams themselves would be updated, but since they are
3651 // passed as a const reference, this is not possible.
3652 // TODO(clamy): When we only create a NavigationRequest, move this to
3653 // CreateNavigationRequestFromLoadURLParams.
3654 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3655 GetLastCommittedEntry());
3656
Rakina Zata Amnie2d31312022-11-18 03:38:453657 // An entry replacement must happen if the current browsing context should
3658 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333659 bool should_replace_current_entry =
3660 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453661 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423662
clamy21718cc22018-06-13 13:34:243663 // Javascript URLs should not create NavigationEntries. All other navigations
3664 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243665 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373666 std::unique_ptr<NavigationEntryImpl> entry =
3667 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3668 should_replace_current_entry,
3669 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243670 DiscardPendingEntry(false);
3671 SetPendingEntry(std::move(entry));
3672 }
3673
Tim Judkins59548192023-05-17 17:51:203674 // Renderer-debug URLs are sent to the current renderer process immediately
3675 // for processing and don't need to create a NavigationRequest. Note: this
3676 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243677 // renderer-debug URLs.
3678 // Note: we intentionally leave the pending entry in place for renderer debug
3679 // URLs, unlike the cases below where we clear it if the navigation doesn't
3680 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303681 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483682 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3683 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153684 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203685 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483686 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363687 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483688 }
3689
clamy21718cc22018-06-13 13:34:243690 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363691 return nullptr;
clamy21718cc22018-06-13 13:34:243692 }
3693
Antonio Sartori78a749f2020-11-30 12:03:393694 DCHECK(pending_entry_);
3695
clamy21718cc22018-06-13 13:34:243696 // Convert navigations to the current URL to a reload.
3697 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3698 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3699 // DevTools sometimes issues navigations to main frames that they do not
3700 // expect to see treated as reload, and it only works because they pass a
3701 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3702 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543703 ReloadType reload_type = params.reload_type;
3704 if (reload_type == ReloadType::NONE &&
3705 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043706 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243707 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243708 params.load_type ==
3709 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543710 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243711 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473712 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393713
3714 // If this is a reload of an existing FrameNavigationEntry and we had a
3715 // policy container for it, then we should copy it into the pending entry,
3716 // so that it is copied to the navigation request in
3717 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453718 FrameNavigationEntry* previous_frame_entry =
3719 GetLastCommittedEntry()->GetFrameEntry(node);
3720 if (previous_frame_entry &&
3721 previous_frame_entry->policy_container_policies()) {
3722 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3723 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393724 }
3725 }
3726
3727 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173728 // document, then we should copy the document polices from RenderFrameHost's
3729 // PolicyContainerHost. The NavigationRequest will create a new
3730 // PolicyContainerHost with the document policies from the |pending_entry_|,
3731 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3732 // the navigation. This way, we ensure that we keep enforcing the right
3733 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453734 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393735 if (node->current_frame_host() &&
3736 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193737 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163738 node->current_frame_host()
3739 ->policy_container_host()
3740 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233741 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393742 }
clamy21718cc22018-06-13 13:34:243743 }
3744
3745 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263746 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243747
Tsuyoshi Horo167ca6432022-03-09 05:16:393748 // This will be used to set the Navigation Timing API navigationStart
3749 // parameter for browser navigations in new tabs (intents, tabs opened through
3750 // "Open link in new tab"). If the navigation must wait on the current
3751 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3752 // will be updated when the BeforeUnload ack is received.
3753 const auto navigation_start_time = base::TimeTicks::Now();
3754
Camille Lamy5193caa2018-10-12 11:59:423755 std::unique_ptr<NavigationRequest> request =
3756 CreateNavigationRequestFromLoadParams(
3757 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143758 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393759 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3760 navigation_start_time);
clamy21718cc22018-06-13 13:34:243761
3762 // If the navigation couldn't start, return immediately and discard the
3763 // pending NavigationEntry.
3764 if (!request) {
3765 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363766 return nullptr;
clamy21718cc22018-06-13 13:34:243767 }
3768
Camille Lamy5193caa2018-10-12 11:59:423769#if DCHECK_IS_ON()
3770 // Safety check that NavigationRequest and NavigationEntry match.
3771 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3772#endif
3773
clamy21718cc22018-06-13 13:34:243774 // This call does not support re-entrancy. See http://crbug.com/347742.
3775 CHECK(!in_navigate_to_pending_entry_);
3776 in_navigate_to_pending_entry_ = true;
3777
arthursonzogni66f711c2019-10-08 14:40:363778 // It is not possible to delete the pending NavigationEntry while navigating
3779 // to it. Grab a reference to delay potential deletion until the end of this
3780 // function.
3781 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3782
Harkiran Bolariaba823e42021-05-21 18:30:363783 base::WeakPtr<NavigationHandle> created_navigation_handle(
3784 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053785 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243786
3787 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363788 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243789}
3790
clamyea99ea12018-05-28 13:54:233791void NavigationControllerImpl::HandleRendererDebugURL(
3792 FrameTreeNode* frame_tree_node,
3793 const GURL& url) {
3794 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243795 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3796 // the renderer process is not live, unless it is the initial navigation
3797 // of the tab.
clamyea99ea12018-05-28 13:54:233798 if (!IsInitialNavigation()) {
3799 DiscardNonCommittedEntries();
3800 return;
3801 }
Fergal Dalyecd3b0202020-06-25 01:57:373802 // The current frame is always a main frame. If IsInitialNavigation() is
3803 // true then there have been no navigations and any frames of this tab must
3804 // be in the same renderer process. If that has crashed then the only frame
3805 // that can be revived is the main frame.
3806 frame_tree_node->render_manager()
3807 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233808 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223809
3810 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3811 // notification, so set is loading to true here to properly surface it when
3812 // the renderer process is done handling the URL.
Alison Gale81f4f2c72024-04-22 19:33:313813 // TODO(crbug.com/40199456): Remove the test dependency on this behavior.
Julie Jeongeun Kim50d124c2022-10-21 13:51:223814 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223815 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223816 }
clamyea99ea12018-05-28 13:54:233817 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3818}
3819
clamy21718cc22018-06-13 13:34:243820std::unique_ptr<NavigationEntryImpl>
3821NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3822 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423823 const LoadURLParams& params,
3824 bool override_user_agent,
3825 bool should_replace_current_entry,
3826 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393827 // Browser initiated navigations might not have a blob_url_loader_factory set
3828 // in params even if the navigation is to a blob URL. If that happens, lookup
3829 // the correct url loader factory to use here.
3830 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483831 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473832 // Resolve the blob URL in the storage partition associated with the target
3833 // frame. This is the storage partition the URL will be loaded in, and only
3834 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393835 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473836 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393837 }
3838
clamy21718cc22018-06-13 13:34:243839 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443840 // extra_headers in params are \n separated; navigation entries want \r\n.
3841 std::string extra_headers_crlf;
3842 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243843
3844 // For subframes, create a pending entry with a corresponding frame entry.
3845 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453846 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243847 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083848 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243849 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373850 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213851 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3852 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393853 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163854 // a conversion of a new navigation into a reload, we will set the right
3855 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193856 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243857 } else {
3858 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173859 // If `node` is the outermost main frame, it rewrites a virtual url in order
3860 // to adjust the original input url if needed. For inner frames such as
3861 // fenced frames or subframes, they don't rewrite urls as the urls are not
3862 // input urls by users.
3863 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323864 scoped_refptr<SiteInstance> source_site_instance =
3865 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373866 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323867 if (source_site_instance && source_site_instance->HasProcess()) {
3868 source_process_site_url =
3869 source_site_instance->GetProcess()->GetProcessLock().site_url();
3870 }
clamy21718cc22018-06-13 13:34:243871 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063872 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323873 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213874 params.transition_type, params.is_renderer_initiated,
3875 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3876 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243877 entry->set_source_site_instance(
3878 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3879 entry->SetRedirectChain(params.redirect_chain);
3880 }
3881
3882 // Set the FTN ID (only used in non-site-per-process, for tests).
3883 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243884 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423885 entry->SetIsOverridingUserAgent(override_user_agent);
3886 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543887 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243888
clamy21718cc22018-06-13 13:34:243889 switch (params.load_type) {
3890 case LOAD_TYPE_DEFAULT:
3891 break;
3892 case LOAD_TYPE_HTTP_POST:
3893 entry->SetHasPostData(true);
3894 entry->SetPostData(params.post_data);
3895 break;
3896 case LOAD_TYPE_DATA:
Shu Yang112ad492024-07-25 17:11:543897 // LoadDataWithBaseURL is a special case that needs to assign both a base
3898 // URL and a virtual URL, while loading the actual content from a data
3899 // URL.
clamy21718cc22018-06-13 13:34:243900 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
Shu Yang112ad492024-07-25 17:11:543901 entry->SetVirtualURL(params.virtual_url_for_special_cases);
Xiaohan Wang7f8052e02022-01-14 18:44:283902#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243903 entry->SetDataURLAsString(params.data_url_as_string);
3904#endif
3905 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3906 break;
Shu Yang112ad492024-07-25 17:11:543907#if BUILDFLAG(IS_ANDROID)
3908 case LOAD_TYPE_PDF_ANDROID:
3909 // Android PDF URLs show the actual PDF URL as a virtual URL, while an
3910 // internal URL is used for the navigation URL.
3911 entry->SetVirtualURL(params.virtual_url_for_special_cases);
3912 break;
3913#endif
clamy21718cc22018-06-13 13:34:243914 }
3915
3916 // TODO(clamy): NavigationEntry is meant for information that will be kept
3917 // after the navigation ended and therefore is not appropriate for
3918 // started_from_context_menu. Move started_from_context_menu to
3919 // NavigationUIData.
3920 entry->set_started_from_context_menu(params.started_from_context_menu);
3921
3922 return entry;
3923}
3924
clamyea99ea12018-05-28 13:54:233925std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423926NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3927 FrameTreeNode* node,
3928 const LoadURLParams& params,
3929 bool override_user_agent,
3930 bool should_replace_current_entry,
3931 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143932 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423933 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573934 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393935 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223936 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493937 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453938 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583939 bool is_container_initiated,
W. James MacLean443ef3e2024-07-16 13:42:343940 net::StorageAccessApiStatus storage_access_api_status,
Arthur Sonzognic686e8f2024-01-11 08:36:373941 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573942 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Charlie Reisf21cd182024-08-09 21:44:523943
3944 // TODO(https://crbug.com/40467594): Add a CHECK(frame_entry) once all
3945 // subframes have FrameNavigationEntries associated with them. Until then,
3946 // there may be cases where a subframe navigation is missing `frame_entry`
3947 // (e.g., see https://crbug.com/358084015).
3948
Nasko Oskov3c2f9e252019-01-10 17:45:533949 // All renderer-initiated navigations must have an initiator_origin.
3950 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513951
Camille Lamy5193caa2018-10-12 11:59:423952 GURL url_to_load;
3953 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323954
Camille Lamy2baa8022018-10-19 16:43:173955 // For main frames, rewrite the URL if necessary and compute the virtual URL
3956 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263957 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423958 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173959 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423960 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423961
Shu Yang112ad492024-07-25 17:11:543962 // Both LoadDataWithBaseURL and Android PDF navigations are special cases
3963 // that need to define a virtual URL to display, which differs from the
3964 // navigation URL.
3965 if (params.load_type == LOAD_TYPE_DATA) {
3966 virtual_url = params.virtual_url_for_special_cases;
3967 }
3968#if BUILDFLAG(IS_ANDROID)
3969 if (params.load_type == LOAD_TYPE_PDF_ANDROID) {
3970 virtual_url = params.virtual_url_for_special_cases;
3971 }
3972#endif
Camille Lamy5193caa2018-10-12 11:59:423973
Camille Lamy2baa8022018-10-19 16:43:173974 if (virtual_url.is_empty())
3975 virtual_url = url_to_load;
3976
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573977 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283978
Aran Gilman249eb122019-12-02 23:32:463979 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3980 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3981 // return different results, leading to a different URL in the
3982 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3983 // pending NavigationEntry, as we'll only make one call to
3984 // RewriteUrlForNavigation.
Charlie Reisf21cd182024-08-09 21:44:523985 if (frame_entry) {
3986 VLOG_IF(1, (url_to_load != frame_entry->url()))
3987 << "NavigationRequest and FrameEntry have different URLs: "
3988 << url_to_load << " vs " << frame_entry->url();
3989 }
Camille Lamyb9ed3c52018-11-19 15:34:283990
Camille Lamy2baa8022018-10-19 16:43:173991 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423992 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173993 // NavigationRequest.
3994 } else {
3995 url_to_load = params.url;
3996 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243997 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173998 }
Camille Lamy5193caa2018-10-12 11:59:423999
Ehsan Karamad44fc72112019-02-26 18:15:474000 if (node->render_manager()->is_attaching_inner_delegate()) {
4001 // Avoid starting any new navigations since this node is now preparing for
4002 // attaching an inner delegate.
4003 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204004 }
Camille Lamy5193caa2018-10-12 11:59:424005
Alex Moshchuk99242832023-05-22 17:21:444006 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:424007 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:444008 }
Camille Lamy5193caa2018-10-12 11:59:424009
danakjd83d706d2020-11-25 22:11:124010 // Look for a pending commit that is to another document in this
4011 // FrameTreeNode. If one exists, then the last committed URL will not be the
4012 // current URL by the time this navigation commits.
4013 bool has_pending_cross_document_commit =
4014 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:214015 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124016
Minggang Wangb9f3fa92021-07-01 15:30:314017 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:494018 /*old_url=*/node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524019 /*new_url=*/url_to_load, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494020 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:134021 /*is_same_document_history_load=*/false,
4022 is_embedder_initiated_fenced_frame_navigation,
4023 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:424024
4025 // Create the NavigationParams based on |params|.
4026
Hiroki Nakagawa4ed61282021-06-18 05:37:234027 bool is_view_source_mode = entry->IsViewSourceMode();
4028 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:294029
Antonio Sartori6984c742021-08-26 08:03:414030 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:294031
Hiroki Nakagawa4ed61282021-06-18 05:37:234032 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:294033 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:254034 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:294035
Charlie Reisf21cd182024-08-09 21:44:524036 std::string page_state_data =
4037 frame_entry ? frame_entry->page_state().ToEncodedData() : std::string();
4038
Minggang Wangb9f3fa92021-07-01 15:30:314039 blink::mojom::CommonNavigationParamsPtr common_params =
4040 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:214041 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514042 blink::mojom::Referrer::New(params.referrer.url,
4043 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:214044 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514045 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:394046 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514047 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:144048 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:414049 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:274050 false /* has_text_fragment_token */,
4051 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
4052 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514053 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:054054 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:424055
Minggang Wangb9f3fa92021-07-01 15:30:314056 blink::mojom::CommitNavigationParamsPtr commit_params =
4057 blink::mojom::CommitNavigationParams::New(
Arthur Sonzognic686e8f2024-01-11 08:36:374058 std::nullopt,
Ari Chivukulac7533522024-05-14 21:52:344059 // The correct storage key will be computed before committing the
4060 // navigation.
4061 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:324062 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:504063 std::vector<net::RedirectInfo>(), params.post_content_type,
4064 common_params->url, common_params->method,
Charlie Reisf21cd182024-08-09 21:44:524065 params.can_load_local_resources, page_state_data,
4066 entry->GetUniqueID(), entry->GetSubframeUniqueNames(node),
Yoav Weiss8c573952022-11-17 17:35:134067 /*intended_as_new_entry=*/true,
4068 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:144069 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
4070 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134071 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314072 params.should_clear_history_list,
4073 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224074 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134075 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514076 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284077#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134078 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144079#endif
Yoav Weiss8c573952022-11-17 17:35:134080 /*is_browser_initiated=*/!params.is_renderer_initiated,
Khushal Sagar71837ad82024-08-09 18:03:154081 /*has_ua_visual_transition*/ false,
Yoav Weiss8c573952022-11-17 17:35:134082 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074083 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134084 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4085 /*origin_agent_cluster=*/false,
4086 /*origin_agent_cluster_left_as_default=*/true,
4087 /*enabled_client_hints=*/
4088 std::vector<network::mojom::WebClientHintsType>(),
Liam Brady38b84562024-03-07 22:11:264089 /*is_cross_site_cross_browsing_context_group=*/false,
4090 /*should_have_sticky_user_activation=*/false,
4091 /*old_page_info=*/nullptr,
Yoav Weiss8c573952022-11-17 17:35:134092 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014093 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134094 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584095 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134096 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134097 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284098 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134099 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444100 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424101 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374102 /*view_transition_state=*/std::nullopt,
4103 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054104 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464105 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374106 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054107 /*not_restored_reasons=*/nullptr,
Chris Fredrickson9ffdf5b2024-07-09 20:05:094108 /*load_with_storage_access=*/
4109 net::StorageAccessApiStatus::kNone,
Arthur Sonzognic686e8f2024-01-11 08:36:374110 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374111 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Kyra800d1d012024-03-27 17:05:484112 /*cookie_deprecation_label=*/std::nullopt,
Khushal Sagar81f89812024-06-11 13:40:314113 /*visited_link_salt=*/std::nullopt,
4114 /*local_surface_id=*/std::nullopt);
Xiaohan Wang7f8052e02022-01-14 18:44:284115#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424116 if (ValidateDataURLAsString(params.data_url_as_string)) {
danakj529a3eba2024-04-18 20:14:564117 commit_params->data_url_as_string = params.data_url_as_string->as_string();
Camille Lamy5193caa2018-10-12 11:59:424118 }
4119#endif
4120
Lucas Furukawa Gadania9c45682019-07-31 22:05:144121 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074122 commit_params->navigation_timing->system_entropy_at_navigation_start =
4123 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4124 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424125
Camille Lamy5193caa2018-10-12 11:59:424126 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4127 std::string extra_headers_crlf;
4128 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094129
Alex Moshchuk9321e6a2022-12-07 21:58:314130 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144131 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084132 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094133 params.initiator_frame_token, params.initiator_process_id,
4134 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214135 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294136 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454137 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
W. James MacLean443ef3e2024-07-16 13:42:344138 is_container_initiated, params.has_rel_opener, storage_access_api_status,
Kevin McNee6455638a2024-06-27 22:05:034139 embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094140 navigation_request->set_from_download_cross_origin_redirect(
4141 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554142 navigation_request->set_force_new_browsing_instance(
4143 params.force_new_browsing_instance);
Mustafa Emre Acer1001b3d2024-07-09 23:10:434144 if (params.force_no_https_upgrade) {
4145 navigation_request->set_force_no_https_upgrade();
4146 }
Yao Xiaodc5ed102019-06-04 19:19:094147 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424148}
4149
4150std::unique_ptr<NavigationRequest>
4151NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234152 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574153 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234154 FrameNavigationEntry* frame_entry,
4155 ReloadType reload_type,
4156 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434157 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374158 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334159 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374160 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134161 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344162 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234163 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434164 // We should never navigate to an existing initial NavigationEntry that is the
4165 // initial NavigationEntry for the initial empty document that hasn't been
4166 // overridden by the synchronous about:blank commit, to preserve previous
4167 // behavior where trying to reload when the main frame is on the initial empty
4168 // document won't result in a navigation.
4169 // See also https://crbug.com/1277414.
4170 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324171
clamyea99ea12018-05-28 13:54:234172 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234173
Ehsan Karamad44fc72112019-02-26 18:15:474174 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4175 // Avoid starting any new navigations since this node is now preparing for
4176 // attaching an inner delegate.
4177 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204178 }
4179
Alex Moshchuk99242832023-05-22 17:21:444180 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4181 dest_url)) {
clamyea99ea12018-05-28 13:54:234182 return nullptr;
4183 }
4184
clamyea99ea12018-05-28 13:54:234185 // This will be used to set the Navigation Timing API navigationStart
4186 // parameter for browser navigations in new tabs (intents, tabs opened through
4187 // "Open link in new tab"). If the navigation must wait on the current
4188 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4189 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074190
clamyea99ea12018-05-28 13:54:234191 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074192 const auto navigation_start_system_entropy =
4193 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4194 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234195
danakjd83d706d2020-11-25 22:11:124196 // Look for a pending commit that is to another document in this
4197 // FrameTreeNode. If one exists, then the last committed URL will not be the
4198 // current URL by the time this navigation commits.
4199 bool has_pending_cross_document_commit =
4200 frame_tree_node->render_manager()
4201 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494202 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214203 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124204
Minggang Wangb9f3fa92021-07-01 15:30:314205 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124206 /*old_url=*/frame_tree_node->current_url(),
Charlie Reisf21cd182024-08-09 21:44:524207 /*new_url=*/dest_url, reload_type, entry, frame_entry,
danakjb952ef12021-01-14 19:58:494208 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494209 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134210 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494211 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424212
4213 // A form submission may happen here if the navigation is a
4214 // back/forward/reload navigation that does a form resubmission.
4215 scoped_refptr<network::ResourceRequestBody> request_body;
4216 std::string post_content_type;
Alison Galed94ce4f2024-04-22 15:20:394217 // TODO(crbug.com/41440869) Store |is_form_submission| in the history
jongdeok.kim5de823b32022-06-14 04:37:504218 // entry. This way, it could be directly retrieved here. Right now, it is only
4219 // partially recovered when request.method == "POST" and request.body exists.
4220 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424221 if (frame_entry->method() == "POST") {
4222 request_body = frame_entry->GetPostData(&post_content_type);
4223 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304224 post_content_type = std::string(
4225 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504226 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424227 }
4228
4229 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314230 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514231 entry->ConstructCommonNavigationParams(
4232 *frame_entry, request_body, dest_url,
4233 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384234 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534235 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514236 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554237 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424238
4239 // TODO(clamy): |intended_as_new_entry| below should always be false once
4240 // Reload no longer leads to this being called for a pending NavigationEntry
4241 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314242 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144243 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404244 *frame_entry, common_params->url, common_params->method,
4245 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144246 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534247 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484248 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134249 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074250 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144251 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074252 commit_params->navigation_timing->system_entropy_at_navigation_start =
4253 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4254 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424255
W. James MacLeanb7d6092682022-10-05 15:23:264256 if (common_params->url.IsAboutSrcdoc()) {
4257 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4258 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594259 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264260 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334261 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314262 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144263 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434264 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334265 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4266 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374267 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294268 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4269 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474270 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234271}
4272
[email protected]d202a7c2012-01-04 07:53:474273void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214274 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274275 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404276
Takashi Toyoshimaea534ef22021-07-21 03:27:594277 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404278 // location bar will have up-to-date information about the security style
4279 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134280 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404281
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374282 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574283 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294284}
4285
initial.commit09911bf2008-07-26 23:55:294286// static
[email protected]d202a7c2012-01-04 07:53:474287size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234288 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154289 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214290 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234291}
4292
[email protected]d202a7c2012-01-04 07:53:474293void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224294 if (is_active && needs_reload_)
4295 LoadIfNecessary();
Khushal Sagarace0e7342024-08-07 21:34:214296
4297 if (frame_tree_->is_primary();
4298 auto* cache = GetNavigationEntryScreenshotCache()) {
4299 cache->SetVisible(is_active);
4300 }
initial.commit09911bf2008-07-26 23:55:294301}
4302
[email protected]d202a7c2012-01-04 07:53:474303void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034304 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4305 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294306 if (!needs_reload_)
4307 return;
4308
Bo Liucdfa4b12018-11-06 00:21:444309 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4310 needs_reload_type_);
4311
initial.commit09911bf2008-07-26 23:55:294312 // Calling Reload() results in ignoring state, and not loading.
Xinghui Lue4e50be2024-05-15 21:46:004313 // Explicitly use NavigateToExistingPendingEntry so that the renderer uses the
initial.commit09911bf2008-07-26 23:55:294314 // cached state.
Xinghui Lue4e50be2024-05-15 21:46:004315 if (entry_replaced_by_post_commit_error_) {
4316 // If the current entry is a post commit error, we reload the entry it
4317 // replaced instead. We leave the error entry in place until a commit
4318 // replaces it, but the pending entry points to the original entry in the
4319 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
4320 // case that pending_entry_ != entries_[pending_entry_index_].
4321 // Note that this handling is similar to
4322 // `NavigationControllerImpl::Reload()`.
4323 pending_entry_ = entry_replaced_by_post_commit_error_.get();
4324 pending_entry_index_ = GetCurrentEntryIndex();
4325 NavigateToExistingPendingEntry(
4326 ReloadType::NONE,
4327 /*initiator_rfh=*/nullptr,
4328 /*soft_navigation_heuristics_task_id=*/std::nullopt,
4329 /*navigation_api_key=*/nullptr);
4330 } else if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134331 NavigateToExistingPendingEntry(
4332 ReloadType::NONE,
4333 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374334 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134335 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454336 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434337 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274338 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344339 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134340 NavigateToExistingPendingEntry(
4341 ReloadType::NONE,
4342 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374343 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134344 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344345 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434346 // We should never navigate to an existing initial NavigationEntry that is
4347 // the initial NavigationEntry for the initial empty document that hasn't
4348 // been overridden by the synchronous about:blank commit, to preserve
4349 // legacy behavior where trying to reload when the main frame is on the
4350 // initial empty document won't result in a navigation. See also
4351 // https://crbug.com/1277414. If there is something to reload, the
4352 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4353 // it here.
avicc872d7242015-08-19 21:26:344354 needs_reload_ = false;
4355 }
initial.commit09911bf2008-07-26 23:55:294356}
4357
Kevin McNeeccca6172021-10-19 17:11:144358base::WeakPtr<NavigationHandle>
4359NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364360 RenderFrameHost* render_frame_host,
4361 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364362 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134363 RenderFrameHostImpl* rfhi =
4364 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584365
4366 // Only active documents can load post-commit error pages:
4367 // - If the document is in pending deletion, the browser already committed to
4368 // destroying this RenderFrameHost so ignore loading the error page.
4369 // - If the document is in back-forward cache, it's not allowed to navigate as
4370 // it should remain frozen. Ignore the request and evict the document from
4371 // back-forward cache.
4372 // - If the document is prerendering, it can navigate but when loading error
4373 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114374 if (rfhi->IsInactiveAndDisallowActivation(
4375 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144376 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114377 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584378
Rakina Zata Amni919b7922020-12-11 09:03:134379 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414380
Minggang Wangb9f3fa92021-07-01 15:30:314381 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434382 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594383 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4384 // the frame actually committed (e.g. iframe with "src" set to a
4385 // slow-responding URL). We should rewrite the URL to about:blank in this
4386 // case, as the renderer will only think a page is an error page if it has a
4387 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134388 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314389 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434390 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334391 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414392
Mike Jacksone2aa7af2023-05-17 06:45:074393 commit_params->navigation_timing->system_entropy_at_navigation_start =
4394 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4395 node, blink::mojom::SystemEntropy::kNormal);
4396
arthursonzogni70ac7302020-05-28 08:49:054397 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4398 // error pages.
Liam Brady34639ec92023-10-13 19:50:454399 commit_params->frame_policy = node->pending_frame_policy();
arthursonzogni70ac7302020-05-28 08:49:054400
John Delaney131ad362019-08-08 21:57:414401 std::unique_ptr<NavigationRequest> navigation_request =
4402 NavigationRequest::CreateBrowserInitiated(
4403 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094404 false /* was_opener_suppressed */, "" /* extra_headers */,
4405 nullptr /* frame_entry */, nullptr /* entry */,
4406 false /* is_form_submission */, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374407 std::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364408 navigation_request->set_post_commit_error_page_html(error_page_html);
Lei Zhanga4770832023-07-19 18:02:364409 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
Charlie Reis09952ee2022-12-08 16:35:074410 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414411 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144412
4413 // Calling BeginNavigation may destroy the NavigationRequest.
4414 base::WeakPtr<NavigationRequest> created_navigation_request(
4415 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414416 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144417 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414418}
4419
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574420void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214421 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094422 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154423 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144424 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294425}
4426
[email protected]d202a7c2012-01-04 07:53:474427void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364428 RestoreType type) {
Alison Gale770f3fc2024-04-27 00:39:584429 // TODO(crbug.com/40816356): Don't allow an index of -1, which would
Charlie Reis23c26da2022-01-29 00:57:474430 // represent a no-committed-entry state.
4431 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364432 ConfigureEntriesForRestore(&entries_, type);
Alison Gale770f3fc2024-04-27 00:39:584433 // TODO(crbug.com/40816356): This will be pointing to the wrong entry
Charlie Reis23c26da2022-01-29 00:57:474434 // if `entries_` contains pre-existing entries from the NavigationController
4435 // before restore, which would not be removed and will be at the front of the
4436 // entries list, causing the index to be off by the amount of pre-existing
4437 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294438 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294439}
[email protected]765b35502008-08-21 00:51:204440
arthursonzogni69a6a1b2019-09-17 09:23:004441void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004442 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4443}
4444
4445void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4446 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474447 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104448 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4449 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294450 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474451 return;
Michael Thiessenc5676d22019-09-25 22:32:104452 }
avi45a72532015-04-07 21:01:454453 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314454
4455 if (!delegate_)
4456 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374457 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484458}
4459
avi7c6f35e2015-05-08 17:52:384460int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4461 int nav_entry_id) const {
4462 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4463 if (entries_[i]->GetUniqueID() == nav_entry_id)
4464 return i;
4465 }
4466 return -1;
4467}
4468
[email protected]d202a7c2012-01-04 07:53:474469void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574470 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254471 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574472 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594473 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254474 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374475 // Normally, cloning a NavigationEntryImpl results in sharing
4476 // FrameNavigationEntries between the original and the clone. However, when
4477 // cloning from a different NavigationControllerImpl, we want to fork the
4478 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374479 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594480 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254481 }
Rakina Zata Amnie2d31312022-11-18 03:38:454482 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274483 DCHECK(pending_entry_index_ == -1 ||
4484 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254485}
[email protected]c5b88d82012-10-06 17:03:334486
4487void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184488 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334489 get_timestamp_callback_ = get_timestamp_callback;
4490}
[email protected]8ff00d72012-10-23 19:12:214491
Shivani Sharmaffb32b82019-04-09 16:58:474492// History manipulation intervention:
4493void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474494 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564495 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404496 bool is_renderer_initiated,
4497 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564498 // Note that for a subframe,
4499 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454500 // gesture happened in any subframe (propagated to main frame) or in the main
4501 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564502 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274503 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474504 return;
4505 }
4506 if (last_committed_entry_index_ == -1)
4507 return;
4508
Shivani Sharmac4cc8922019-04-18 03:11:174509 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474510
Alexander Timine3ec4192020-04-20 16:39:404511 // Log UKM with the URL we are navigating away from.
4512 ukm::builders::HistoryManipulationIntervention(
4513 previous_page_load_ukm_source_id)
4514 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474515}
4516
Shivani Sharmac4cc8922019-04-18 03:11:174517void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4518 int reference_index,
4519 bool skippable) {
4520 auto* reference_entry = GetEntryAtIndex(reference_index);
4521 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4522
4523 int64_t document_sequence_number =
4524 reference_entry->root_node()->frame_entry->document_sequence_number();
4525 for (int index = 0; index < GetEntryCount(); index++) {
4526 auto* entry = GetEntryAtIndex(index);
4527 if (entry->root_node()->frame_entry->document_sequence_number() ==
4528 document_sequence_number) {
4529 entry->set_should_skip_on_back_forward_ui(skippable);
4530 }
4531 }
4532}
4533
arthursonzogni66f711c2019-10-08 14:40:364534std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4535NavigationControllerImpl::ReferencePendingEntry() {
4536 DCHECK(pending_entry_);
4537 auto pending_entry_ref =
4538 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4539 pending_entry_refs_.insert(pending_entry_ref.get());
4540 return pending_entry_ref;
4541}
4542
4543void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4544 // Ignore refs that don't correspond to the current pending entry.
4545 auto it = pending_entry_refs_.find(ref);
4546 if (it == pending_entry_refs_.end())
4547 return;
4548 pending_entry_refs_.erase(it);
4549
4550 if (!pending_entry_refs_.empty())
4551 return;
4552
4553 // The pending entry may be deleted before the last PendingEntryRef.
4554 if (!pending_entry_)
4555 return;
4556
4557 // We usually clear the pending entry when the matching NavigationRequest
4558 // fails, so that an arbitrary URL isn't left visible above a committed page.
4559 //
4560 // However, we do preserve the pending entry in some cases, such as on the
4561 // initial navigation of an unmodified blank tab. We also allow the delegate
4562 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4563 // user edit the URL and try again. This may be useful in cases that the
4564 // committed page cannot be attacker-controlled. In these cases, we still
4565 // allow the view to clear the pending entry and typed URL if the user
4566 // requests (e.g., hitting Escape with focus in the address bar).
4567 //
4568 // Do not leave the pending entry visible if it has an invalid URL, since this
4569 // might be formatted in an unexpected or unsafe way.
4570 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364571 bool should_preserve_entry =
4572 (pending_entry_ == GetVisibleEntry()) &&
4573 pending_entry_->GetURL().is_valid() &&
4574 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4575 if (should_preserve_entry)
4576 return;
4577
4578 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374579 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364580}
4581
Titouan Rigoudy6ec70402021-02-02 15:42:194582std::unique_ptr<PolicyContainerPolicies>
4583NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394584 RenderFrameHostImpl* rfh,
4585 bool is_same_document,
Antonio Sartorib8addf62024-09-16 07:59:214586 bool navigation_encountered_error,
Rakina Zata Amniafd3c6582021-11-30 06:19:174587 const GURL& url) {
Antonio Sartorib8addf62024-09-16 07:59:214588 if (navigation_encountered_error) {
4589 // We should never reload the policy container of an error page from
4590 // history, see https://crbug.com/364773822.
4591 return nullptr;
4592 }
4593
Antonio Sartori78a749f2020-11-30 12:03:394594 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454595 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394596 FrameNavigationEntry* previous_frame_entry =
4597 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4598
Alison Gale770f3fc2024-04-27 00:39:584599 // TODO(crbug.com/40467594): Remove this nullptr check when we can
Antonio Sartori78a749f2020-11-30 12:03:394600 // ensure we always have a FrameNavigationEntry here.
4601 if (!previous_frame_entry)
4602 return nullptr;
4603
Titouan Rigoudy6ec70402021-02-02 15:42:194604 const PolicyContainerPolicies* previous_policies =
4605 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394606
Titouan Rigoudy6ec70402021-02-02 15:42:194607 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394608 return nullptr;
4609
4610 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234611 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394612 }
4613
Titouan Rigoudy72f892d2022-05-02 18:21:234614 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394615}
4616
Hayato Ito2c8c08d02021-06-23 03:38:434617void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504618 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434619 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4620 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4621 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504622
4623 auto callback = base::BindRepeating(
4624 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4625 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4626 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4627 }
4628 },
Hayato Ito2c8c08d02021-06-23 03:38:434629 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034630 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504631}
4632
4633void NavigationControllerImpl::DidAccessInitialMainDocument() {
4634 // We may have left a failed browser-initiated navigation in the address bar
4635 // to let the user edit it and try again. Clear it now that content might
4636 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034637 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504638 DiscardPendingEntry(false);
4639
4640 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374641 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504642}
4643
4644void NavigationControllerImpl::UpdateStateForFrame(
4645 RenderFrameHostImpl* rfhi,
4646 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564647 OPTIONAL_TRACE_EVENT1("content",
4648 "NavigationControllerImpl::UpdateStateForFrame",
4649 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504650 // The state update affects the last NavigationEntry associated with the given
4651 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4652 // in the case of an UpdateState from a frame being swapped out). We track
4653 // which entry this is in the RenderFrameHost's nav_entry_id.
4654 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4655 if (!entry)
4656 return;
4657
4658 FrameNavigationEntry* frame_entry =
4659 entry->GetFrameEntry(rfhi->frame_tree_node());
4660 if (!frame_entry)
4661 return;
4662
4663 // The SiteInstance might not match if we do a cross-process navigation with
4664 // replacement (e.g., auto-subframe), in which case the swap out of the old
4665 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4666 // has already been replaced and destroyed.
4667 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4668 return;
4669
4670 if (page_state == frame_entry->page_state())
4671 return; // Nothing to update.
4672
4673 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4674
4675 // The document_sequence_number and item_sequence_number recorded in the
4676 // FrameNavigationEntry should not differ from the one coming with the update,
4677 // since it must come from the same document. Do not update it if a difference
4678 // is detected, as this indicates that |frame_entry| is not the correct one.
4679 blink::ExplodedPageState exploded_state;
4680 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4681 return;
4682
4683 if (exploded_state.top.document_sequence_number !=
4684 frame_entry->document_sequence_number() ||
4685 exploded_state.top.item_sequence_number !=
4686 frame_entry->item_sequence_number()) {
4687 return;
4688 }
4689
4690 frame_entry->SetPageState(page_state);
4691 NotifyEntryChanged(entry);
4692}
4693
Nate Chapina2c881f52023-11-07 17:02:094694namespace {
4695
4696// The caller is responsible for ensuring the entry is same-origin to the
4697// origin to be committed.
4698blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4699 FrameNavigationEntry* frame_entry,
4700 int64_t pending_document_sequence_number) {
4701 blink::ExplodedPageState exploded_state;
4702 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4703 &exploded_state)) {
4704 return nullptr;
4705 }
4706 blink::ExplodedFrameState frame_state = exploded_state.top;
4707
4708 // If the document represented by this FNE hid its full url from appearing in
4709 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4710 // in the navigation API as well (unless we're navigating to that document).
4711 std::u16string url;
4712 if (pending_document_sequence_number ==
4713 frame_entry->document_sequence_number() ||
4714 !frame_entry->protect_url_in_navigation_api()) {
4715 url = frame_state.url_string.value_or(std::u16string());
4716 }
4717
4718 return blink::mojom::NavigationApiHistoryEntry::New(
4719 frame_state.navigation_api_key.value_or(std::u16string()),
4720 frame_state.navigation_api_id.value_or(std::u16string()), url,
4721 frame_state.item_sequence_number, frame_state.document_sequence_number,
4722 frame_state.navigation_api_state);
4723}
4724
4725} // namespace
4726
Domenic Denicolacd30f5f82022-03-16 21:48:014727std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4728NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574729 Direction direction,
4730 int entry_index,
4731 const url::Origin& pending_origin,
4732 FrameTreeNode* node,
4733 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304734 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094735 int64_t pending_document_sequence_number,
4736 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014737 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454738 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174739 // Don't process the initial entry.
4740 DCHECK_EQ(GetEntryCount(), 1);
4741 return entries;
4742 }
Nate Chapind1fe3612021-04-16 20:45:574743 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304744 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574745 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4746 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094747 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574748 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414749 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574750 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014751 // An entry should only appear in the navigation API entries if it is for
4752 // the same origin as the document being committed. Check the committed
4753 // origin, or if that is not available (during restore), check against the
4754 // FNE's url.
Alison Gale770f3fc2024-04-27 00:39:584755 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapina2c881f52023-11-07 17:02:094756 // once we can be sure that entries with the same ISN will never be
4757 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414758 url::Origin frame_entry_origin =
4759 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4760 frame_entry->url(),
4761 frame_entry->initiator_origin().value_or(url::Origin())));
4762 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574763 break;
4764 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4765 continue;
Nate Chapina2c881f52023-11-07 17:02:094766 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4767 ToNavigationApiHistoryEntry(frame_entry,
4768 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304769 DCHECK(entry->url.empty() ||
4770 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574771 entries.push_back(std::move(entry));
4772 previous_item_sequence_number = frame_entry->item_sequence_number();
4773 }
4774 }
4775 // If |entries| was constructed by iterating backwards from
4776 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4777 // earliest-at-the-front. Reverse it.
4778 if (direction == Direction::kBack)
4779 std::reverse(entries.begin(), entries.end());
4780 return entries;
4781}
4782
Domenic Denicolacd30f5f82022-03-16 21:48:014783blink::mojom::NavigationApiHistoryEntryArraysPtr
4784NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554785 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574786 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404787 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444788 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404789 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574790
Nate Chapind1fe3612021-04-16 20:45:574791 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554792 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574793
Nate Chapine82339d02022-05-03 23:48:254794 // NOTE: |entry_index| is the index where this entry will commit if no
4795 // modifications are made between now and DidCommitNavigation. This is used to
4796 // walk |entries_| and determine which entries should be exposed by the
4797 // navigation API. It is important to calculate this correctly, because blink
4798 // will cancel a same-document history commit if it's not present in the
4799 // entries blink knows about.
4800 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574801 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304802 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254803 bool will_create_new_entry = false;
4804 if (GetPendingEntryIndex() != -1) {
4805 entry_index = GetPendingEntryIndex();
4806 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4807 pending_item_sequence_number = frame_entry->item_sequence_number();
4808 pending_document_sequence_number =
4809 frame_entry->document_sequence_number();
4810 }
4811 } else if (request &&
4812 !NavigationTypeUtils::IsReload(
4813 request->common_params().navigation_type) &&
4814 !NavigationTypeUtils::IsHistory(
4815 request->common_params().navigation_type) &&
4816 !request->common_params().should_replace_current_entry &&
4817 !request->common_params()
4818 .is_history_navigation_in_new_child_frame) {
4819 will_create_new_entry = true;
4820 entry_index = GetLastCommittedEntryIndex() + 1;
4821 // Don't set pending_item_sequence_number or
4822 // pending_document_sequence_number in this case - a new unique isn/dsn will
4823 // be calculated in the renderer later.
4824 } else if (GetLastCommittedEntryIndex() != -1) {
4825 entry_index = GetLastCommittedEntryIndex();
4826 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574827 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304828 pending_document_sequence_number =
4829 frame_entry->document_sequence_number();
4830 }
Nate Chapind1fe3612021-04-16 20:45:574831 }
4832
Domenic Denicolacd30f5f82022-03-16 21:48:014833 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254834 if (entry_index == -1) {
4835 // TODO(rakina): Exit early when there is no last committed entry.
4836 // Remove when InitialNavigationEntry ships.
4837 return entry_arrays;
4838 }
4839
Nate Chapina2c881f52023-11-07 17:02:094840 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014841 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574842 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094843 pending_item_sequence_number, pending_document_sequence_number,
4844 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574845
4846 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094847 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574848 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014849 entry_arrays->forward_entries =
4850 PopulateSingleNavigationApiHistoryEntryVector(
4851 Direction::kForward, entry_index, pending_origin, node,
4852 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094853 pending_document_sequence_number, forwardmost_index);
4854 }
4855
4856 // If the previous entry is within the block of contiguous entries being
4857 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254858 FrameNavigationEntry* previous_entry = nullptr;
4859 if (frame_tree_->is_prerendering()) {
Avi Drissmanbd153642024-09-03 18:58:054860 FrameTreeNodeId initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4861 .initiator_frame_tree_node_id();
4862 if (initiator_id) {
Nate Chapinc06cf80a2023-11-18 01:12:254863 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4864 previous_entry = initiator_node->frame_tree()
4865 .controller()
4866 .GetLastCommittedEntry()
4867 ->GetFrameEntry(initiator_node);
4868 }
4869 } else if (GetLastCommittedEntryIndex() != -1 &&
4870 GetLastCommittedEntryIndex() >= backmost_index &&
4871 GetLastCommittedEntryIndex() <= forwardmost_index) {
4872 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4873 }
4874 if (previous_entry) {
4875 url::Origin previous_entry_origin =
4876 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4877 previous_entry->url(),
4878 previous_entry->initiator_origin().value_or(url::Origin())));
Alison Gale770f3fc2024-04-27 00:39:584879 // TODO(crbug.com/40181982): Move this into ToNavigationApiHistoryEntry()
Nate Chapinc06cf80a2023-11-18 01:12:254880 // once we can be sure that entries with the same ISN will never be
4881 // cross-origin.
4882 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4883 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4884 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094885 }
Nate Chapind1fe3612021-04-16 20:45:574886 }
Nate Chapinc06cf80a2023-11-18 01:12:254887
Nate Chapin4e657a472022-02-06 03:38:374888 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574889}
4890
Nate Chapinfbfe5af2021-06-10 17:22:084891NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574892NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084893 FrameNavigationEntry* current_entry,
4894 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574895 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084896 if (!target_entry || !target_entry->committed_origin())
4897 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084898 if (!current_entry->committed_origin()->IsSameOriginWith(
4899 *target_entry->committed_origin())) {
4900 return HistoryNavigationAction::kStopLooking;
4901 }
4902
4903 // NOTE: We don't actually care between kSameDocument and
4904 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574905 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084906 return HistoryNavigationAction::kDifferentDocument;
4907 return HistoryNavigationAction::kKeepLooking;
4908}
4909
Domenic Denicolacc094fb2022-03-16 23:40:574910void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204911 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374912 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144913 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574914 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204915 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084916 FrameNavigationEntry* current_entry =
4917 GetLastCommittedEntry()->GetFrameEntry(node);
4918 if (!current_entry)
4919 return;
4920
Alison Gale47d1537d2024-04-19 21:31:464921 // TODO(crbug.com/40878000): Make sure that the right task ID is passed
Yoav Weiss8c573952022-11-17 17:35:134922 // when `navigation.traverseTo()` is called.
4923
Nate Chapinfbfe5af2021-06-10 17:22:084924 // We want to find the nearest matching entry that is contiguously
4925 // same-instance and same-origin. Check back first, then forward.
4926 // TODO(japhet): Link spec here once it exists.
4927 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574928 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084929 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4930 if (result == HistoryNavigationAction::kStopLooking)
4931 break;
4932 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144933 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084934 return;
4935 }
4936 }
4937 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574938 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084939 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4940 if (result == HistoryNavigationAction::kStopLooking)
4941 break;
4942 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144943 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084944 return;
4945 }
4946 }
Nate Chapinbf682fa32022-09-26 22:41:204947
4948 // If we fall through to here, a matching NavigationEntry couldn't be found.
4949 // Notify the renderer that the navigation was cancelled.
4950 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4951 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084952}
4953
Domenic Denicolacc094fb2022-03-16 23:40:574954bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304955 network::mojom::ReferrerPolicy referrer_policy) {
4956 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4957 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4958}
4959
shivanigithubf405bf0d2021-11-05 17:58:334960bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4961 const FrameTreeNode* frame_tree_node) const {
Alison Gale81f4f2c72024-04-22 19:33:314962 // TODO(crbug.com/40176906): We may have to add portals in addition to
shivanigithubf405bf0d2021-11-05 17:58:334963 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544964 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:464965 // The preview mode appears as prerendered page in renderers, and
4966 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:034967 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:514968 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:334969 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544970}
4971
Julie Jeongeun Kim0e242242022-11-30 10:45:094972void NavigationControllerImpl::DidChangeReferrerPolicy(
4973 FrameTreeNode* node,
4974 network::mojom::ReferrerPolicy referrer_policy) {
4975 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4976 if (!entry)
4977 return;
4978
4979 // The FrameNavigationEntry may want to change whether to protect its url
4980 // in the navigation API when the referrer policy changes.
4981 entry->set_protect_url_in_navigation_api(
4982 ShouldProtectUrlInNavigationApi(referrer_policy));
4983}
4984
[email protected]8ff00d72012-10-23 19:12:214985} // namespace content