blob: 84abbc447cb642bc2f45c28a0cbdc3e5cffb4b30 [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"
Peter Kastingb53b81912021-04-28 19:23:3049#include "base/strings/string_piece.h"
[email protected]348fbaac2013-06-11 06:31:5150#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0051#include "base/strings/utf_string_conversions.h"
[email protected]a43858f2013-06-28 15:18:3752#include "base/time/time.h"
Carlos Caballero40b0efd2021-01-26 11:55:0053#include "base/trace_event/optional_trace_event.h"
ssid3e765612015-01-28 04:03:4254#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0855#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5956#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2857#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1858#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3959#include "content/browser/blob_storage/chrome_blob_storage_context.h"
William Liu055a3542023-04-02 17:21:1960#include "content/browser/browser_context_impl.h"
[email protected]825b1662012-03-12 19:07:3161#include "content/browser/browser_url_handler_impl.h"
[email protected]5f2aa722013-08-07 16:59:4162#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0463#include "content/browser/dom_storage/session_storage_namespace_impl.h"
Nate Chapinc06cf80a2023-11-18 01:12:2564#include "content/browser/preloading/prerender/prerender_host.h"
Sharon Yang242ef822023-05-15 21:07:3265#include "content/browser/process_lock.h"
Mingyu Lei68f34412023-08-21 07:31:3766#include "content/browser/renderer_host/back_forward_cache_impl.h"
danakjc492bf82020-09-09 20:02:4467#include "content/browser/renderer_host/debug_urls.h"
68#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0069#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3370#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4471#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5772#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4473#include "content/browser/renderer_host/navigation_request.h"
William Liu055a3542023-04-02 17:21:1974#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_cache.h"
75#include "content/browser/renderer_host/navigation_transitions/navigation_entry_screenshot_manager.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"
Nate Chapind1fe3612021-04-16 20:45:5784#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5185#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1186#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1987#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1188#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4689#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0090#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3891#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1692#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4793#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5894#include "content/public/browser/render_widget_host.h"
95#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1096#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3497#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1998#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3899#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:10100#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:47101#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:43102#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:59103#include "media/base/mime_util.h"
Lei Zhanga4770832023-07-19 18:02:36104#include "net/base/net_errors.h"
Arthur Sonzogni620cec62018-12-13 13:08:57105#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18106#include "services/metrics/public/cpp/ukm_builders.h"
107#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17108#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37109#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44110#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58111#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39112#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30113#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21114#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06115#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43116#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50117#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31118#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51119#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
Jiewei Qian87951f52023-10-17 01:33:46120#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature.mojom.h"
[email protected]cca6f392014-05-28 21:32:26121#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29122
[email protected]8ff00d72012-10-23 19:12:21123namespace content {
[email protected]e9ba4472008-09-14 15:42:43124namespace {
125
[email protected]e9ba4472008-09-14 15:42:43126// Invoked when entries have been pruned, or removed. For example, if the
127// current entries are [google, digg, yahoo], with the current entry google,
128// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47129void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50130 int index,
[email protected]c12bf1a12008-09-17 16:28:49131 int count) {
[email protected]8ff00d72012-10-23 19:12:21132 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50133 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49134 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14135 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43136}
137
[email protected]e9ba4472008-09-14 15:42:43138// Configure all the NavigationEntries in entries for restore. This resets
139// the transition type to reload and makes sure the content state isn't empty.
140void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57141 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48142 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47143 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43144 // Use a transition type of reload so that we don't incorrectly increase
145 // the typed count.
Lei Zhang96031532019-10-10 19:05:47146 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
147 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43148 }
149}
150
[email protected]bf70edce2012-06-20 22:32:22151// Determines whether or not we should be carrying over a user agent override
152// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57153bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22154 return last_entry && last_entry->GetIsOverridingUserAgent();
155}
156
Camille Lamy5193caa2018-10-12 11:59:42157// Determines whether to override user agent for a navigation.
158bool ShouldOverrideUserAgent(
159 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57160 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42161 switch (override_user_agent) {
162 case NavigationController::UA_OVERRIDE_INHERIT:
163 return ShouldKeepOverride(last_committed_entry);
164 case NavigationController::UA_OVERRIDE_TRUE:
165 return true;
166 case NavigationController::UA_OVERRIDE_FALSE:
167 return false;
Camille Lamy5193caa2018-10-12 11:59:42168 }
169 NOTREACHED();
170 return false;
171}
172
Rakina Zata Amni312822d72021-06-04 16:13:37173// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28174// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37175// link which results in a navigation to the last committed URL (but wasn't
176// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04177// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
178// |base_url_for_data_url|, |transition_type| correspond to the new navigation
179// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
180// navigation that committed.
181bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
182 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57183 const GURL& virtual_url,
184 const GURL& base_url_for_data_url,
185 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57186 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37187 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57188 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37189 // Navigations intended to do a replacement shouldn't be converted to do a
190 // reload.
191 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28192 return false;
clamy0a656e42018-02-06 18:18:28193 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45194 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55195 return false;
196
arthursonzogni7a8243682017-12-14 16:41:42197 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28198 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42199 return false;
200
ananta3bdd8ae2016-12-22 17:11:55201 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
202 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
203 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28204 bool transition_type_can_be_converted = false;
205 if (ui::PageTransitionCoreTypeIs(transition_type,
206 ui::PAGE_TRANSITION_RELOAD) &&
207 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
208 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55209 }
clamy0a656e42018-02-06 18:18:28210 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55211 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28212 transition_type_can_be_converted = true;
213 }
214 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
215 transition_type_can_be_converted = true;
216 if (!transition_type_can_be_converted)
217 return false;
218
219 // This check is required for cases like view-source:, etc. Here the URL of
220 // the navigation entry would contain the url of the page, while the virtual
221 // URL contains the full URL including the view-source prefix.
222 if (virtual_url != last_committed_entry->GetVirtualURL())
223 return false;
224
Fergal Daly766177d2020-07-07 07:54:04225 // Check that the URLs match.
226 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
227 // If there's no frame entry then by definition the URLs don't match.
228 if (!frame_entry)
229 return false;
230
231 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28232 return false;
233
234 // This check is required for Android WebView loadDataWithBaseURL. Apps
235 // can pass in anything in the base URL and we need to ensure that these
236 // match before classifying it as a reload.
237 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
238 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
239 return false;
ananta3bdd8ae2016-12-22 17:11:55240 }
241
clamy0a656e42018-02-06 18:18:28242 // Skip entries with SSL errors.
243 if (last_committed_entry->ssl_error())
244 return false;
245
246 // Don't convert to a reload when the last navigation was a POST or the new
247 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04248 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28249 return false;
250
251 return true;
ananta3bdd8ae2016-12-22 17:11:55252}
253
Arthur Sonzognic686e8f2024-01-11 08:36:37254std::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12255 const mojom::DidCommitProvisionalLoadParams& params,
256 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32257 // Error pages commit in an opaque origin, yet have the real URL that resulted
258 // in an error as the |params.url|. Since successful reload of an error page
259 // should commit in the correct origin, setting the opaque origin on the
260 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17261 if (request && request->DidEncounterError())
Arthur Sonzognic686e8f2024-01-11 08:36:37262 return std::nullopt;
Nasko Oskov03912102019-01-11 00:21:32263
Arthur Sonzognic686e8f2024-01-11 08:36:37264 return std::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32265}
266
Alex Moshchuk99242832023-05-22 17:21:44267bool IsValidURLForNavigation(FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:42268 const GURL& virtual_url,
269 const GURL& dest_url) {
270 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
Alex Moshchuk99242832023-05-22 17:21:44271 if (node->IsOutermostMainFrame() && !virtual_url.is_valid() &&
272 !virtual_url.is_empty()) {
Camille Lamy5193caa2018-10-12 11:59:42273 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
274 << virtual_url.possibly_invalid_spec();
275 return false;
276 }
277
278 // Don't attempt to navigate to non-empty invalid URLs.
279 if (!dest_url.is_valid() && !dest_url.is_empty()) {
280 LOG(WARNING) << "Refusing to load invalid URL: "
281 << dest_url.possibly_invalid_spec();
282 return false;
283 }
284
285 // The renderer will reject IPC messages with URLs longer than
286 // this limit, so don't attempt to navigate with a longer URL.
287 if (dest_url.spec().size() > url::kMaxURLChars) {
288 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
289 << " characters.";
290 return false;
291 }
292
Aaron Colwell33109c592020-04-21 21:31:19293 // Reject renderer debug URLs because they should have been handled before
294 // we get to this point. This check handles renderer debug URLs
295 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
296 // provides defense-in-depth if a renderer debug URL manages to get here via
297 // some other path. We want to reject the navigation here so it doesn't
298 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30299 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19300 LOG(WARNING) << "Refusing to load renderer debug URL: "
301 << dest_url.possibly_invalid_spec();
302 return false;
303 }
304
Alex Moshchuk99242832023-05-22 17:21:44305 // Guests only support navigations to known-safe schemes. This check already
306 // exists in the extensions layer, where it also dispatches proper events to
307 // the guest's embedder (see WebViewGuest::LoadURLWithParams). This check is
308 // for defense-in-depth to ensure that no other places in the codebase
309 // accidentally navigate guests to schemes such as WebUI, which is not
310 // supported. See https://crbug.com/1444221.
311 if (node->current_frame_host()->GetSiteInstance()->IsGuest()) {
312 auto* cpsp = content::ChildProcessSecurityPolicy::GetInstance();
313 if (!cpsp->IsWebSafeScheme(dest_url.scheme()) &&
314 !dest_url.SchemeIs(url::kAboutScheme)) {
315 LOG(WARNING) << "Refusing to load unsafe URL in a guest: "
316 << dest_url.possibly_invalid_spec();
317 return false;
318 }
319 }
320
Camille Lamy5193caa2018-10-12 11:59:42321 return true;
322}
323
Mikel Astizba9cf2fd2017-12-17 10:38:10324// See replaced_navigation_entry_data.h for details: this information is meant
325// to ensure |*output_entry| keeps track of its original URL (landing page in
326// case of server redirects) as it gets replaced (e.g. history.replaceState()),
327// without overwriting it later, for main frames.
328void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57329 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10330 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17331 if (output_entry->GetReplacedEntryData().has_value() ||
332 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10333 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17334 }
Mikel Astizba9cf2fd2017-12-17 10:38:10335
336 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57337 data.first_committed_url = replaced_entry->GetURL();
338 data.first_timestamp = replaced_entry->GetTimestamp();
339 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29340 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10341}
342
Minggang Wangb9f3fa92021-07-01 15:30:31343blink::mojom::NavigationType GetNavigationType(
344 const GURL& old_url,
345 const GURL& new_url,
346 ReloadType reload_type,
347 NavigationEntryImpl* entry,
348 const FrameNavigationEntry& frame_entry,
349 bool has_pending_cross_document_commit,
350 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49351 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13352 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49353 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23354 // Reload navigations
355 switch (reload_type) {
356 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31357 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23358 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31359 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23360 case ReloadType::NONE:
361 break; // Fall through to rest of function.
362 }
363
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08364 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31365 return entry->GetHasPostData()
366 ? blink::mojom::NavigationType::RESTORE_WITH_POST
367 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23368 }
369
danakjb952ef12021-01-14 19:58:49370 const bool can_be_same_document =
371 // A pending cross-document commit means this navigation will not occur in
372 // the current document, as that document would end up being replaced in
373 // the meantime.
374 !has_pending_cross_document_commit &&
375 // If the current document is an error page, we should always treat it as
376 // a different-document navigation so that we'll attempt to load the
377 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49378 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13379 // If the navigation is an embedder-initiated navigation of a fenced
380 // frame root (i.e. enters a fenced frame tree from outside),
381 // same-document navigations should be disabled because we don't want to
382 // allow information to be joined across multiple embedder-initiated
383 // fenced frame navigations (which may contain separate cross-site data).
384 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49385 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
386 // same-document navigations should be disabled because we want to force
387 // the creation of a new browsing context group.
388 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12389
clamyea99ea12018-05-28 13:54:23390 // History navigations.
391 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12392 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31393 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
394 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23395 }
396 DCHECK(!is_same_document_history_load);
397
398 // A same-document fragment-navigation happens when the only part of the url
399 // that is modified is after the '#' character.
400 //
401 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12402 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23403 //
404 // Note: this check is only valid for navigations that are not history
405 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
406 // history navigation from 'A#foo' to 'A#bar' is not a same-document
407 // navigation, but a different-document one. This is why history navigation
408 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47409 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
410 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12411
412 // The one case where we do the wrong thing here and incorrectly choose
413 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
414 // the renderer is a frameset. All frameset navigations should be
415 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
416 // navigation would do the right thing, as it would send it to the browser and
417 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
418 // into this method). But since we can't tell that case here for browser-
419 // initiated navigations, we have to get the renderer involved. In that case
420 // the navigation would be restarted due to the renderer spending a reply of
421 // mojom::CommitResult::RestartCrossDocument.
422
423 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31424 ? blink::mojom::NavigationType::SAME_DOCUMENT
425 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23426}
427
Camille Lamy5193caa2018-10-12 11:59:42428// Adjusts the original input URL if needed, to get the URL to actually load and
429// the virtual URL, which may differ.
430void RewriteUrlForNavigation(const GURL& original_url,
431 BrowserContext* browser_context,
432 GURL* url_to_load,
433 GURL* virtual_url,
434 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42435 // Allow the browser URL handler to rewrite the URL. This will, for example,
436 // remove "view-source:" from the beginning of the URL to get the URL that
437 // will actually be loaded. This real URL won't be shown to the user, just
438 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31439 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42440 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
441 url_to_load, browser_context, reverse_on_redirect);
442}
443
444#if DCHECK_IS_ON()
445// Helper sanity check function used in debug mode.
446void ValidateRequestMatchesEntry(NavigationRequest* request,
447 NavigationEntryImpl* entry) {
448 if (request->frame_tree_node()->IsMainFrame()) {
449 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
450 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31451 ui::PageTransitionFromInt(request->common_params().transition),
452 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42453 }
Nasko Oskovc36327d2019-01-03 23:23:04454 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42455 entry->should_clear_history_list());
456 DCHECK_EQ(request->common_params().has_user_gesture,
457 entry->has_user_gesture());
458 DCHECK_EQ(request->common_params().base_url_for_data_url,
459 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04460 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42461 entry->GetCanLoadLocalResources());
462 DCHECK_EQ(request->common_params().started_from_context_menu,
463 entry->has_started_from_context_menu());
464
465 FrameNavigationEntry* frame_entry =
466 entry->GetFrameEntry(request->frame_tree_node());
467 if (!frame_entry) {
468 NOTREACHED();
469 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 {
481 NOTREACHED();
482 }
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
Matt Falkenhagen548ed1562021-07-06 01:38:26821WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
822 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32823}
824
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57825BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55826 return browser_context_;
827}
828
[email protected]d202a7c2012-01-04 07:53:47829void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30830 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36831 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57832 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47833 // Note that it's possible for `entries_` to contain multiple entries at this
834 // point, as Restore() might be called on a NavigationController that is
835 // already used (e.g. due to WebView's restoreState() API), not only for fresh
836 // NavigationControllers. These entries are not cleared to preserve legacy
837 // behavior and also because `pending_entry_` might point to one of the
838 // pre-existing entries. An exception for this is when `entries_` contains
839 // only the initial NavigationEntry, which must be removed.
840
841 // Do not proceed if selected_navigation will be out of bounds for the updated
842 // entries_ list, since it will be assigned to last_committed_entry_index_ and
843 // used to index entries_.
844 // TODO(https://crbug.com/1287624): Consider also returning early if entries
845 // is empty, since there should be no work to do (rather than marking the
846 // existing entries as needing reload). Also consider returning early if the
847 // selected index is -1, which represents a no-committed-entry state.
848 if (selected_navigation < -1 ||
849 selected_navigation >=
850 base::checked_cast<int>(entries->size() + entries_.size())) {
851 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24852 }
Charlie Reis23c26da2022-01-29 00:57:47853
Rakina Zata Amni46087a12022-11-11 08:28:38854 // There will always be at least one entry (new NavigationControllers will
855 // have the initial NavigationEntry).
856 if (selected_navigation == -1)
857 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47858
Rakina Zata Amni46087a12022-11-11 08:28:38859 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
860 // If we are on the initial NavigationEntry, it must be the only entry in
861 // the list. Since it's impossible to do a history navigation to the
862 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
863 // `pending_entry` might be set for a new non-history navigation).
864 // Note that we should not clear `entries_` if `entries` is empty (when
865 // InitialNavigationEntry mode is enabled), since that would leave us
866 // without any NavigationEntry.
867 CHECK_EQ(1, GetEntryCount());
868 CHECK_EQ(-1, pending_entry_index_);
869 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47870 }
[email protected]ce3fa3c2009-04-20 19:55:57871
[email protected]ce3fa3c2009-04-20 19:55:57872 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44873 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03874 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47875 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43876 if (entry->GetURL().is_empty()) {
877 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01878 // persisting the initial NavigationEntry [which is no longer possible but
879 // some old persisted sessions might still contain it] or when the
880 // serializer failed to write the URL because it's too long). Trying to
881 // restore and navigate to an entry with an empty URL will result in
882 // crashes, so change the URL to about:blank. See also
883 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43884 entry->SetURL(GURL(url::kAboutBlankURL));
885 }
dcheng36b6aec92015-12-26 06:16:36886 entries_.push_back(
887 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47888 }
avif16f85a72015-11-13 18:25:03889
890 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
891 // cleared out safely.
892 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57893
894 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36895 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57896}
897
toyoshim6142d96f2016-12-19 09:07:25898void NavigationControllerImpl::Reload(ReloadType reload_type,
899 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03900 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
901 (int)reload_type);
902 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
903 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28904 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28905 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32906 int current_index = -1;
907
Carlos IL42b416592019-10-07 23:10:36908 if (entry_replaced_by_post_commit_error_) {
909 // If there is an entry that was replaced by a currently active post-commit
910 // error navigation, this can't be the initial navigation.
911 DCHECK(!IsInitialNavigation());
912 // If the current entry is a post commit error, we reload the entry it
913 // replaced instead. We leave the error entry in place until a commit
914 // replaces it, but the pending entry points to the original entry in the
915 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
916 // case that pending_entry_ != entries_[pending_entry_index_].
917 entry = entry_replaced_by_post_commit_error_.get();
918 current_index = GetCurrentEntryIndex();
919 } else if (IsInitialNavigation() && pending_entry_) {
920 // If we are reloading the initial navigation, just use the current
921 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32922 entry = pending_entry_;
923 // The pending entry might be in entries_ (e.g., after a Clone), so we
924 // should also update the current_index.
925 current_index = pending_entry_index_;
926 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00927 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32928 current_index = GetCurrentEntryIndex();
929 if (current_index != -1) {
creis3da03872015-02-20 21:12:32930 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32931 }
[email protected]979a4bc2013-04-24 01:27:15932 }
[email protected]241db352013-04-22 18:04:05933
[email protected]59167c22013-06-03 18:07:32934 // If we are no where, then we can't reload. TODO(darin): We should add a
935 // CanReload method.
936 if (!entry)
937 return;
938
Rakina Zata Amnif297a802022-01-18 03:53:43939 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
940 // We should never navigate to an existing initial NavigationEntry that is
941 // the initial NavigationEntry for the initial empty document that hasn't
942 // been overridden by the synchronous about:blank commit, to preserve
943 // legacy behavior where trying to reload when the main frame is on the
944 // initial empty document won't result in a navigation. See also
945 // https://crbug.com/1277414.
946 return;
947 }
948
Aran Gilman37d11632019-10-08 23:07:15949 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30950 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07951 // they really want to do this. If they do, the dialog will call us back
952 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57953 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02954
[email protected]106a0812010-03-18 00:15:12955 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57956 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47957 return;
initial.commit09911bf2008-07-26 23:55:29958 }
Lei Zhang96031532019-10-10 19:05:47959
Wang Huia25efabc2022-09-24 17:27:22960 // Set ReloadType for |entry|.
961 entry->set_reload_type(reload_type);
962
Lei Zhang96031532019-10-10 19:05:47963 if (!IsInitialNavigation())
964 DiscardNonCommittedEntries();
965
966 pending_entry_ = entry;
967 pending_entry_index_ = current_index;
968 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
969
Nate Chapin45f620582021-09-30 17:45:43970 // location.reload() goes through BeginNavigation, so all reloads triggered
971 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13972 NavigateToExistingPendingEntry(
973 reload_type,
974 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:37975 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:13976 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29977}
978
[email protected]d202a7c2012-01-04 07:53:47979void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48980 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12981}
982
[email protected]d202a7c2012-01-04 07:53:47983void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49984 // If the pending reload type has been cleared by another navigation
985 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48986 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49987 return;
[email protected]106a0812010-03-18 00:15:12988 }
Wang Hui96ab1012022-10-11 02:05:49989 Reload(pending_reload_, false);
990 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12991}
992
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57993bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09994 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11995}
996
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57997bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38998 // Check that we're on the initial NavigationEntry and that this is not a
999 // cloned tab.
1000 return IsInitialNavigation() && GetEntryCount() == 1 &&
1001 GetLastCommittedEntry()->IsInitialEntry() &&
1002 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:401003}
1004
Aran Gilman37d11632019-10-08 23:07:151005NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
1006 int nav_entry_id) const {
avi254eff02015-07-01 08:27:581007 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:031008 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:581009}
1010
Adithya Srinivasan9b0c99c2021-08-10 15:19:451011NavigationEntryImpl*
1012NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
1013 int nav_entry_id) const {
1014 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
1015 if (entry)
1016 return entry;
1017 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:521018 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:451019 : nullptr;
1020}
1021
W. James MacLeanc07dc41b2022-07-25 18:52:161022void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:571023 const url::Origin& origin) {
1024 for (int i = 0; i < GetEntryCount(); i++) {
1025 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:161026 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571027 }
1028 if (entry_replaced_by_post_commit_error_) {
1029 // It's possible we could come back to this entry if the error
1030 // page/interstitial goes away.
1031 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:161032 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:571033 }
W. James MacLean1c40862c2020-04-27 21:05:571034}
1035
avi25764702015-06-23 15:43:371036void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:571037 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:001038 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:371039 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:271040 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:201041}
1042
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571043NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:471044 if (pending_entry_)
1045 return pending_entry_;
1046 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:201047}
1048
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571049NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:321050 // The pending entry is safe to return for new (non-history), browser-
1051 // initiated navigations. Most renderer-initiated navigations should not
1052 // show the pending entry, to prevent URL spoof attacks.
1053 //
1054 // We make an exception for renderer-initiated navigations in new tabs, as
1055 // long as no other page has tried to access the initial empty document in
1056 // the new tab. If another page modifies this blank page, a URL spoof is
1057 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:321058 bool safe_to_show_pending =
1059 pending_entry_ &&
1060 // Require a new navigation.
avi0dca04d2015-01-26 20:21:091061 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:321062 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:461063 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:321064
1065 // Also allow showing the pending entry for history navigations in a new tab,
1066 // such as Ctrl+Back. In this case, no existing page is visible and no one
1067 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:151068 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
1069 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:321070 safe_to_show_pending = true;
1071
1072 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:191073 return pending_entry_;
1074 return GetLastCommittedEntry();
1075}
1076
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571077int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:201078 if (pending_entry_index_ != -1)
1079 return pending_entry_index_;
1080 return last_committed_entry_index_;
1081}
1082
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571083NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381084 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031085 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201086}
1087
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571088bool NavigationControllerImpl::CanViewSource() {
Takashi Toyoshima6c58bbd2023-05-19 09:41:351089 const std::string& mime_type = frame_tree_->root()
1090 ->current_frame_host()
1091 ->GetPage()
1092 .GetContentsMimeType();
Kinuko Yasuda74702f92017-07-31 03:27:531093 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1094 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271095 NavigationEntry* visible_entry = GetVisibleEntry();
1096 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391097 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161098}
1099
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571100int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271101 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451102 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271103 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551104 return last_committed_entry_index_;
1105}
1106
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571107int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451108 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291109 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551110 return static_cast<int>(entries_.size());
1111}
1112
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571113NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371114 if (index < 0 || index >= GetEntryCount())
1115 return nullptr;
1116
avif16f85a72015-11-13 18:25:031117 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251118}
1119
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571120NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471121 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201122}
1123
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571124int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461125 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031126}
1127
Arthur Sonzognic686e8f2024-01-11 08:36:371128std::optional<int> NavigationControllerImpl::GetIndexForGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031129 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
Kevin McNee3b3a56192023-03-17 14:40:591130 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1131 return index;
1132 }
Shivani Sharma298d12852019-01-22 20:04:031133 }
Arthur Sonzognic686e8f2024-01-11 08:36:371134 return std::nullopt;
Kevin McNee3b3a56192023-03-17 14:40:591135}
1136
1137bool NavigationControllerImpl::CanGoBack() {
1138 return GetIndexForGoBack().has_value();
1139}
1140
Arthur Sonzognic686e8f2024-01-11 08:36:371141std::optional<int> NavigationControllerImpl::GetIndexForGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591142 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1143 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui()) {
1144 return index;
1145 }
1146 }
Arthur Sonzognic686e8f2024-01-11 08:36:371147 return std::nullopt;
[email protected]765b35502008-08-21 00:51:201148}
1149
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571150bool NavigationControllerImpl::CanGoForward() {
Kevin McNee3b3a56192023-03-17 14:40:591151 return GetIndexForGoForward().has_value();
[email protected]765b35502008-08-21 00:51:201152}
1153
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571154bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031155 int index = GetIndexForOffset(offset);
1156 return index >= 0 && index < GetEntryCount();
1157}
1158
Xiaohan Wang7f8052e02022-01-14 18:44:281159#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151160bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151161 if (offset == 0)
1162 return true;
1163 int increment = offset > 0 ? 1 : -1;
1164 int non_skippable_entries = 0;
1165 for (int index = GetIndexForOffset(increment);
1166 index >= 0 && index < GetEntryCount(); index += increment) {
1167 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1168 non_skippable_entries++;
1169
1170 if (non_skippable_entries == std::abs(offset))
1171 return true;
1172 }
1173 return false;
1174}
1175#endif
1176
[email protected]d202a7c2012-01-04 07:53:471177void NavigationControllerImpl::GoBack() {
Arthur Sonzognic686e8f2024-01-11 08:36:371178 const std::optional<int> target_index = GetIndexForGoBack();
shivanisha55201872018-12-13 04:29:061179
Kevin McNeeedc481c2023-04-27 22:30:581180 CHECK(target_index.has_value());
Miyoung Shin1c565c912021-03-17 12:11:211181
Kevin McNee3b3a56192023-03-17 14:40:591182 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201183}
1184
[email protected]d202a7c2012-01-04 07:53:471185void NavigationControllerImpl::GoForward() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:161186 // Note that at least one entry (the last one) will be non-skippable since
1187 // entries are marked skippable only when they add another entry because of
1188 // redirect or pushState.
Arthur Sonzognic686e8f2024-01-11 08:36:371189 const std::optional<int> target_index = GetIndexForGoForward();
Kevin McNee3b3a56192023-03-17 14:40:591190
Kevin McNeeedc481c2023-04-27 22:30:581191 CHECK(target_index.has_value());
Kevin McNee3b3a56192023-03-17 14:40:591192
1193 GoToIndex(*target_index);
[email protected]765b35502008-08-21 00:51:201194}
1195
[email protected]d202a7c2012-01-04 07:53:471196void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131197 GoToIndex(index, /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:371198 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:131199 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161200}
1201
Nate Chapinbf682fa32022-09-26 22:41:201202void NavigationControllerImpl::GoToIndex(
1203 int index,
1204 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371205 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131206 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201207 const std::string* navigation_api_key) {
sunjian30574a62017-03-21 21:39:441208 TRACE_EVENT0("browser,navigation,benchmark",
1209 "NavigationControllerImpl::GoToIndex");
Peter Boströmf68fe042023-06-07 18:27:501210 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
1211 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_size",
1212 entries_.size());
1213 // Indices should have have been validated by the caller.
1214 CHECK_GE(index, 0);
1215 CHECK_LT(static_cast<size_t>(index), entries_.size());
[email protected]765b35502008-08-21 00:51:201216
Rakina Zata Amnif297a802022-01-18 03:53:431217 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1218 // We should never navigate to an existing initial NavigationEntry that is
1219 // the initial NavigationEntry for the initial empty document that hasn't
1220 // been overridden by the synchronous about:blank commit, to preserve
1221 // legacy behavior where trying to reload when the main frame is on the
1222 // initial empty document won't result in a navigation. See also
1223 // https://crbug.com/1277414.
1224 return;
1225 }
1226
[email protected]cbab76d2008-10-13 22:42:471227 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201228
arthursonzogni5c4c202d2017-04-25 23:41:271229 DCHECK_EQ(nullptr, pending_entry_);
1230 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431231
arthursonzogni5c4c202d2017-04-25 23:41:271232 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201233 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271234 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1235 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201236 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131237 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201238 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201239}
1240
[email protected]d202a7c2012-01-04 07:53:471241void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121242 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031243 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201244 return;
1245
[email protected]9ba14052012-06-22 23:50:031246 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201247}
1248
Nate Chapinbf682fa32022-09-26 22:41:201249void NavigationControllerImpl::GoToOffsetFromRenderer(
1250 int offset,
Yoav Weiss8c573952022-11-17 17:35:131251 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:371252 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:131253 soft_navigation_heuristics_task_id) {
Nate Chapinbb74c5a52023-07-21 23:13:351254 // Note: This is actually reached in unit tests.
1255 if (!CanGoToOffset(offset))
Nate Chapin45f620582021-09-30 17:45:431256 return;
1257
Nate Chapinbf682fa32022-09-26 22:41:201258 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131259 soft_navigation_heuristics_task_id,
1260 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431261}
1262
Xiaohan Wang7f8052e02022-01-14 18:44:281263#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151264void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1265 // Note: This is actually reached in unit tests.
1266 if (!CanGoToOffsetWithSkipping(offset))
1267 return;
1268
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421269 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151270 GoToIndex(GetIndexForOffset(offset));
1271 return;
1272 }
1273 int increment = offset > 0 ? 1 : -1;
1274 // Find the offset without counting skippable entries.
1275 int target_index = GetIndexForOffset(increment);
1276 int non_skippable_entries = 0;
1277 for (int index = target_index; index >= 0 && index < GetEntryCount();
1278 index += increment) {
1279 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1280 non_skippable_entries++;
1281
1282 if (non_skippable_entries == std::abs(offset)) {
1283 target_index = index;
1284 break;
1285 }
1286 }
1287
1288 GoToIndex(target_index);
1289}
1290#endif
1291
[email protected]41374f12013-07-24 02:49:281292bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151293 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281294 return false;
[email protected]6a13a6c2011-12-20 21:47:121295
[email protected]43032342011-03-21 14:10:311296 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281297 return true;
[email protected]cbab76d2008-10-13 22:42:471298}
1299
Michael Thiessen9b14d512019-09-23 21:19:471300void NavigationControllerImpl::PruneForwardEntries() {
1301 DiscardNonCommittedEntries();
1302 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471303 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471304 if (num_removed <= 0)
1305 return;
Nate Chapin9eb16be72022-09-23 22:54:311306 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471307 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1308 NotifyPrunedEntries(this, remove_start_index /* start index */,
1309 num_removed /* count */);
1310}
1311
Aran Gilman37d11632019-10-08 23:07:151312void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1313 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321314 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311315 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511316 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1317 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321318 }
1319}
1320
Harkiran Bolariaba823e42021-05-21 18:30:361321base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1322 const GURL& url,
1323 const Referrer& referrer,
1324 ui::PageTransition transition,
1325 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471326 LoadURLParams params(url);
1327 params.referrer = referrer;
1328 params.transition_type = transition;
1329 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361330 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471331}
1332
Harkiran Bolariaba823e42021-05-21 18:30:361333base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1334 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061335 if (params.is_renderer_initiated)
1336 DCHECK(params.initiator_origin.has_value());
1337
naskob8744d22014-08-28 17:07:431338 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151339 "NavigationControllerImpl::LoadURLWithParams", "url",
1340 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291341 bool is_explicit_navigation =
1342 GetContentClient()->browser()->IsExplicitNavigation(
1343 params.transition_type);
1344 if (HandleDebugURL(params.url, params.transition_type,
1345 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431346 // If Telemetry is running, allow the URL load to proceed as if it's
1347 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491348 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431349 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361350 return nullptr;
[email protected]47752982014-07-29 08:01:431351 }
[email protected]8bf1048012012-02-08 01:22:181352
[email protected]cf002332012-08-14 19:17:471353 // Checks based on params.load_type.
1354 switch (params.load_type) {
1355 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431356 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471357 break;
1358 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261359 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471360 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361361 return nullptr;
[email protected]cf002332012-08-14 19:17:471362 }
1363 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461364 }
[email protected]e47ae9472011-10-13 19:48:341365
[email protected]e47ae9472011-10-13 19:48:341366 // The user initiated a load, we don't need to reload anymore.
1367 needs_reload_ = false;
1368
Harkiran Bolariaba823e42021-05-21 18:30:361369 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441370}
1371
Charlie Reis4c53a962023-06-21 23:17:531372void NavigationControllerImpl::LoadOriginalRequestURL() {
1373 // If the original request URL is not valid, matches the current URL, or
1374 // involves POST data, then simply reload. The POST check avoids issues with
1375 // sending data to the wrong page.
1376 const GURL& last_committed_url = GetLastCommittedEntry()->GetURL();
1377 const GURL& original_request_url =
1378 GetLastCommittedEntry()->GetOriginalRequestURL();
1379 if (!original_request_url.is_valid() ||
1380 original_request_url == last_committed_url ||
1381 GetLastCommittedEntry()->GetHasPostData()) {
1382 Reload(ReloadType::NORMAL, true);
1383 return;
1384 }
1385
1386 // Otherwise, attempt to load the original request URL without any of the
1387 // other data from the current NavigationEntry, replacing the current entry.
1388 // Loading the original URL is useful in cases such as modifying the user
1389 // agent.
1390 std::unique_ptr<NavigationController::LoadURLParams> load_params =
1391 std::make_unique<NavigationController::LoadURLParams>(
1392 original_request_url);
1393 load_params->should_replace_current_entry = true;
1394 load_params->transition_type = ui::PAGE_TRANSITION_RELOAD;
1395 LoadURLWithParams(*load_params.get());
1396}
1397
Mohamed Abdelhalim833de902019-09-16 17:41:451398bool NavigationControllerImpl::PendingEntryMatchesRequest(
1399 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191400 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451401 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191402}
1403
[email protected]d202a7c2012-01-04 07:53:471404bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321405 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071406 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331407 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441408 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251409 bool was_on_initial_empty_document,
Shivani Sharmaeef521b2024-01-18 13:03:561410 bool previous_document_had_history_intervention_activation,
Camille Lamy10aafcd32018-12-05 15:48:131411 NavigationRequest* navigation_request) {
1412 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331413
1414 // Note: validation checks and renderer kills due to invalid commit messages
1415 // must happen before getting here, in
1416 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1417 // effects of the navigation have already occurred.
1418
[email protected]cd2e15742013-03-08 04:08:311419 is_initial_navigation_ = false;
1420
Wang Hui96ab1012022-10-11 02:05:491421 // Any pending request to repost a form submission is no longer valid, since a
1422 // different NavigationEntry is committing.
1423 pending_reload_ = ReloadType::NONE;
1424
[email protected]0e8db942008-09-24 21:21:481425 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431426 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451427 if (entry_replaced_by_post_commit_error_) {
1428 // Same document navigation events with a post-commit error should already
1429 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1430 // reaching here.
1431 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331432
Rakina Zata Amnie2d31312022-11-18 03:38:451433 // Any commit while a post-commit error page is showing should put the
1434 // original entry back, replacing the error page's entry. This includes
1435 // reloads, where the original entry was used as the pending entry and
1436 // should now be at the correct index at commit time.
1437 entries_[last_committed_entry_index_] =
1438 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481439 }
Rakina Zata Amnie2d31312022-11-18 03:38:451440 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1441 details->previous_entry_index = GetLastCommittedEntryIndex();
Shu Yang7a3ec532023-06-21 17:49:001442 // Must honor user agent overrides in the |navigation_request|, such as
1443 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1444 // result, besides comparing |pending_entry_|'s user agent against
1445 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1446 // agent against LastCommittedEntry's.
1447 if (navigation_request->is_overriding_user_agent() !=
Shu Yang127e41a2023-12-19 01:26:541448 GetLastCommittedEntry()->GetIsOverridingUserAgent() ||
1449 (PendingEntryMatchesRequest(navigation_request) &&
1450 pending_entry_->GetIsOverridingUserAgent() !=
1451 GetLastCommittedEntry()->GetIsOverridingUserAgent())) {
Shu Yang7a3ec532023-06-21 17:49:001452 overriding_user_agent_changed = true;
Rakina Zata Amnie2d31312022-11-18 03:38:451453 }
[email protected]ecd9d8702008-08-28 22:10:171454
Dave Tapuskaa2ab4f252021-07-08 21:31:281455 bool is_main_frame_navigation = !rfh->GetParent();
1456
Alexander Timind2f2e4f22019-04-02 20:04:531457 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1458 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281459 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141460 // BackForwardCacheMetrics to be associated with the new navigation's
1461 // NavigationEntry, by either creating a new object or reusing the previous
1462 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281463 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Takashi Toyoshima7c041d82023-09-26 16:09:211464 if (navigation_request->frame_tree_node()->frame_tree().is_primary()) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141465 back_forward_cache_metrics = BackForwardCacheMetrics::
1466 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281467 GetLastCommittedEntry(), is_main_frame_navigation,
1468 params.document_sequence_number);
1469 }
Yuzu Saijo29f96ca92022-12-08 04:54:121470
Alexander Timind2f2e4f22019-04-02 20:04:531471 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281472 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451473 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1474 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531475 }
1476 }
1477
Rakina Zata Amnifd8370b2022-11-14 13:32:251478 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1479 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091480 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251481 details->did_replace_entry =
1482 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091483
fdegans9caf66a2015-07-30 21:10:421484 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111485 // except for restored entries. This should be true even if the current commit
1486 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291487 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481488 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081489 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111490
1491 // Only make changes based on the pending entry if the NavigationRequest
1492 // matches it. Otherwise, the pending entry may be for a different request
1493 // (e.g., if a slow history navigation is pending while an auto-subframe
1494 // commit occurs).
1495 if (PendingEntryMatchesRequest(navigation_request)) {
1496 // It is no longer necessary to consider the pending entry as restored.
1497 if (pending_entry_->IsRestored()) {
1498 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1499 was_restored = true;
1500 }
[email protected]e9ba4472008-09-14 15:42:431501
Charlie Reisf8cde712022-10-20 16:25:091502 // If the SiteInstance has changed from the matching pending entry, this
1503 // must be treated as a new navigation with replacement. Set the replacement
1504 // bit here and ClassifyNavigation will identify this case and return
1505 // NEW_ENTRY.
1506 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1507 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1508 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251509 // TODO(nasko,creis,rakina): Move this to happen before committing the
1510 // navigation. This is a bit complicated because we don't currently
1511 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091512 details->did_replace_entry = true;
1513 }
Nasko Oskovaee2f862018-06-15 00:05:521514 }
[email protected]bcd904482012-02-01 01:54:221515
[email protected]e9ba4472008-09-14 15:42:431516 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101517 NavigationType navigation_type =
1518 ClassifyNavigation(rfh, params, navigation_request);
1519 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451520
Rakina Zata Amnie2d31312022-11-18 03:38:451521 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451522 // Ensure that this navigation does not add a navigation entry, since
1523 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1524 // beyond the last committed one. Therefore, `should_replace_current_entry`
1525 // should be set, which replaces the current entry, or this should be a
1526 // reload, which does not create a new entry.
Rakina Zata Amnifd8370b2022-11-14 13:32:251527 DCHECK(navigation_request->common_params().should_replace_current_entry ||
Dominic Farolinoe0f8d7c2023-08-16 15:38:331528 navigation_request->GetReloadType() != ReloadType::NONE);
shivanigithub189833f2022-04-27 18:08:451529 }
1530
Rakina Zata Amnie2d31312022-11-18 03:38:451531 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551532 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241533 // This is a subframe navigation on the initial empty document, which used
1534 // to not have a NavigationEntry to attach to. Now it can attach to the
1535 // initial NavigationEntry, and we must ensure that its NavigationEntry
1536 // will keep the "initial NavigationEntry" status and won't append a new
1537 // NavigationEntry (it should always do replacement instead).
1538 // See also https://crbug.com/1277414.
1539 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551540 // Subframe navigation on initial NavigationEntry must not append a new
1541 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1542 // means every subframe navigation that happens while we're on the initial
1543 // NavigationEntry will always reuse the existing NavigationEntry and
1544 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101545 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1546 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551547 // This is a navigation that modifies the initial NavigationEntry, either
1548 // for a replacement or a reload. The initial NavigationEntry should
1549 // retain its "initial NavigationEntry" status in this case.
1550 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241551 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251552 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1553 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241554 // This is a synchronous about:blank navigation on the main frame, which
1555 // used to not create a NavigationEntry when we have no NavigationEntry on
1556 // FrameTree creation. We now have the initial NavigationEntry and are on
1557 // the initial NavigationEntry. To preserve old behavior, we should still
1558 // keep the "initial" status for the new NavigationEntry that we will
1559 // create for this navigation, so that subframe navigations under the
1560 // synchronously committed about:blank document will never append new
1561 // NavigationEntry, and instead will just reuse the initial
1562 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1563 // See also https://crbug.com/1277414.
1564 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551565 }
1566 }
1567 DCHECK(!details->should_stay_as_initial_entry ||
1568 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201569
eugenebutee08663a2017-04-27 17:43:121570 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441571 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121572
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071573 details->is_prerender_activation =
1574 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241575 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1576 ->GetOutermostMainFrame()
1577 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071578
Peter Boströmd7592132019-01-30 04:50:311579 // Make sure we do not discard the pending entry for a different ongoing
1580 // navigation when a same document commit comes in unexpectedly from the
1581 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1582 // other navigation types. See https://crbug.com/900036.
1583 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061584 bool keep_pending_entry =
1585 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101586 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061587 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311588
Miyoung Shin3299cbf2022-11-22 01:41:101589 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061590 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491591 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051592 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561593 previous_document_had_history_intervention_activation,
1594 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431595 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061596 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491597 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1598 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001599 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431600 break;
[email protected]8ff00d72012-10-23 19:12:211601 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471602 RendererDidNavigateNewSubframe(
1603 rfh, params, details->is_same_document, details->did_replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561604 previous_document_had_history_intervention_activation,
1605 navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431606 break;
[email protected]8ff00d72012-10-23 19:12:211607 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391608 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251609 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001610 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081611 // We don't send a notification about auto-subframe PageState during
1612 // UpdateStateForFrame, since it looks like nothing has changed. Send
1613 // it here at commit time instead.
1614 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431615 return false;
creis59d5a47cb2016-08-24 23:57:191616 }
[email protected]e9ba4472008-09-14 15:42:431617 break;
Aran Gilman37d11632019-10-08 23:07:151618 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431619 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151620 break;
[email protected]765b35502008-08-21 00:51:201621 }
1622
[email protected]688aa65c62012-09-28 04:32:221623 // At this point, we know that the navigation has just completed, so
1624 // record the time.
1625 //
1626 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261627 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331628 base::Time timestamp =
1629 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1630 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131631 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221632
Peter Boströmd7592132019-01-30 04:50:311633 // If we aren't keeping the pending entry, there shouldn't be one at this
1634 // point. Clear it again in case any error cases above forgot to do so.
1635 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1636 // been cleared instead of protecting against it.
1637 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551638 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141639
[email protected]e9ba4472008-09-14 15:42:431640 // All committed entries should have nonempty content state so WebKit doesn't
1641 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471642 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321643 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221644 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441645 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141646
Alexander Timind2f2e4f22019-04-02 20:04:531647 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1648 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281649 if (back_forward_cache_metrics &&
1650 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531651 active_entry->set_back_forward_cache_metrics(
1652 std::move(back_forward_cache_metrics));
1653 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281654
1655 // `back_forward_cache_metrics()` may return null as we do not record
1656 // back-forward cache metrics for navigations in non-primary frame trees.
1657 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141658 // TODO(https://crbug.com/1338089): Remove this.
1659 // These are both only available from details at this point, so we capture
1660 // them here.
1661 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101662 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141663 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1664 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281665 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1666 navigation_request,
1667 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1668 }
naskoc7533512016-05-06 17:01:121669
Charles Reisc0507202017-09-21 00:40:021670 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1671 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1672 // A mismatch can occur if the renderer lies or due to a unique name collision
1673 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121674 FrameNavigationEntry* frame_entry =
1675 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021676 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1677 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031678 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081679 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1680 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031681 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201682
1683 // Remember the bindings the renderer process has at this point, so that
1684 // we do not grant this entry additional bindings if we come back to it.
1685 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301686 }
[email protected]132e281a2012-07-31 18:32:441687
[email protected]97d8f0d2013-10-29 16:49:211688 // Once it is committed, we no longer need to track several pieces of state on
1689 // the entry.
naskoc7533512016-05-06 17:01:121690 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131691
[email protected]49bd30e62011-03-22 20:12:591692 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221693 // TODO(creis): This check won't pass for subframes until we create entries
1694 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001695 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421696 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591697
[email protected]e9ba4472008-09-14 15:42:431698 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001699 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001700 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311701 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531702
arthursonzogni7ddc6542021-04-09 09:16:501703 active_entry->SetIsOverridingUserAgent(
1704 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031705
[email protected]93f230e02011-06-01 14:40:001706 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291707
aelias100c9192017-01-13 00:01:431708 if (overriding_user_agent_changed)
1709 delegate_->UpdateOverridingUserAgent();
1710
creis03b48002015-11-04 00:54:561711 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1712 // one knows the latest NavigationEntry it is showing (whether it has
1713 // committed anything in this navigation or not). This allows things like
1714 // state and title updates from RenderFrames to apply to the latest relevant
1715 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381716 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031717 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381718 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431719
1720 if (navigation_request->IsPrerenderedPageActivation()) {
1721 BroadcastHistoryOffsetAndLength();
1722 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1723 // is activated. As a result, a "prerenderingchange" event listener sees the
1724 // history.length which is not updated yet. We should guarantee that
1725 // history's length and offset should be updated before a
1726 // "prerenderingchange" event listener runs. One possible approach is to use
1727 // the same IPC which "prerenderingchange" uses, and propagate history's
1728 // length and offset together with that.
1729 }
1730
[email protected]e9ba4472008-09-14 15:42:431731 return true;
initial.commit09911bf2008-07-26 23:55:291732}
1733
[email protected]8ff00d72012-10-23 19:12:211734NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321735 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101736 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241737 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591738 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511739 "ClassifyNavigation");
1740
avi7c6f35e2015-05-08 17:52:381741 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241742 // A new entry. We may or may not have a corresponding pending entry, and
1743 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001744 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491745 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061746 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381747 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241748 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511749 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381750 return NAVIGATION_TYPE_NEW_SUBFRAME;
1751 }
1752
Charlie Reisc0f17d2d2021-01-12 18:52:491753 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381754 DCHECK(!params.history_list_was_cleared);
1755
avi39c1edd32015-06-04 20:06:001756 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381757 // All manual subframes would be did_create_new_entry and handled above, so
1758 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081759 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1760 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381761 }
1762
Rakina Zata Amnif6950d552020-11-24 03:26:101763 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1764 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381765 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1766 // create a new page.
1767
Hayato Ito2ae49442021-07-02 02:59:251768 // This main frame navigation is not a history navigation (since
1769 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1770 // reload or a replacement navigation, which will modify the existing entry.
1771 //
Nasko Oskov332593c2018-08-16 17:21:341772 // TODO(nasko): With error page isolation, reloading an existing session
1773 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491774 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341775 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511776 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491777 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061778 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381779 }
1780
Charlie Reisf8cde712022-10-20 16:25:091781 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521782 // If the SiteInstance of the |pending_entry_| does not match the
1783 // SiteInstance that got committed, treat this as a new navigation with
1784 // replacement. This can happen if back/forward/reload encounters a server
1785 // redirect to a different site or an isolated error page gets successfully
1786 // reloaded into a different SiteInstance.
1787 if (pending_entry_->site_instance() &&
1788 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491789 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061790 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521791 }
creis77c9aa32015-09-25 19:59:421792
Nasko Oskovaee2f862018-06-15 00:05:521793 if (pending_entry_index_ == -1) {
1794 // In this case, we have a pending entry for a load of a new URL but Blink
1795 // didn't do a new navigation (params.did_create_new_entry). First check
1796 // to make sure Blink didn't treat a new cross-process navigation as
1797 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161798 // we must treat it as NEW rather than the converted reload case below,
1799 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451800 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161801 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061802 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521803 }
1804
1805 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161806 // We will create a pending entry, but NavigateWithoutEntry will convert
1807 // it to a reload since it's the same page and not create a new entry for
1808 // it. (The user doesn't want to have a new back/forward entry when they
1809 // do this.) Therefore we want to just ignore the pending entry and go
1810 // back to where we were (the "existing entry").
1811 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061812 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521813 }
avi7c6f35e2015-05-08 17:52:381814 }
1815
Rakina Zata Amni153d5702021-09-13 22:48:001816 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381817 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491818 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1819 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161820 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061821 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381822 }
1823
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121824 if (navigation_request->DidEncounterError() &&
1825 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101826 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381827 // If the renderer was going to a new pending entry that got cleared because
1828 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491829 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381830 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511831 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491832 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061833 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381834 }
1835
Charlie Reisc0f17d2d2021-01-12 18:52:491836 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101837 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511838 trace_return.traced_value()->SetInteger("existing_entry_index",
1839 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381840 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441841 // The renderer has committed a navigation to an entry that no longer
1842 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491843 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061844 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381845 }
1846
avi7c6f35e2015-05-08 17:52:381847 // Since we weeded out "new" navigations above, we know this is an existing
1848 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491849 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061850 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381851}
1852
Rakina Zata Amni3460d382021-10-29 00:43:371853void NavigationControllerImpl::UpdateNavigationEntryDetails(
1854 NavigationEntryImpl* entry,
1855 RenderFrameHostImpl* rfh,
1856 const mojom::DidCommitProvisionalLoadParams& params,
1857 NavigationRequest* request,
1858 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001859 bool is_new_entry,
1860 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371861 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171862 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371863 entry->AddOrUpdateFrameEntry(
1864 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571865 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371866 rfh->GetSiteInstance(), nullptr, params.url,
1867 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171868 Referrer(*params.referrer),
1869 request ? request->common_params().initiator_origin : params.origin,
Arthur Sonzognic686e8f2024-01-11 08:36:371870 request ? request->common_params().initiator_base_url : std::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171871 request ? request->GetRedirectChain() : redirects, params.page_state,
1872 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
Rakina Zata Amni3460d382021-10-29 00:43:371873 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171874 rfh, request && request->IsSameDocument(),
1875 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371876
1877 if (rfh->GetParent()) {
1878 // Only modify the NavigationEntry for main frame navigations.
1879 return;
1880 }
1881 if (entry->update_virtual_url_with_url())
1882 UpdateVirtualURLToURL(entry, params.url);
1883 // Don't use the page type from the pending entry. Some interstitial page
1884 // may have set the type to interstitial. Once we commit, however, the page
1885 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171886 entry->set_page_type((request && request->DidEncounterError())
1887 ? PAGE_TYPE_ERROR
1888 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431889 if (commit_details && commit_details->should_stay_as_initial_entry) {
1890 // Retain the "initial NavigationEntry" status.
1891 if (request->IsSameDocument()) {
1892 // If this is for a same-document navigation, the NavigationEntry must be
1893 // reused and should already be marked as the initial NavigationEntry.
1894 DCHECK(entry->IsInitialEntry());
1895 } else {
1896 // If this is for a cross-document navigation, it can be caused by a
1897 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1898 // "for synchronous about:blank" in the latter case, and also when it is
1899 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1900 // is not for a synchronous about:blank commit.
1901 NavigationEntryImpl::InitialNavigationEntryState new_state =
1902 NavigationEntryImpl::InitialNavigationEntryState::
1903 kInitialNotForSynchronousAboutBlank;
1904 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1905 request->is_synchronous_renderer_commit()) {
1906 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1907 kInitialForSynchronousAboutBlank;
1908 }
1909 entry->set_initial_navigation_entry_state(new_state);
1910 }
1911 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1912 // Remove the "initial NavigationEntry" status.
1913 entry->set_initial_navigation_entry_state(
1914 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001915 }
Rakina Zata Amniddf10502022-01-15 02:56:551916
Rakina Zata Amni3460d382021-10-29 00:43:371917 if (is_new_entry) {
1918 // Some properties of the NavigationEntry are only set when the entry is
1919 // new (we aren't reusing it).
1920 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171921 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
Peter Kasting8104ba82024-01-31 15:23:401922 : GURL());
Adithya Srinivasan72b07352023-12-21 15:56:011923 DCHECK_EQ(rfh->GetPage().is_overriding_user_agent(),
1924 params.is_overriding_user_agent);
Rakina Zata Amni3460d382021-10-29 00:43:371925 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1926 } else {
1927 // We are reusing the NavigationEntry. The site instance will normally be
1928 // the same except for a few cases:
1929 // 1) session restore, when no site instance will be assigned or
1930 // 2) redirect, when the site instance is reset.
1931 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1932 entry->site_instance() == rfh->GetSiteInstance());
1933 }
1934}
1935
Rakina Zata Amniafd3c6582021-11-30 06:19:171936void NavigationControllerImpl::CreateInitialEntry() {
1937 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031938 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171939 auto params = mojom::DidCommitProvisionalLoadParams::New();
1940 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1941 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1942 // before we have initial NavigationEntries.
Peter Kasting8104ba82024-01-31 15:23:401943 params->url = GURL();
Rakina Zata Amniafd3c6582021-11-30 06:19:171944 params->http_status_code = 0;
1945 params->url_is_unreachable = false;
1946 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171947 params->post_id = -1;
1948 params->embedding_token = base::UnguessableToken::Create();
1949 params->navigation_token = base::UnguessableToken::Create();
1950 params->did_create_new_entry = true;
1951 params->origin = rfh->GetLastCommittedOrigin();
1952 params->should_update_history = true;
1953 params->item_sequence_number = 0;
1954 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151955 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171956 params->transition = is_in_fenced_frame_tree
1957 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1958 : ui::PAGE_TRANSITION_LINK;
1959 params->referrer = blink::mojom::Referrer::New();
1960
Rakina Zata Amniafd3c6582021-11-30 06:19:171961 auto new_entry = std::make_unique<NavigationEntryImpl>(
1962 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381963 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211964 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1965 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1966 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171967 UpdateNavigationEntryDetails(
1968 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001969 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1970 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171971
1972 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1973 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001974 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171975}
1976
Charlie Reisc0f17d2d2021-01-12 18:52:491977void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321978 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071979 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361980 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441981 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:561982 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:001983 NavigationRequest* request,
1984 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571985 std::unique_ptr<NavigationEntryImpl> new_entry;
Arthur Sonzognic686e8f2024-01-11 08:36:371986 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451987 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:371988 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:521989 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
1990 initiator_base_url = request->common_params().initiator_base_url;
1991 }
Lukasz Anforowicz435bcb582019-07-12 20:50:061992
creisf49dfc92016-07-26 17:05:181993 // First check if this is an in-page navigation. If so, clone the current
1994 // entry instead of looking at the pending entry, because the pending entry
1995 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451996 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301997 FrameNavigationEntry* previous_frame_entry =
1998 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451999 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482000 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572001 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082002 rfh->GetSiteInstance(), nullptr, params.url,
2003 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212004 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:092005 request->GetRedirectChain(), params.page_state, params.method,
2006 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:392007 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:302008 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572009 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302010 // FrameNavigationEntry.
2011 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572012 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:032013
creisf49dfc92016-07-26 17:05:182014 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:032015 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:522016 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
2017 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:572018 // TODO(jam): we had one report of this with a URL that was redirecting to
2019 // only tildes. Until we understand that better, don't copy the cert in
2020 // this case.
2021 new_entry->GetSSL() = SSLStatus();
2022 }
creisf49dfc92016-07-26 17:05:182023
Patrick Monette50e8bd82019-06-13 22:40:452024 // It is expected that |frame_entry| is now owned by |new_entry|. This means
2025 // that |frame_entry| should now have a reference count of exactly 2: one
2026 // due to the local variable |frame_entry|, and another due to |new_entry|
2027 // also retaining one. This should never fail, because it's the main frame.
2028 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:182029 }
2030
Harkiran Bolaria59290d62021-03-17 01:53:012031 // If this is an activation navigation from a prerendered page, transfer the
2032 // new entry from an entry already created and stored in the
2033 // NavigationRequest. |new_entry| will not have been set prior to this as
2034 // |is_same_document| is mutually exclusive with
2035 // |IsPrerenderedPageActivation|.
2036 if (request->IsPrerenderedPageActivation()) {
2037 DCHECK(!is_same_document);
2038 DCHECK(!new_entry);
2039 new_entry = request->TakePrerenderNavigationEntry();
2040 DCHECK(new_entry);
2041 }
2042
Charlie Reisc0f17d2d2021-01-12 18:52:492043 // Only make a copy of the pending entry if it is appropriate for the new
2044 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:452045 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:042046 // 1. The SiteInstance hasn't been assigned to something else.
2047 // 2. The pending entry was intended as a new entry, rather than being a
2048 // history navigation that was interrupted by an unrelated,
2049 // renderer-initiated navigation.
2050 // TODO(csharrison): Investigate whether we can remove some of the coarser
2051 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:452052 if (!new_entry && PendingEntryMatchesRequest(request) &&
2053 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:342054 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:432055 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:352056 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:432057
Camille Lamy62b826012019-02-26 09:15:472058 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452059 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:182060 }
2061
Charlie Reisc0f17d2d2021-01-12 18:52:492062 // For cross-document commits with no matching pending entry, create a new
2063 // entry.
creisf49dfc92016-07-26 17:05:182064 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:062065 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:072066 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:212067 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:582068 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:452069 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:172070 nullptr, // blob_url_loader_factory
2071 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:242072
2073 // Find out whether the new entry needs to update its virtual URL on URL
2074 // change and set up the entry accordingly. This is needed to correctly
2075 // update the virtual URL when replaceState is called after a pushState.
2076 GURL url = params.url;
2077 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:492078 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:412079 // update the virtual URL based on the new URL. For example, this is needed
2080 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
2081 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:372082 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
2083 &url, browser_context_, &needs_update);
2084 new_entry->set_update_virtual_url_with_url(needs_update);
2085
Camille Lamy62b826012019-02-26 09:15:472086 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452087 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432088 }
2089
Harkiran Bolaria59290d62021-03-17 01:53:012090 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2091 // for prerendered contents, if any. This is because prerendering/activation
2092 // technically won't be creating a new document. Unlike BFCache, prerendering
2093 // creates a new NavigationEntry rather than using an existing one.
2094 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372095 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2096 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002097 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082098
Harkiran Bolaria59290d62021-03-17 01:53:012099 // history.pushState() is classified as a navigation to a new page, but sets
2100 // is_same_document to true. In this case, we already have the title and
2101 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452102 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012103 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2104 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2105 }
[email protected]3a868f212014-08-09 10:41:192106 }
[email protected]ff64b3e2014-05-31 04:07:332107
[email protected]60d6cca2013-04-30 08:47:132108 DCHECK(!params.history_list_was_cleared || !replace_entry);
2109 // The browser requested to clear the session history when it initiated the
2110 // navigation. Now we know that the renderer has updated its state accordingly
2111 // and it is safe to also clear the browser side history.
2112 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552113 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132114 entries_.clear();
2115 last_committed_entry_index_ = -1;
2116 }
2117
Nasko Oskovaee2f862018-06-15 00:05:522118 // If this is a new navigation with replacement and there is a
2119 // pending_entry_ which matches the navigation reported by the renderer
2120 // process, then it should be the one replaced, so update the
2121 // last_committed_entry_index_ to use it.
2122 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092123 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522124 last_committed_entry_index_ = pending_entry_index_;
2125 }
2126
Alexander Timine3ec4192020-04-20 16:39:402127 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562128 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402129 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052130
Yuzu Saijoa725585f2022-11-28 04:14:032131 // If this is a history navigation and the old entry has an existing
2132 // back/forward cache metrics object, keep using the old one so that the
2133 // reasons logged from the last time the page navigated gets preserved.
2134 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2135 request)) {
2136 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2137 // because some tests do not have a pending entry.
2138 NavigationEntryImpl* entry =
2139 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2140 if (entry && entry->back_forward_cache_metrics()) {
2141 scoped_refptr<BackForwardCacheMetrics> metrics =
2142 entry->TakeBackForwardCacheMetrics();
2143 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2144 }
2145 }
2146
Carlos IL42b416592019-10-07 23:10:362147 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312148 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152149 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432150}
2151
Charlie Reisc0f17d2d2021-01-12 18:52:492152void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322153 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072154 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362155 bool is_same_document,
jam48cea9082017-02-15 06:13:292156 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452157 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002158 bool keep_pending_entry,
2159 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562160 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2161 << "that a last committed entry exists.";
2162
[email protected]e9ba4472008-09-14 15:42:432163 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002164 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432165
Charlie Reis7e2cb6d2021-01-26 01:27:162166 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002167 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162168 // We're guaranteed to have a last committed entry if intended_as_new_entry
2169 // is true.
avicbdc4c12015-07-01 16:07:112170 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162171
2172 // If the NavigationRequest matches a new pending entry and is classified as
2173 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2174 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092175 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162176 // Note: The pending entry will usually have a real ReloadType here, but
2177 // it can still be ReloadType::NONE in cases that
2178 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2179
2180 // If we classified this correctly, the SiteInstance should not have
2181 // changed.
2182 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2183
2184 // For converted reloads, we assign the entry's unique ID to be that of
2185 // the new one. Since this is always the result of a user action, we want
2186 // to dismiss infobars, etc. like a regular user-initiated navigation.
2187 entry->set_unique_id(pending_entry_->GetUniqueID());
2188
2189 // The extra headers may have changed due to reloading with different
2190 // headers.
2191 entry->set_extra_headers(pending_entry_->extra_headers());
2192 }
2193 // Otherwise, this was intended as a new entry but the pending entry was
2194 // lost in the meantime and no new entry was created. We are stuck at the
2195 // last committed entry.
2196
2197 // Even if this is a converted reload from pressing enter in the omnibox,
2198 // the server could redirect, requiring an update to the SSL status. If this
2199 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452200 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162201 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472202 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452203 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162204 }
Rakina Zata Amnif6950d552020-11-24 03:26:102205 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112206 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102207 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162208
eugenebut604866f2017-05-10 21:35:362209 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452210 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362211 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2212 // this was a restored same document navigation entry, then it won't have
2213 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2214 // navigated it.
jam48cea9082017-02-15 06:13:292215 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522216 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2217 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292218 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2219 was_restored) {
2220 entry->GetSSL() = last_entry->GetSSL();
2221 }
2222 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452223 // In rapid back/forward navigations |request| sometimes won't have a cert
2224 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192225 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452226 if (request->GetSSLInfo().has_value() &&
2227 request->GetSSLInfo()->is_valid()) {
2228 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522229 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2230 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192231 entry->GetSSL() = SSLStatus();
2232 }
jam48cea9082017-02-15 06:13:292233 }
avicbdc4c12015-07-01 16:07:112234 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272235 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572236 // navigations that are EXISTING_ENTRY are same-document navigations that
2237 // result in replacement (e.g. history.replaceState(), location.replace(),
2238 // forced replacements for trivial session history contexts). For these
2239 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112240 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102241
Mikel Astizba9cf2fd2017-12-17 10:38:102242 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2243 // to avoid misleading interpretations (e.g. URLs paired with
2244 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2245 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2246 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2247
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572248 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102249
eugenebut604866f2017-05-10 21:35:362250 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452251 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362252 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472253 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452254 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112255 }
2256 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432257
Rakina Zata Amni3460d382021-10-29 00:43:372258 UpdateNavigationEntryDetails(entry, rfh, params, request,
2259 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002260 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302261
[email protected]5ccd4dc2012-10-24 02:28:142262 // The redirected to page should not inherit the favicon from the previous
2263 // page.
eugenebut604866f2017-05-10 21:35:362264 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482265 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142266
Charlie Reis951f43372023-05-05 00:30:072267 // Update the last committed index to reflect the committed entry. Do this
2268 // before calling DiscardNonCommittedEntriesWithCommitDetails, so that the
2269 // delegate sees the correct committed index when notified of navigation
2270 // state changes. (Otherwise CanGoBack may incorrectly return true, as in
2271 // https://crbug.com/1439948.)
Charlie Reisfbe5f1022023-10-03 15:21:212272 last_committed_entry_index_ = GetIndexOfEntry(entry);
Charlie Reis951f43372023-05-05 00:30:072273
Peter Boströmd7592132019-01-30 04:50:312274 // We should also usually discard the pending entry if it corresponds to a
2275 // different navigation, since that one is now likely canceled. In rare
2276 // cases, we leave the pending entry for another navigation in place when we
2277 // know it is still ongoing, to avoid a flicker in the omnibox (see
2278 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432279 //
2280 // Note that we need to use the "internal" version since we don't want to
2281 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312282 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002283 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]e9ba4472008-09-14 15:42:432284}
2285
[email protected]d202a7c2012-01-04 07:53:472286void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322287 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072288 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362289 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472290 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:562291 bool previous_document_had_history_intervention_activation,
Rakina Zata Amnia4e27222021-12-22 01:05:002292 NavigationRequest* request,
2293 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262294 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2295 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552296 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2297 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112298
[email protected]e9ba4472008-09-14 15:42:432299 // Manual subframe navigations just get the current entry cloned so the user
2300 // can go back or forward to it. The actual subframe information will be
2301 // stored in the page state for each of those entries. This happens out of
2302 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092303 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2304 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382305
Mikel Astizba9cf2fd2017-12-17 10:38:102306 // The DCHECK below documents the fact that we don't know of any situation
2307 // where |replace_entry| is true for subframe navigations. This simplifies
2308 // reasoning about the replacement struct for subframes (see
2309 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2310 DCHECK(!replace_entry);
2311
Patrick Monette50e8bd82019-06-13 22:40:452312 // This FrameNavigationEntry might not end up being used in the
2313 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Arthur Sonzognic686e8f2024-01-11 08:36:372314 const std::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452315 request->common_params().initiator_origin;
Arthur Sonzognic686e8f2024-01-11 08:36:372316 std::optional<GURL> initiator_base_url;
W. James MacLean8be423a2023-03-31 21:35:522317 if (params.url.IsAboutBlank() || params.url.IsAboutSrcdoc()) {
2318 initiator_base_url = request->common_params().initiator_base_url;
2319 }
Nate Chapin63db0d12022-01-20 22:03:302320 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2321 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2322 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572323 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302324 if (is_same_document) {
2325 FrameNavigationEntry* previous_frame_entry =
2326 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572327 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302328 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572329 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302330 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572331 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302332 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572333 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302334 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572335 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302336 policy_container_policies->referrer_policy);
2337 }
2338
Patrick Monette50e8bd82019-06-13 22:40:452339 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482340 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572341 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082342 rfh->GetSiteInstance(), nullptr, params.url,
2343 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212344 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2345 request->GetRedirectChain(), params.page_state, params.method,
2346 params.post_id, nullptr /* blob_url_loader_factory */,
Domenic Denicolacc094fb2022-03-16 23:40:572347 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032348
creisce0ef3572017-01-26 17:53:082349 std::unique_ptr<NavigationEntryImpl> new_entry =
2350 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452351 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032352 frame_tree_->root());
creise062d542015-08-25 02:01:552353
Alexander Timine3ec4192020-04-20 16:39:402354 SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaeef521b2024-01-18 13:03:562355 replace_entry, previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:402356 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472357
creisce0ef3572017-01-26 17:53:082358 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452359 // to replace, which can happen due to a unique name change. See
2360 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2361 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382362
Dave Tapuska87696ae2021-11-18 18:48:312363 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152364 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432365}
2366
[email protected]d202a7c2012-01-04 07:53:472367bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322368 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072369 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392370 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252371 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002372 NavigationRequest* request,
2373 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292374 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2375 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2376
[email protected]e9ba4472008-09-14 15:42:432377 // We're guaranteed to have a previously committed entry, and we now need to
2378 // handle navigation inside of a subframe in it without creating a new entry.
2379 DCHECK(GetLastCommittedEntry());
2380
creis913c63ce2016-07-16 19:52:522381 // For newly created subframes, we don't need to send a commit notification.
2382 // This is only necessary for history navigations in subframes.
2383 bool send_commit_notification = false;
2384
Rakina Zata Amnif6950d552020-11-24 03:26:102385 // If |nav_entry_id| is non-zero and matches an existing entry, this
2386 // is a history navigation. Update the last committed index accordingly. If
2387 // we don't recognize the |nav_entry_id|, it might be a recently
2388 // pruned entry. We'll handle it below.
2389 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2390 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472391 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062392 // Make sure that a subframe commit isn't changing the main frame's
2393 // origin. Otherwise the renderer process may be confused, leading to a
2394 // URL spoof. We can't check the path since that may change
2395 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572396 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2397 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242398 // We should use checks similar to RenderFrameHostImpl's
2399 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2400 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572401 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2402 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2403 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2404 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522405 current_top_url.DeprecatedGetOriginAsURL() !=
2406 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442407 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512408 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062409 }
creis3cdc3b02015-05-29 23:00:472410
creis913c63ce2016-07-16 19:52:522411 // We only need to discard the pending entry in this history navigation
2412 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062413 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002414 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522415
2416 // History navigations should send a commit notification.
2417 send_commit_notification = true;
avi98405c22015-05-21 20:47:062418 }
[email protected]e9ba4472008-09-14 15:42:432419 }
[email protected]f233e4232013-02-23 00:55:142420
creisce0ef3572017-01-26 17:53:082421 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2422 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372423 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2424 // exists), or we may want to clobber it and create a new one. We update in
2425 // cases where the corresponding FrameNavigationEntry is conceptually similar
2426 // to the document described by the commit params: same-document
2427 // navigations, history traversal to an existing entry, and reloads (including
2428 // a "soft reload" where we navigate to the same url without flagging it as a
2429 // reload). But in the case of a different document that is not logically
2430 // related to the committed FrameNavigationEntry's document (cross-document,
2431 // not same url, not a reload, not a history traversal), we replace rather
2432 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252433 //
Nate Chapin9f169072021-06-09 19:32:372434 // In the case where we update, the FrameNavigationEntry will potentially be
2435 // shared across multiple NavigationEntries, and any updates will be reflected
2436 // in all of those NavigationEntries. In the replace case, any existing
2437 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252438 //
2439 // When navigating away from the initial empty document, we also update rather
2440 // than replace. Either update or replace will overwrite the initial empty
2441 // document state for |last_committed|, but if the FrameNavigationEntry for
2442 // the initial empty document is shared across multiple NavigationEntries (due
2443 // to a navigation in another frame), we want to make sure we overwrite the
2444 // initial empty document state everywhere this FrameNavigationEntry is used,
2445 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452446 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372447 FrameNavigationEntry* last_committed_frame_entry =
2448 last_committed->GetFrameEntry(rfh->frame_tree_node());
2449 NavigationEntryImpl::UpdatePolicy update_policy =
2450 NavigationEntryImpl::UpdatePolicy::kUpdate;
2451 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312452 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372453 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252454 last_committed_frame_entry->url() != params.url &&
2455 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372456 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2457 }
2458
Rakina Zata Amni3460d382021-10-29 00:43:372459 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002460 update_policy, false /* is_new_entry */,
2461 commit_details);
creis625a0c7d2015-03-24 23:17:122462
creis913c63ce2016-07-16 19:52:522463 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432464}
2465
[email protected]d202a7c2012-01-04 07:53:472466int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232467 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032468 for (size_t i = 0; i < entries_.size(); ++i) {
2469 if (entries_[i].get() == entry)
2470 return i;
2471 }
2472 return -1;
[email protected]765b35502008-08-21 00:51:202473}
2474
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572475void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242476 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572477 NavigationControllerImpl* source =
2478 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572479 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382480 DCHECK_EQ(1, GetEntryCount());
2481 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472482 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172483 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572484
Francois Dorayeaace782017-06-21 16:37:242485 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442486 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572487 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572488
Fergal Dalya1d569972021-03-16 03:24:532489 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302490 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532491 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2492 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302493 }
[email protected]4e6419c2010-01-15 04:50:342494
Lukasz Anforowicz0de0f452020-12-02 19:57:152495 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572496}
2497
Aran Gilman37d11632019-10-08 23:07:152498void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2499 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162500 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012501 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162502
[email protected]d202a7c2012-01-04 07:53:472503 NavigationControllerImpl* source =
2504 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252505
avi2b177592014-12-10 02:08:022506 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012507 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252508
[email protected]474f8512013-05-31 22:31:162509 // We now have one entry, possibly with a new pending entry. Ensure that
2510 // adding the entries from source won't put us over the limit.
2511 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572512 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572513 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252514
Carlos IL4dea8902020-05-26 15:14:292515 // Insert the entries from source. Ignore any pending entry, since it has not
2516 // committed in source.
[email protected]474f8512013-05-31 22:31:162517 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172518 DCHECK_NE(max_source_index, -1);
2519 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572520
2521 // Ignore the source's current entry if merging with replacement.
2522 // TODO(davidben): This should preserve entries forward of the current
2523 // too. http://crbug.com/317872
2524 if (replace_entry && max_source_index > 0)
2525 max_source_index--;
2526
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572527 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252528
2529 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552530 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142531
Hayato Ito2c8c08d02021-06-23 03:38:432532 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252533}
2534
[email protected]79368982013-11-13 01:11:012535bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162536 // If there is no last committed entry, we cannot prune. Even if there is a
2537 // pending entry, it may not commit, leaving this WebContents blank, despite
2538 // possibly giving it new entries via CopyStateFromAndPrune.
2539 if (last_committed_entry_index_ == -1)
2540 return false;
[email protected]9350602e2013-02-26 23:27:442541
[email protected]474f8512013-05-31 22:31:162542 // We cannot prune if there is a pending entry at an existing entry index.
2543 // It may not commit, so we have to keep the last committed entry, and thus
2544 // there is no sensible place to keep the pending entry. It is ok to have
2545 // a new pending entry, which can optionally commit as a new navigation.
2546 if (pending_entry_index_ != -1)
2547 return false;
2548
[email protected]474f8512013-05-31 22:31:162549 return true;
2550}
2551
[email protected]79368982013-11-13 01:11:012552void NavigationControllerImpl::PruneAllButLastCommitted() {
2553 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162554
avi2b177592014-12-10 02:08:022555 DCHECK_EQ(0, last_committed_entry_index_);
2556 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442557
Hayato Ito2c8c08d02021-06-23 03:38:432558 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442559}
2560
[email protected]79368982013-11-13 01:11:012561void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162562 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012563 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262564
Nate Chapin9eb16be72022-09-23 22:54:312565 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2566
[email protected]474f8512013-05-31 22:31:162567 // Erase all entries but the last committed entry. There may still be a
2568 // new pending entry after this.
2569 entries_.erase(entries_.begin(),
2570 entries_.begin() + last_committed_entry_index_);
2571 entries_.erase(entries_.begin() + 1, entries_.end());
2572 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262573}
2574
Christian Dullweber1af31e62018-02-22 11:49:482575void NavigationControllerImpl::DeleteNavigationEntries(
2576 const DeletionPredicate& deletionPredicate) {
2577 // It is up to callers to check the invariants before calling this.
2578 CHECK(CanPruneAllButLastCommitted());
2579 std::vector<int> delete_indices;
2580 for (size_t i = 0; i < entries_.size(); i++) {
2581 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572582 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482583 delete_indices.push_back(i);
2584 }
2585 }
2586 if (delete_indices.empty())
2587 return;
2588
2589 if (delete_indices.size() == GetEntryCount() - 1U) {
2590 PruneAllButLastCommitted();
2591 } else {
2592 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382593 for (const auto& index : base::Reversed(delete_indices)) {
2594 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482595 }
Hayato Ito2c8c08d02021-06-23 03:38:432596 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482597 }
2598 delegate()->NotifyNavigationEntriesDeleted();
2599}
2600
Carlos Caballero35ce710c2019-09-19 10:59:452601BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2602 return back_forward_cache_;
2603}
2604
William Liu055a3542023-04-02 17:21:192605NavigationEntryScreenshotCache*
2606NavigationControllerImpl::GetNavigationEntryScreenshotCache() {
Takashi Toyoshima7c041d82023-09-26 16:09:212607 CHECK(frame_tree_->is_primary());
William Liu055a3542023-04-02 17:21:192608 if (!nav_entry_screenshot_cache_ && AreBackForwardTransitionsEnabled()) {
2609 nav_entry_screenshot_cache_ =
2610 std::make_unique<NavigationEntryScreenshotCache>(
2611 BrowserContextImpl::From(browser_context_)
2612 ->GetNavigationEntryScreenshotManager()
2613 ->GetSafeRef(),
2614 this);
2615 }
2616 return nav_entry_screenshot_cache_.get();
2617}
2618
clamy987a3752018-05-03 17:36:262619void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2620 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2621 // progress, since this will cause a use-after-free. (We only allow this
2622 // when the tab is being destroyed for shutdown, since it won't return to
2623 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032624 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262625
2626 if (was_failure && pending_entry_) {
2627 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2628 } else {
2629 failed_pending_entry_id_ = 0;
2630 }
2631
2632 if (pending_entry_) {
2633 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332634 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262635 pending_entry_index_ = -1;
2636 pending_entry_ = nullptr;
2637 }
arthursonzogni66f711c2019-10-08 14:40:362638
2639 // Ensure any refs to the current pending entry are ignored if they get
2640 // deleted, by clearing the set of known refs. All future pending entries will
2641 // only be affected by new refs.
2642 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262643}
2644
2645void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2646 if (pending_entry_)
2647 pending_entry_->set_ssl_error(error);
2648}
2649
Xiaohan Wang7f8052e02022-01-14 18:44:282650#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422651// static
2652bool NavigationControllerImpl::ValidateDataURLAsString(
2653 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2654 if (!data_url_as_string)
2655 return false;
2656
2657 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2658 return false;
2659
2660 // The number of characters that is enough for validating a data: URI.
2661 // From the GURL's POV, the only important part here is scheme, it doesn't
2662 // check the actual content. Thus we can take only the prefix of the url, to
2663 // avoid unneeded copying of a potentially long string.
2664 const size_t kDataUriPrefixMaxLen = 64;
2665 GURL data_url(
2666 std::string(data_url_as_string->front_as<char>(),
2667 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2668 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2669 return false;
2670
2671 return true;
2672}
2673#endif
2674
Shivani Sharma194877032019-03-07 17:52:472675void NavigationControllerImpl::NotifyUserActivation() {
2676 // When a user activation occurs, ensure that all adjacent entries for the
2677 // same document clear their skippable bit, so that the history manipulation
2678 // intervention does not apply to them.
Lijin Shen9c475d32023-09-02 00:15:012679 const bool can_go_back = CanGoBack();
Shivani Sharmac4cc8922019-04-18 03:11:172680 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Lijin Shen9c475d32023-09-02 00:15:012681 // If the value of CanGoBack changes as a result of making some entries
2682 // non-skippable, then we must let the delegate know to update its UI state.
2683 // See https://crbug.com/1477784.
2684 if (!can_go_back && CanGoBack()) {
2685 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
2686 }
Shivani Sharma194877032019-03-07 17:52:472687}
2688
clamy987a3752018-05-03 17:36:262689bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2690 RenderFrameHostImpl* render_frame_host,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332691 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client,
2692 blink::LocalFrameToken initiator_frame_token,
2693 int initiator_process_id) {
clamy987a3752018-05-03 17:36:262694 NavigationEntryImpl* entry =
2695 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2696 if (!entry)
2697 return false;
2698
2699 FrameNavigationEntry* frame_entry =
2700 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2701 if (!frame_entry)
2702 return false;
2703
Camille Lamy5193caa2018-10-12 11:59:422704 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572705 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232706 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332707 true /* is_history_navigation_in_new_child */, initiator_frame_token,
2708 initiator_process_id);
clamyea99ea12018-05-28 13:54:232709
2710 if (!request)
2711 return false;
2712
arthursonzognif046d4a2019-12-12 19:08:102713 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412714
Rakina Zata Amni1c83b082023-02-08 01:09:002715 SCOPED_CRASH_KEY_STRING256(
2716 "Bug1400009", "req_url",
2717 request->GetURL().GetWithEmptyPath().possibly_invalid_spec());
2718 SCOPED_CRASH_KEY_NUMBER(
2719 "Bug1400009", "nav_entry_si",
2720 entry->site_instance() ? ((int)entry->site_instance()->GetId()) : -1);
2721 SCOPED_CRASH_KEY_NUMBER("Bug1400009", "fne_si",
2722 frame_entry->site_instance()
2723 ? ((int)frame_entry->site_instance()->GetId())
2724 : -1);
2725 bool has_sig =
2726 (frame_entry->site_instance() && frame_entry->site_instance()->group());
2727 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_exists", has_sig);
2728 SCOPED_CRASH_KEY_BOOL("Bug1400009", "fne_sig_has_rvh",
2729 has_sig ? (!!frame_tree_->GetRenderViewHost(
2730 frame_entry->site_instance()->group()))
2731 : false);
Lukasz Anforowicz9ee83c272020-12-01 20:14:052732 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2733 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232734
2735 return true;
clamy987a3752018-05-03 17:36:262736}
2737
Tsuyoshi Horo52fd08e2020-07-07 07:03:452738bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2739 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2740 if (!entry)
2741 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432742
2743 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2744 // We should never navigate to an existing initial NavigationEntry that is
2745 // the initial NavigationEntry for the initial empty document that hasn't
2746 // been overridden by the synchronous about:blank commit, to preserve
2747 // legacy behavior where trying to reload when the main frame is on the
2748 // initial empty document won't result in a navigation. See also
2749 // https://crbug.com/1277414.
2750 return false;
2751 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452752 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2753 if (!frame_entry)
2754 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142755 ReloadType reload_type = ReloadType::NORMAL;
2756 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452757 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142758 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452759 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432760 false /* is_history_navigation_in_new_child */,
Arthur Sonzognic686e8f2024-01-11 08:36:372761 std::nullopt /* initiator_frame_token */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:332762 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452763 if (!request)
2764 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052765 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452766 return true;
2767}
2768
clamy987a3752018-05-03 17:36:262769void NavigationControllerImpl::NavigateFromFrameProxy(
2770 RenderFrameHostImpl* render_frame_host,
2771 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022772 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452773 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:372774 const std::optional<url::Origin>& initiator_origin,
2775 const std::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262776 bool is_renderer_initiated,
2777 SiteInstance* source_site_instance,
2778 const Referrer& referrer,
2779 ui::PageTransition page_transition,
2780 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252781 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262782 const std::string& method,
2783 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092784 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142785 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212786 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502787 bool is_form_submission,
Arthur Sonzognic686e8f2024-01-11 08:36:372788 const std::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292789 blink::mojom::NavigationInitiatorActivationAndAdStatus
2790 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222791 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492792 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462793 bool is_unfenced_top_navigation,
Sergey Poromovdd557c12023-03-01 11:28:452794 bool force_new_browsing_instance,
Camillia Smith Barnes6a643962023-03-03 00:28:582795 bool is_container_initiated,
Arthur Sonzognic686e8f2024-01-11 08:36:372796 std::optional<std::u16string> embedder_shared_storage_context) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582797 if (is_renderer_initiated)
2798 DCHECK(initiator_origin.has_value());
2799
clamy987a3752018-05-03 17:36:262800 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582801
Rakina Zata Amni2322f4f82022-01-24 13:24:242802 // Don't allow an entry replacement if there is no entry to replace.
2803 // http://crbug.com/457149
2804 if (GetEntryCount() == 0)
2805 should_replace_current_entry = false;
2806
clamy987a3752018-05-03 17:36:262807 // Create a NavigationEntry for the transfer, without making it the pending
2808 // entry. Subframe transfers should have a clone of the last committed entry
2809 // with a FrameNavigationEntry for the target frame. Main frame transfers
2810 // should have a new NavigationEntry.
2811 // TODO(creis): Make this unnecessary by creating (and validating) the params
2812 // directly, passing them to the destination RenderFrameHost. See
2813 // https://crbug.com/536906.
2814 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262815 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262816 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452817 DCHECK(GetLastCommittedEntry());
2818 entry = GetLastCommittedEntry()->Clone();
2819 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172820 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2821 // Renderer-initiated navigation that target a remote frame are currently
2822 // classified as browser-initiated when this one has already navigated.
2823 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372824 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2825 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2826 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2827 // same-document navigation), they will still be present in the
2828 // committed NavigationEntry that will be referenced to construct the new
2829 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262830 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082831 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582832 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372833 std::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212834 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152835 blob_url_loader_factory, nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262836 } else {
2837 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172838 // If `node` is the outermost main frame, it rewrites a virtual url in order
2839 // to adjust the original input url if needed. For inner frames such as
2840 // fenced frames or subframes, they don't rewrite urls as the urls are not
2841 // input urls by users.
2842 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Arthur Sonzognic686e8f2024-01-11 08:36:372843 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:322844 if (source_site_instance && source_site_instance->HasProcess()) {
2845 source_process_site_url =
2846 source_site_instance->GetProcess()->GetProcessLock().site_url();
2847 }
clamy987a3752018-05-03 17:36:262848 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212849 url, referrer, initiator_origin, initiator_base_url,
Sharon Yang242ef822023-05-15 21:07:322850 source_process_site_url, page_transition, is_renderer_initiated,
W. James MacLean23e90a12022-12-21 04:38:212851 extra_headers, browser_context_, blob_url_loader_factory,
2852 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262853 entry->root_node()->frame_entry->set_source_site_instance(
2854 static_cast<SiteInstanceImpl*>(source_site_instance));
2855 entry->root_node()->frame_entry->set_method(method);
2856 }
clamy987a3752018-05-03 17:36:262857
Camille Lamy5193caa2018-10-12 11:59:422858 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452859 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262860 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422861 override_user_agent = true;
clamy987a3752018-05-03 17:36:262862 }
2863 // TODO(creis): Set user gesture and intent received timestamp on Android.
2864
2865 // We may not have successfully added the FrameNavigationEntry to |entry|
2866 // above (per https://crbug.com/608402), in which case we create it from
2867 // scratch. This works because we do not depend on |frame_entry| being inside
2868 // |entry| during NavigateToEntry. This will go away when we shortcut this
2869 // further in https://crbug.com/536906.
2870 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2871 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452872 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082873 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582874 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Arthur Sonzognic686e8f2024-01-11 08:36:372875 std::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212876 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Kunihiko Sakamoto2ae79e62023-05-26 00:34:152877 blob_url_loader_factory, nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572878 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262879 }
2880
Camille Lamy5193caa2018-10-12 11:59:422881 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022882 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452883 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292884 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212885 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422886 params.source_site_instance = source_site_instance;
2887 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2888 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032889 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422890 params.referrer = referrer;
2891 /* params.redirect_chain: skip */
2892 params.extra_headers = extra_headers;
2893 params.is_renderer_initiated = is_renderer_initiated;
2894 params.override_user_agent = UA_OVERRIDE_INHERIT;
2895 /* params.base_url_for_data_url: skip */
2896 /* params.virtual_url_for_data_url: skip */
2897 /* params.data_url_as_string: skip */
2898 params.post_data = post_body;
2899 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582900 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422901 /* params.frame_name: skip */
2902 // TODO(clamy): See if user gesture should be propagated to this function.
2903 params.has_user_gesture = false;
2904 params.should_clear_history_list = false;
2905 params.started_from_context_menu = false;
2906 /* params.navigation_ui_data: skip */
2907 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222908 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542909 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212910 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412911 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502912 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292913 params.initiator_activation_and_ad_status =
2914 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422915
2916 std::unique_ptr<NavigationRequest> request =
2917 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032918 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142919 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392920 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492921 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:582922 is_unfenced_top_navigation, is_container_initiated,
2923 embedder_shared_storage_context);
clamyea99ea12018-05-28 13:54:232924
2925 if (!request)
2926 return;
2927
Garrett Tanzerbb8db412022-09-27 21:59:462928 // Force the navigation to take place in a new browsing instance.
2929 // This is used by _unfencedTop in fenced frames to ensure that navigations
2930 // leaving the fenced context create a new browsing instance.
2931 if (force_new_browsing_instance) {
2932 request->coop_status().ForceBrowsingInstanceSwap();
2933 }
2934
Arthur Hemery948742762019-09-18 10:06:242935 // At this stage we are proceeding with this navigation. If this was renderer
2936 // initiated with user gesture, we need to make sure we clear up potential
2937 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2938 DiscardNonCommittedEntries();
2939
Lukasz Anforowicz9ee83c272020-12-01 20:14:052940 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262941}
2942
[email protected]d1198fd2012-08-13 22:50:192943void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252944 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212945 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192946 if (!session_storage_namespace)
2947 return;
2948
2949 // We can't overwrite an existing SessionStorage without violating spec.
2950 // Attempts to do so may give a tab access to another tab's session storage
2951 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152952 bool successful_insert =
2953 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252954 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052955 static_cast<SessionStorageNamespaceImpl*>(
2956 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302957 .second;
2958 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192959}
2960
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572961bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452962 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032963 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462964}
2965
Aran Gilman37d11632019-10-08 23:07:152966SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252967 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302968 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252969 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032970 DOMStorageContextWrapper* context_wrapper =
2971 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2972
2973 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252974 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032975 if (it != session_storage_namespace_map_.end()) {
2976 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152977 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2978 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472979
michaelnbacbcbd2016-02-09 00:32:032980 return it->second.get();
2981 }
2982
2983 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102984 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2985 SessionStorageNamespaceImpl::Create(context_wrapper);
2986 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2987 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252988 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102989 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302990
Daniel Murphy31bbb8b12018-02-07 21:44:102991 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302992}
2993
2994SessionStorageNamespace*
2995NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252996 return GetSessionStorageNamespace(
2997 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302998}
2999
3000const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573001NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:303002 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:553003}
[email protected]d202a7c2012-01-04 07:53:473004
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573005bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:563006 return needs_reload_;
3007}
[email protected]a26023822011-12-29 00:23:553008
[email protected]46bb5e9c2013-10-03 22:16:473009void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:413010 SetNeedsReload(NeedsReloadType::kRequestedByClient);
3011}
3012
3013void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:473014 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:413015 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:543016
3017 if (last_committed_entry_index_ != -1) {
3018 entries_[last_committed_entry_index_]->SetTransitionType(
3019 ui::PAGE_TRANSITION_RELOAD);
3020 }
[email protected]46bb5e9c2013-10-03 22:16:473021}
3022
[email protected]d202a7c2012-01-04 07:53:473023void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:573024 DCHECK_LT(index, GetEntryCount());
3025 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:313026 DiscardNonCommittedEntries();
3027
Nate Chapin9eb16be72022-09-23 22:54:313028 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:313029 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:123030 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:313031 last_committed_entry_index_--;
3032}
3033
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573034NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:273035 // If there is no pending_entry_, there should be no pending_entry_index_.
3036 DCHECK(pending_entry_ || pending_entry_index_ == -1);
3037
3038 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:363039 // at that index. An exception is while a reload of a post commit error page
3040 // is ongoing; in that case pending entry will point to the entry replaced
3041 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:273042 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:363043 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
3044 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:273045
[email protected]022af742011-12-28 18:37:253046 return pending_entry_;
3047}
3048
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573049int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:273050 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:273051 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:553052 return pending_entry_index_;
3053}
3054
avi25764702015-06-23 15:43:373055void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:573056 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:363057 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:313058 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:003059 bool in_fenced_frame_tree,
3060 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:313061 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
3062 // set because:
3063 // 1) They don't influence the history of the outer page.
3064 // 2) They are always replace only navigation (there is always only one entry
3065 // in their history stack).
3066 // 3) Are not top level navigations and appear similar to iframes.
3067 // Navigations of the fenced frame might create a new NavigationEntry, which
3068 // will call this function. Non fenced frame navigations will never have
3069 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
3070 // InsertOrReplaceEntry.
3071 DCHECK_EQ(in_fenced_frame_tree,
3072 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
3073 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:203074
avi5cad4912015-06-19 05:25:443075 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
3076 // need to keep continuity with the pending entry, so copy the pending entry's
3077 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
3078 // then the renderer navigated on its own, independent of the pending entry,
3079 // so don't copy anything.
3080 if (pending_entry_ && pending_entry_index_ == -1)
3081 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:203082
Rakina Zata Amnia4e27222021-12-22 01:05:003083 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:203084
creisee17e932015-07-17 17:56:223085 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:453086 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:103087 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573088 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:363089 // If the new entry is a post-commit error page, we store the current last
3090 // committed entry to the side so that we can put it back when navigating
3091 // away from the error.
3092 if (was_post_commit_error) {
3093 DCHECK(!entry_replaced_by_post_commit_error_);
3094 entry_replaced_by_post_commit_error_ =
3095 std::move(entries_[last_committed_entry_index_]);
3096 }
dcheng36b6aec92015-12-26 06:16:363097 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:223098 return;
3099 }
[email protected]765b35502008-08-21 00:51:203100
creis37979a62015-08-04 19:48:183101 // We shouldn't see replace == true when there's no committed entries.
3102 DCHECK(!replace);
3103
Michael Thiessen9b14d512019-09-23 21:19:473104 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:203105
Shivani Sharmad8c8d652019-02-13 17:27:573106 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:203107
dcheng36b6aec92015-12-26 06:16:363108 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:203109 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:293110}
3111
Shivani Sharmad8c8d652019-02-13 17:27:573112void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:163113 if (entries_.size() < max_entry_count())
3114 return;
3115
3116 DCHECK_EQ(max_entry_count(), entries_.size());
3117 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:573118 CHECK_EQ(pending_entry_index_, -1);
3119
3120 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423121 // Retrieve the oldest skippable entry.
3122 for (; index < GetEntryCount(); index++) {
3123 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3124 break;
Shivani Sharmad8c8d652019-02-13 17:27:573125 }
3126
3127 // If there is no skippable entry or if it is the last committed entry then
3128 // fall back to pruning the oldest entry. It is not safe to prune the last
3129 // committed entry.
3130 if (index == GetEntryCount() || index == last_committed_entry_index_)
3131 index = 0;
3132
3133 bool should_succeed = RemoveEntryAtIndex(index);
3134 DCHECK_EQ(true, should_succeed);
3135
3136 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253137}
3138
clamy3cb9bea92018-07-10 12:42:023139void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163140 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203141 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:373142 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133143 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203144 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503145 TRACE_EVENT0("navigation",
3146 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273147 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023148 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363149 if (pending_entry_index_ != -1) {
3150 // The pending entry may not be in entries_ if a post-commit error page is
3151 // showing.
3152 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3153 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3154 }
Gyuyoung Kim107c2a02021-04-13 01:49:303155 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573156 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013157 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033158 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573159 int nav_entry_id = pending_entry_->GetUniqueID();
Yoav Weiss8c573952022-11-17 17:35:133160 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3161 // the same as the top level frame being navigated.
3162 if (root->current_frame_host() != initiator_rfh) {
Arthur Sonzognic686e8f2024-01-11 08:36:373163 soft_navigation_heuristics_task_id = std::nullopt;
Yoav Weiss8c573952022-11-17 17:35:133164 }
Arthur Sonzogni620cec62018-12-13 13:08:573165
[email protected]83c2e232011-10-07 21:36:463166 // If we were navigating to a slow-to-commit page, and the user performs
3167 // a session history navigation to the last committed page, RenderViewHost
3168 // will force the throbber to start, but WebKit will essentially ignore the
3169 // navigation, and won't send a message to stop the throbber. To prevent this
3170 // from happening, we drop the navigation here and stop the slow-to-commit
3171 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023172 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083173 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273174 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033175 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123176
[email protected]83c2e232011-10-07 21:36:463177 DiscardNonCommittedEntries();
3178 return;
3179 }
3180
Arthur Sonzognic686e8f2024-01-11 08:36:373181 std::optional<blink::LocalFrameToken> initiator_frame_token;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333182 int initiator_process_id = ChildProcessHost::kInvalidUniqueID;
3183 if (initiator_rfh) {
3184 initiator_frame_token = initiator_rfh->GetFrameToken();
3185 initiator_process_id = initiator_rfh->GetProcess()->GetID();
3186 DCHECK(initiator_frame_token);
3187 }
3188
creisce0ef3572017-01-26 17:53:083189 // Compare FrameNavigationEntries to see which frames in the tree need to be
3190 // navigated.
clamy3cb9bea92018-07-10 12:42:023191 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3192 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333193 FindFramesToNavigate(root, reload_type, initiator_frame_token,
3194 initiator_process_id, soft_navigation_heuristics_task_id,
3195 &same_document_loads, &different_document_loads);
creis4e2ecb72015-06-20 00:46:303196
3197 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573198 // We were unable to match any frames to navigate. This can happen if a
3199 // history navigation targets a subframe that no longer exists
3200 // (https://crbug.com/705550). In this case, we need to update the current
3201 // history entry to the pending one but keep the main document loaded. We
3202 // also need to ensure that observers are informed about the updated
3203 // current history entry (e.g., for greying out back/forward buttons), and
3204 // that renderer processes update their history offsets. The easiest way
3205 // to do all that is to schedule a "redundant" same-document navigation in
3206 // the main frame.
3207 //
3208 // Note that we don't want to remove this history entry, as it might still
3209 // be valid later, since a frame that it's targeting may be recreated.
3210 //
3211 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3212 // need to repeat history navigations until finding the one that works.
3213 // Consider changing this behavior to keep looking for the first valid
3214 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023215 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423216 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573217 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573218 ReloadType::NONE /* reload_type */,
3219 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433220 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333221 initiator_frame_token, initiator_process_id);
clamy3cb9bea92018-07-10 12:42:023222 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573223 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023224 DiscardPendingEntry(false);
3225 return;
3226 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573227 same_document_loads.push_back(std::move(navigation_request));
3228
3229 // Sanity check that we never take this branch for any kinds of reloads,
3230 // as those should've queued a different-document load in the main frame.
3231 DCHECK(!is_forced_reload);
3232 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303233 }
3234
Nate Chapinbf682fa32022-09-26 22:41:203235 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163236 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203237 if (initiator_rfh && initiator_rfh->IsSandboxed(
3238 network::mojom::WebSandboxFlags::kTopNavigation)) {
3239 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3240 initiator_rfh, same_document_loads) &&
3241 DoesSandboxNavigationStayWithinSubtree(
3242 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503243 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163244 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203245 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3246 initiator_rfh,
3247 navigates_inside_tree
3248 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3249 : blink::mojom::WebFeature::
3250 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523251
3252 // If the navigation occurred outside the tree discard it because
3253 // the sandboxed frame didn't have permission to navigate outside
3254 // its tree. If it is possible that the navigation is both inside and
3255 // outside the frame tree and we discard it entirely because we don't
3256 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143257 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203258 // If a |navigation_api_key| was provided, this navigation originated from
3259 // the navigation API. Notify the renderer that the navigation was
3260 // cancelled so the navigation API can fire an error event and reject the
3261 // relevant promise.
3262 if (navigation_api_key) {
3263 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3264 *navigation_api_key,
3265 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3266 }
Dave Tapuska855c1e12019-08-23 20:45:523267 DiscardPendingEntry(false);
3268 return;
3269 }
Dave Tapuska8bfd84c2019-03-26 20:47:163270 }
3271
Nate Chapin6c43c022023-02-13 23:32:423272 // If it is possible that this traverse may involve a same-document navigation
3273 // in the initiator and there is a Navigation API key involved, then we may
3274 // need to notify the initiator if it fails. (The early returns above either
3275 // do not involve these cases or already notify the initiator.)
3276 // The event only needs to fire for the initiator, and only if the initiator
3277 // itself is performing a same-document navigation (because the event will not
3278 // fire if it navigates cross-document).
3279 if (navigation_api_key) {
3280 for (auto& item : same_document_loads) {
3281 if (item->frame_tree_node() == initiator_rfh->frame_tree_node()) {
3282 item->set_pending_navigation_api_key(*navigation_api_key);
3283 break;
3284 }
3285 }
3286 }
3287
Carlos Caballero539a421c2020-07-06 10:25:573288 // BackForwardCache:
3289 // Navigate immediately if the document is in the BackForwardCache.
Mingyu Lei7584b6b2023-04-13 03:02:563290 if (back_forward_cache_.GetOrEvictEntry(nav_entry_id).has_value()) {
Carlos Caballero539a421c2020-07-06 10:25:573291 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3292 DCHECK_EQ(reload_type, ReloadType::NONE);
3293 auto navigation_request = CreateNavigationRequestFromEntry(
3294 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3295 ReloadType::NONE, false /* is_same_document_history_load */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333296 false /* is_history_navigation_in_new_child */, initiator_frame_token,
3297 initiator_process_id);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053298 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573299
3300 return;
3301 }
3302
3303 // History navigation might try to reuse a specific BrowsingInstance, already
3304 // used by a page in the cache. To avoid having two different main frames that
3305 // live in the same BrowsingInstance, evict the all pages with this
3306 // BrowsingInstance from the cache.
3307 //
3308 // For example, take the following scenario:
3309 //
3310 // A1 = Some page on a.com
3311 // A2 = Some other page on a.com
3312 // B3 = An uncacheable page on b.com
3313 //
3314 // Then the following navigations occur:
3315 // A1->A2->B3->A1
3316 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3317 // take its place) and A1 will be created in the same BrowsingInstance (and
3318 // SiteInstance), as A2.
3319 //
3320 // If we didn't do anything, both A1 and A2 would remain alive in the same
3321 // BrowsingInstance/SiteInstance, which is unsupported by
3322 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3323 // A2 from the cache.
3324 if (pending_entry_->site_instance()) {
3325 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3326 pending_entry_->site_instance());
3327 }
3328
Rakina Zata Amnid605d462022-06-01 10:17:033329 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3330 pending_entry_ && pending_entry_->IsRestored());
3331 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3332 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3333 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3334 pending_entry_index_);
3335 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3336 last_committed_entry_index_);
3337 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3338 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3339 pending_entry_ && pending_entry_->IsInitialEntry());
3340 SCOPED_CRASH_KEY_BOOL(
3341 "nav_reentrancy", "pending_entry_initial2",
3342 pending_entry_ &&
3343 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3344 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3345 IsInitialNavigation());
3346 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3347 IsInitialBlankNavigation());
3348 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3349 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3350 (int)pending_reload_);
3351
clamy3cb9bea92018-07-10 12:42:023352 // This call does not support re-entrancy. See http://crbug.com/347742.
3353 CHECK(!in_navigate_to_pending_entry_);
3354 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303355
Rakina Zata Amnid605d462022-06-01 10:17:033356 // If the navigation-reentrancy is caused by calling
3357 // NavigateToExistingPendingEntry twice, this will note the previous call's
3358 // pending entry's ID.
3359 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3360 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3361
arthursonzogni66f711c2019-10-08 14:40:363362 // It is not possible to delete the pending NavigationEntry while navigating
3363 // to it. Grab a reference to delay potential deletion until the end of this
3364 // function.
3365 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3366
Nate Chapin154b14b2023-02-17 18:28:163367 // If there is a main-frame same-document history navigation, we may defer
3368 // the subframe history navigations in order to give JS in the main frame the
3369 // opportunity to cancel the entire traverse via the navigate event. In that
3370 // case, we need to stash the main frame request's navigation token on the
3371 // subframes, so they can look up the main frame request and defer themselves
3372 // until it completes.
3373 if (!same_document_loads.empty() &&
3374 same_document_loads.at(0)->frame_tree_node()->IsMainFrame()) {
3375 NavigationRequest* main_frame_request = same_document_loads.at(0).get();
3376 // The token will only be returned in cases where deferring the navigation
3377 // is necessary.
3378 if (auto main_frame_same_document_token =
3379 main_frame_request->GetNavigationTokenForDeferringSubframes()) {
3380 for (auto& item : same_document_loads) {
3381 if (item.get() != main_frame_request) {
3382 item->set_main_frame_same_document_history_token(
3383 main_frame_same_document_token);
3384 }
3385 }
3386 for (auto& item : different_document_loads) {
3387 item->set_main_frame_same_document_history_token(
3388 main_frame_same_document_token);
3389 }
3390 }
3391 }
3392
William Liu122754942024-01-18 22:34:393393 if (!initiator_rfh) {
3394 // A browser-initiated navigation won't have a `initiator_rfh`.
3395 CountBrowserInitiatedMainframeAndSubframeHistoryNavigaions(
3396 different_document_loads, same_document_loads);
3397 }
3398
creis4e2ecb72015-06-20 00:46:303399 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023400 for (auto& item : same_document_loads) {
3401 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053402 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303403 }
clamy3cb9bea92018-07-10 12:42:023404 for (auto& item : different_document_loads) {
3405 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053406 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303407 }
clamy3cb9bea92018-07-10 12:42:023408
3409 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303410}
3411
Alex Moshchuk3a4e77a2020-05-29 21:32:573412NavigationControllerImpl::HistoryNavigationAction
3413NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303414 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573415 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423416 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583417 // Only active and prerendered documents are allowed to navigate in their
3418 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423419 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013420 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583421 // - If the document is in pending deletion, the browser already committed
3422 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3423 // - If the document is in back-forward cache, it's not allowed to navigate
3424 // as it should remain frozen. Ignore the request and evict the document
3425 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423426 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583427 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423428 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113429 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3430 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423431 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113432 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423433 }
arthursonzogni03f76152019-02-12 10:35:203434
Alex Moshchuk3a4e77a2020-05-29 21:32:573435 // Reloads should result in a different-document load. Note that reloads may
3436 // also happen via the |needs_reload_| mechanism where the reload_type is
3437 // NONE, so detect this by comparing whether we're going to the same
3438 // entry that we're currently on. Similarly to above, only main frames
3439 // should reach this. Note that subframes support reloads, but that's done
3440 // via a different path that doesn't involve FindFramesToNavigate (see
3441 // RenderFrameHost::Reload()).
3442 if (reload_type != ReloadType::NONE ||
3443 pending_entry_index_ == last_committed_entry_index_) {
3444 DCHECK(frame->IsMainFrame());
3445 return HistoryNavigationAction::kDifferentDocument;
3446 }
3447
Alex Moshchuk47d1a4bd2020-06-01 22:15:343448 // If there is no new FrameNavigationEntry for the frame, ignore the
3449 // load. For example, this may happen when going back to an entry before a
3450 // frame was created. Suppose we commit a same-document navigation that also
3451 // results in adding a new subframe somewhere in the tree. If we go back,
3452 // the new subframe will be missing a FrameNavigationEntry in the previous
3453 // NavigationEntry, but we shouldn't delete or change what's loaded in
3454 // it.
3455 //
Alex Moshchuke65c39272020-06-03 17:55:373456 // Note that in this case, there is no need to keep looking for navigations
3457 // in subframes, which would be missing FrameNavigationEntries as well.
3458 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343459 // It's important to check this before checking |old_item| below, since both
3460 // might be null, and in that case we still shouldn't change what's loaded in
3461 // this frame. Note that scheduling any loads assumes that |new_item| is
3462 // non-null. See https://crbug.com/1088354.
3463 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3464 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373465 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343466
Charlie Reisa474fb62022-03-17 02:31:363467 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3468 // which history item it is currently on, since this may be different than the
3469 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3470 // (e.g., if a history navigation is targeting multiple frames and only some
3471 // have committed so far).
creis4e2ecb72015-06-20 00:46:303472 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363473 frame->current_frame_host()->last_committed_frame_entry();
3474 if (!old_item) {
3475 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3476 // fall back to the last committed NavigationEntry's record for this frame.
3477 // This may happen in cases like the initial state of the RenderFrameHost.
3478 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3479 // accurate FrameNavigationEntry and eliminate this case.
3480 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3481 }
3482 // If neither approach finds a FrameNavigationEntry, schedule a
3483 // different-document load.
3484 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573485 if (!old_item)
3486 return HistoryNavigationAction::kDifferentDocument;
3487
Alex Moshchuk3a4e77a2020-05-29 21:32:573488 // If the new item is not in the same SiteInstance, schedule a
3489 // different-document load. Newly restored items may not have a SiteInstance
3490 // yet, in which case it will be assigned on first commit.
3491 if (new_item->site_instance() &&
3492 new_item->site_instance() != old_item->site_instance())
3493 return HistoryNavigationAction::kDifferentDocument;
3494
3495 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313496 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3497 // that we do this even if the history navigation would not be modifying this
3498 // frame were it live.
3499 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573500 return HistoryNavigationAction::kDifferentDocument;
3501
3502 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313503 // Starting a navigation after a crash early-promotes the speculative
3504 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3505 // committed yet, so we can not possibly perform a same-document history
3506 // navigation. The frame would need to be reloaded with a cross-document
3507 // navigation.
3508 if (!frame->current_frame_host()->has_committed_any_navigation())
3509 return HistoryNavigationAction::kDifferentDocument;
3510
creis54131692016-08-12 18:32:253511 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493512 // sequence number but different item sequence number.
3513 if (new_item->document_sequence_number() ==
3514 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573515 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493516 }
avib48cb312016-05-05 21:35:003517
Alex Moshchuk3a4e77a2020-05-29 21:32:573518 // Otherwise, if both item and document sequence numbers differ, this
3519 // should be a different document load.
3520 return HistoryNavigationAction::kDifferentDocument;
3521 }
3522
3523 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373524 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573525 DCHECK_EQ(new_item->document_sequence_number(),
3526 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373527 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573528}
3529
3530void NavigationControllerImpl::FindFramesToNavigate(
3531 FrameTreeNode* frame,
3532 ReloadType reload_type,
Arthur Sonzognic686e8f2024-01-11 08:36:373533 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333534 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373535 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:133536 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573537 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3538 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3539 DCHECK(pending_entry_);
3540 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3541
3542 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3543
3544 if (action == HistoryNavigationAction::kSameDocument) {
3545 std::unique_ptr<NavigationRequest> navigation_request =
3546 CreateNavigationRequestFromEntry(
3547 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133548 /*is_same_document_history_load=*/true,
3549 /*is_history_navigation_in_new_child_frame=*/false,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333550 initiator_frame_token, initiator_process_id,
3551 soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573552 if (navigation_request) {
3553 // Only add the request if was properly created. It's possible for the
3554 // creation to fail in certain cases, e.g. when the URL is invalid.
3555 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303556 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573557 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473558 std::unique_ptr<NavigationRequest> navigation_request =
3559 CreateNavigationRequestFromEntry(
3560 frame, pending_entry_, new_item, reload_type,
3561 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433562 false /* is_history_navigation_in_new_child */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333563 initiator_frame_token, initiator_process_id);
Lei Zhang96031532019-10-10 19:05:473564 if (navigation_request) {
3565 // Only add the request if was properly created. It's possible for the
3566 // creation to fail in certain cases, e.g. when the URL is invalid.
3567 different_document_loads->push_back(std::move(navigation_request));
3568 }
3569 // For a different document, the subframes will be destroyed, so there's
3570 // no need to consider them.
3571 return;
Alex Moshchuke65c39272020-06-03 17:55:373572 } else if (action == HistoryNavigationAction::kStopLooking) {
3573 return;
creis4e2ecb72015-06-20 00:46:303574 }
3575
Yoav Weiss8c573952022-11-17 17:35:133576 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3577 // we currently only support soft navigation heuristics for the top level
3578 // frame.
creis4e2ecb72015-06-20 00:46:303579 for (size_t i = 0; i < frame->child_count(); i++) {
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:333580 FindFramesToNavigate(frame->child_at(i), reload_type, initiator_frame_token,
3581 initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:373582 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Nate Chapin45f620582021-09-30 17:45:433583 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303584 }
3585}
3586
Harkiran Bolariaba823e42021-05-21 18:30:363587base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243588 const LoadURLParams& params) {
3589 // Find the appropriate FrameTreeNode.
3590 FrameTreeNode* node = nullptr;
3591 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3592 !params.frame_name.empty()) {
3593 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033594 ? frame_tree_->FindByID(params.frame_tree_node_id)
3595 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503596 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243597 }
3598
3599 // If no FrameTreeNode was specified, navigate the main frame.
3600 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033601 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243602
Camille Lamy5193caa2018-10-12 11:59:423603 // Compute overrides to the LoadURLParams for |override_user_agent|,
3604 // |should_replace_current_entry| and |has_user_gesture| that will be used
3605 // both in the creation of the NavigationEntry and the NavigationRequest.
3606 // Ideally, the LoadURLParams themselves would be updated, but since they are
3607 // passed as a const reference, this is not possible.
3608 // TODO(clamy): When we only create a NavigationRequest, move this to
3609 // CreateNavigationRequestFromLoadURLParams.
3610 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3611 GetLastCommittedEntry());
3612
Rakina Zata Amnie2d31312022-11-18 03:38:453613 // An entry replacement must happen if the current browsing context should
3614 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333615 bool should_replace_current_entry =
3616 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453617 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423618
clamy21718cc22018-06-13 13:34:243619 // Javascript URLs should not create NavigationEntries. All other navigations
3620 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243621 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373622 std::unique_ptr<NavigationEntryImpl> entry =
3623 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3624 should_replace_current_entry,
3625 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243626 DiscardPendingEntry(false);
3627 SetPendingEntry(std::move(entry));
3628 }
3629
Tim Judkins59548192023-05-17 17:51:203630 // Renderer-debug URLs are sent to the current renderer process immediately
3631 // for processing and don't need to create a NavigationRequest. Note: this
3632 // includes navigations to JavaScript URLs, which are considered
clamy21718cc22018-06-13 13:34:243633 // renderer-debug URLs.
3634 // Note: we intentionally leave the pending entry in place for renderer debug
3635 // URLs, unlike the cases below where we clear it if the navigation doesn't
3636 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303637 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483638 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3639 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153640 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Tim Judkins59548192023-05-17 17:51:203641 params.url, browser_context_, node->current_frame_host())) {
Oleg Davydov2cc0167b2019-02-05 14:32:483642 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363643 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483644 }
3645
clamy21718cc22018-06-13 13:34:243646 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363647 return nullptr;
clamy21718cc22018-06-13 13:34:243648 }
3649
Antonio Sartori78a749f2020-11-30 12:03:393650 DCHECK(pending_entry_);
3651
clamy21718cc22018-06-13 13:34:243652 // Convert navigations to the current URL to a reload.
3653 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3654 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3655 // DevTools sometimes issues navigations to main frames that they do not
3656 // expect to see treated as reload, and it only works because they pass a
3657 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3658 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543659 ReloadType reload_type = params.reload_type;
3660 if (reload_type == ReloadType::NONE &&
3661 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043662 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243663 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243664 params.load_type ==
3665 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543666 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243667 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473668 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393669
3670 // If this is a reload of an existing FrameNavigationEntry and we had a
3671 // policy container for it, then we should copy it into the pending entry,
3672 // so that it is copied to the navigation request in
3673 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453674 FrameNavigationEntry* previous_frame_entry =
3675 GetLastCommittedEntry()->GetFrameEntry(node);
3676 if (previous_frame_entry &&
3677 previous_frame_entry->policy_container_policies()) {
3678 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3679 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393680 }
3681 }
3682
3683 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173684 // document, then we should copy the document polices from RenderFrameHost's
3685 // PolicyContainerHost. The NavigationRequest will create a new
3686 // PolicyContainerHost with the document policies from the |pending_entry_|,
3687 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3688 // the navigation. This way, we ensure that we keep enforcing the right
3689 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453690 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393691 if (node->current_frame_host() &&
3692 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193693 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163694 node->current_frame_host()
3695 ->policy_container_host()
3696 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233697 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393698 }
clamy21718cc22018-06-13 13:34:243699 }
3700
3701 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263702 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243703
Tsuyoshi Horo167ca6432022-03-09 05:16:393704 // This will be used to set the Navigation Timing API navigationStart
3705 // parameter for browser navigations in new tabs (intents, tabs opened through
3706 // "Open link in new tab"). If the navigation must wait on the current
3707 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3708 // will be updated when the BeforeUnload ack is received.
3709 const auto navigation_start_time = base::TimeTicks::Now();
3710
Camille Lamy5193caa2018-10-12 11:59:423711 std::unique_ptr<NavigationRequest> request =
3712 CreateNavigationRequestFromLoadParams(
3713 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143714 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393715 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3716 navigation_start_time);
clamy21718cc22018-06-13 13:34:243717
3718 // If the navigation couldn't start, return immediately and discard the
3719 // pending NavigationEntry.
3720 if (!request) {
3721 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363722 return nullptr;
clamy21718cc22018-06-13 13:34:243723 }
3724
Camille Lamy5193caa2018-10-12 11:59:423725#if DCHECK_IS_ON()
3726 // Safety check that NavigationRequest and NavigationEntry match.
3727 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3728#endif
3729
clamy21718cc22018-06-13 13:34:243730 // This call does not support re-entrancy. See http://crbug.com/347742.
3731 CHECK(!in_navigate_to_pending_entry_);
3732 in_navigate_to_pending_entry_ = true;
3733
arthursonzogni66f711c2019-10-08 14:40:363734 // It is not possible to delete the pending NavigationEntry while navigating
3735 // to it. Grab a reference to delay potential deletion until the end of this
3736 // function.
3737 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3738
Harkiran Bolariaba823e42021-05-21 18:30:363739 base::WeakPtr<NavigationHandle> created_navigation_handle(
3740 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053741 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243742
3743 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363744 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243745}
3746
clamyea99ea12018-05-28 13:54:233747void NavigationControllerImpl::HandleRendererDebugURL(
3748 FrameTreeNode* frame_tree_node,
3749 const GURL& url) {
3750 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243751 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3752 // the renderer process is not live, unless it is the initial navigation
3753 // of the tab.
clamyea99ea12018-05-28 13:54:233754 if (!IsInitialNavigation()) {
3755 DiscardNonCommittedEntries();
3756 return;
3757 }
Fergal Dalyecd3b0202020-06-25 01:57:373758 // The current frame is always a main frame. If IsInitialNavigation() is
3759 // true then there have been no navigations and any frames of this tab must
3760 // be in the same renderer process. If that has crashed then the only frame
3761 // that can be revived is the main frame.
3762 frame_tree_node->render_manager()
3763 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233764 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223765
3766 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3767 // notification, so set is loading to true here to properly surface it when
3768 // the renderer process is done handling the URL.
3769 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3770 if (!url.SchemeIs(url::kJavaScriptScheme)) {
Julie Jeongeun Kim50d124c2022-10-21 13:51:223771 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
Julie Jeongeun Kim50d124c2022-10-21 13:51:223772 }
clamyea99ea12018-05-28 13:54:233773 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3774}
3775
clamy21718cc22018-06-13 13:34:243776std::unique_ptr<NavigationEntryImpl>
3777NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3778 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423779 const LoadURLParams& params,
3780 bool override_user_agent,
3781 bool should_replace_current_entry,
3782 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393783 // Browser initiated navigations might not have a blob_url_loader_factory set
3784 // in params even if the navigation is to a blob URL. If that happens, lookup
3785 // the correct url loader factory to use here.
3786 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483787 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473788 // Resolve the blob URL in the storage partition associated with the target
3789 // frame. This is the storage partition the URL will be loaded in, and only
3790 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393791 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473792 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393793 }
3794
clamy21718cc22018-06-13 13:34:243795 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443796 // extra_headers in params are \n separated; navigation entries want \r\n.
3797 std::string extra_headers_crlf;
3798 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243799
3800 // For subframes, create a pending entry with a corresponding frame entry.
3801 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453802 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243803 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083804 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243805 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Arthur Sonzognic686e8f2024-01-11 08:36:373806 params.url, std::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213807 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3808 "GET", -1, blob_url_loader_factory,
Antonio Sartori78a749f2020-11-30 12:03:393809 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163810 // a conversion of a new navigation into a reload, we will set the right
3811 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193812 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243813 } else {
3814 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173815 // If `node` is the outermost main frame, it rewrites a virtual url in order
3816 // to adjust the original input url if needed. For inner frames such as
3817 // fenced frames or subframes, they don't rewrite urls as the urls are not
3818 // input urls by users.
3819 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
Sharon Yang242ef822023-05-15 21:07:323820 scoped_refptr<SiteInstance> source_site_instance =
3821 params.source_site_instance;
Arthur Sonzognic686e8f2024-01-11 08:36:373822 std::optional<GURL> source_process_site_url = std::nullopt;
Sharon Yang242ef822023-05-15 21:07:323823 if (source_site_instance && source_site_instance->HasProcess()) {
3824 source_process_site_url =
3825 source_site_instance->GetProcess()->GetProcessLock().site_url();
3826 }
clamy21718cc22018-06-13 13:34:243827 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063828 params.url, params.referrer, params.initiator_origin,
Sharon Yang242ef822023-05-15 21:07:323829 params.initiator_base_url, source_process_site_url,
W. James MacLean23e90a12022-12-21 04:38:213830 params.transition_type, params.is_renderer_initiated,
3831 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3832 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243833 entry->set_source_site_instance(
3834 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3835 entry->SetRedirectChain(params.redirect_chain);
3836 }
3837
3838 // Set the FTN ID (only used in non-site-per-process, for tests).
3839 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243840 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423841 entry->SetIsOverridingUserAgent(override_user_agent);
3842 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543843 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243844
clamy21718cc22018-06-13 13:34:243845 switch (params.load_type) {
3846 case LOAD_TYPE_DEFAULT:
3847 break;
3848 case LOAD_TYPE_HTTP_POST:
3849 entry->SetHasPostData(true);
3850 entry->SetPostData(params.post_data);
3851 break;
3852 case LOAD_TYPE_DATA:
3853 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3854 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283855#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243856 entry->SetDataURLAsString(params.data_url_as_string);
3857#endif
3858 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3859 break;
clamy21718cc22018-06-13 13:34:243860 }
3861
3862 // TODO(clamy): NavigationEntry is meant for information that will be kept
3863 // after the navigation ended and therefore is not appropriate for
3864 // started_from_context_menu. Move started_from_context_menu to
3865 // NavigationUIData.
3866 entry->set_started_from_context_menu(params.started_from_context_menu);
3867
3868 return entry;
3869}
3870
clamyea99ea12018-05-28 13:54:233871std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423872NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3873 FrameTreeNode* node,
3874 const LoadURLParams& params,
3875 bool override_user_agent,
3876 bool should_replace_current_entry,
3877 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143878 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423879 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573880 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393881 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223882 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493883 bool is_embedder_initiated_fenced_frame_navigation,
Sergey Poromovdd557c12023-03-01 11:28:453884 bool is_unfenced_top_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:583885 bool is_container_initiated,
Arthur Sonzognic686e8f2024-01-11 08:36:373886 std::optional<std::u16string> embedder_shared_storage_context) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573887 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283888 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533889 // All renderer-initiated navigations must have an initiator_origin.
3890 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513891
Camille Lamy5193caa2018-10-12 11:59:423892 GURL url_to_load;
3893 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323894
Camille Lamy2baa8022018-10-19 16:43:173895 // For main frames, rewrite the URL if necessary and compute the virtual URL
3896 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263897 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423898 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173899 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423900 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423901
Camille Lamy2baa8022018-10-19 16:43:173902 // For DATA loads, override the virtual URL.
3903 if (params.load_type == LOAD_TYPE_DATA)
3904 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423905
Camille Lamy2baa8022018-10-19 16:43:173906 if (virtual_url.is_empty())
3907 virtual_url = url_to_load;
3908
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573909 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283910
Aran Gilman249eb122019-12-02 23:32:463911 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3912 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3913 // return different results, leading to a different URL in the
3914 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3915 // pending NavigationEntry, as we'll only make one call to
3916 // RewriteUrlForNavigation.
3917 VLOG_IF(1, (url_to_load != frame_entry->url()))
3918 << "NavigationRequest and FrameEntry have different URLs: "
3919 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283920
Camille Lamy2baa8022018-10-19 16:43:173921 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423922 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173923 // NavigationRequest.
3924 } else {
3925 url_to_load = params.url;
3926 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243927 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173928 }
Camille Lamy5193caa2018-10-12 11:59:423929
Ehsan Karamad44fc72112019-02-26 18:15:473930 if (node->render_manager()->is_attaching_inner_delegate()) {
3931 // Avoid starting any new navigations since this node is now preparing for
3932 // attaching an inner delegate.
3933 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203934 }
Camille Lamy5193caa2018-10-12 11:59:423935
Alex Moshchuk99242832023-05-22 17:21:443936 if (!IsValidURLForNavigation(node, virtual_url, url_to_load)) {
Camille Lamy5193caa2018-10-12 11:59:423937 return nullptr;
Alex Moshchuk99242832023-05-22 17:21:443938 }
Camille Lamy5193caa2018-10-12 11:59:423939
danakjd83d706d2020-11-25 22:11:123940 // Look for a pending commit that is to another document in this
3941 // FrameTreeNode. If one exists, then the last committed URL will not be the
3942 // current URL by the time this navigation commits.
3943 bool has_pending_cross_document_commit =
3944 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213945 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123946
Minggang Wangb9f3fa92021-07-01 15:30:313947 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493948 /*old_url=*/node->current_url(),
3949 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3950 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133951 /*is_same_document_history_load=*/false,
3952 is_embedder_initiated_fenced_frame_navigation,
3953 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423954
3955 // Create the NavigationParams based on |params|.
3956
Hiroki Nakagawa4ed61282021-06-18 05:37:233957 bool is_view_source_mode = entry->IsViewSourceMode();
3958 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293959
Antonio Sartori6984c742021-08-26 08:03:413960 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293961
Hiroki Nakagawa4ed61282021-06-18 05:37:233962 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293963 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253964 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293965
Minggang Wangb9f3fa92021-07-01 15:30:313966 blink::mojom::CommonNavigationParamsPtr common_params =
3967 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213968 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513969 blink::mojom::Referrer::New(params.referrer.url,
3970 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213971 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513972 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393973 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513974 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143975 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413976 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273977 false /* has_text_fragment_token */,
3978 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3979 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513980 false /* is_history_navigation_in_new_child_frame */,
Chris Fredricksonb52bcd02023-03-28 14:48:053981 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423982
Minggang Wangb9f3fa92021-07-01 15:30:313983 blink::mojom::CommitNavigationParamsPtr commit_params =
3984 blink::mojom::CommitNavigationParams::New(
Arthur Sonzognic686e8f2024-01-11 08:36:373985 std::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073986 // The correct storage key and session storage key will be computed
3987 // before committing the navigation.
3988 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3989 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323990 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503991 std::vector<net::RedirectInfo>(), params.post_content_type,
3992 common_params->url, common_params->method,
3993 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313994 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133995 entry->GetSubframeUniqueNames(node),
3996 /*intended_as_new_entry=*/true,
3997 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143998 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3999 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:134000 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:314001 params.should_clear_history_list,
4002 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:224003 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:134004 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:514005 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:284006#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:134007 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144008#endif
Yoav Weiss8c573952022-11-17 17:35:134009 /*is_browser_initiated=*/!params.is_renderer_initiated,
Yoav Weiss8c573952022-11-17 17:35:134010 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:074011 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134012 /*force_enabled_origin_trials=*/std::vector<std::string>(),
4013 /*origin_agent_cluster=*/false,
4014 /*origin_agent_cluster_left_as_default=*/true,
4015 /*enabled_client_hints=*/
4016 std::vector<network::mojom::WebClientHintsType>(),
4017 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
4018 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:014019 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:134020 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:584021 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:134022 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:134023 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:284024 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:134025 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:444026 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:424027 network::mojom::NavigationDeliveryType::kDefault,
Arthur Sonzognic686e8f2024-01-11 08:36:374028 /*view_transition_state=*/std::nullopt,
4029 /*soft_navigation_heuristics_task_id=*/std::nullopt,
sbinglera07ae732022-12-02 20:49:054030 /*modified_runtime_features=*/
Jiewei Qian87951f52023-10-17 01:33:464031 base::flat_map<::blink::mojom::RuntimeFeature, bool>(),
Arthur Sonzognic686e8f2024-01-11 08:36:374032 /*fenced_frame_properties=*/std::nullopt,
Chris Fredricksonb52bcd02023-03-28 14:48:054033 /*not_restored_reasons=*/nullptr,
Arthur Hemeryd51484b2023-06-02 15:50:004034 /*load_with_storage_access=*/false,
Arthur Sonzognic686e8f2024-01-11 08:36:374035 /*browsing_context_group_info=*/std::nullopt,
Nan Linda394ba2023-11-03 21:17:374036 /*lcpp_hint=*/nullptr, blink::CreateDefaultRendererContentSettings(),
Arthur Sonzognic686e8f2024-01-11 08:36:374037 /*cookie_deprecation_label=*/std::nullopt);
Xiaohan Wang7f8052e02022-01-14 18:44:284038#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:424039 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:144040 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:424041 }
4042#endif
4043
Lucas Furukawa Gadania9c45682019-07-31 22:05:144044 commit_params->was_activated = params.was_activated;
Mike Jacksone2aa7af2023-05-17 06:45:074045 commit_params->navigation_timing->system_entropy_at_navigation_start =
4046 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4047 node, params.suggested_system_entropy);
Camille Lamy5193caa2018-10-12 11:59:424048
Camille Lamy5193caa2018-10-12 11:59:424049 // extra_headers in params are \n separated; NavigationRequests want \r\n.
4050 std::string extra_headers_crlf;
4051 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:094052
Alex Moshchuk9321e6a2022-12-07 21:58:314053 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144054 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084055 !params.is_renderer_initiated, params.was_opener_suppressed,
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094056 params.initiator_frame_token, params.initiator_process_id,
4057 extra_headers_crlf, frame_entry, entry, params.is_form_submission,
John Delaney50425f82020-04-07 16:26:214058 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:294059 params.impression, params.initiator_activation_and_ad_status,
Sergey Poromovdd557c12023-03-01 11:28:454060 params.is_pdf, is_embedder_initiated_fenced_frame_navigation,
Camillia Smith Barnes6a643962023-03-03 00:28:584061 is_container_initiated, embedder_shared_storage_context);
Yao Xiaodc5ed102019-06-04 19:19:094062 navigation_request->set_from_download_cross_origin_redirect(
4063 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:554064 navigation_request->set_force_new_browsing_instance(
4065 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:094066 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:424067}
4068
4069std::unique_ptr<NavigationRequest>
4070NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:234071 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574072 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:234073 FrameNavigationEntry* frame_entry,
4074 ReloadType reload_type,
4075 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:434076 bool is_history_navigation_in_new_child_frame,
Arthur Sonzognic686e8f2024-01-11 08:36:374077 const std::optional<blink::LocalFrameToken>& initiator_frame_token,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334078 int initiator_process_id,
Arthur Sonzognic686e8f2024-01-11 08:36:374079 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weiss8c573952022-11-17 17:35:134080 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:344081 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:234082 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:434083 // We should never navigate to an existing initial NavigationEntry that is the
4084 // initial NavigationEntry for the initial empty document that hasn't been
4085 // overridden by the synchronous about:blank commit, to preserve previous
4086 // behavior where trying to reload when the main frame is on the initial empty
4087 // document won't result in a navigation.
4088 // See also https://crbug.com/1277414.
4089 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:324090
clamyea99ea12018-05-28 13:54:234091 Referrer dest_referrer = frame_entry->referrer();
clamyea99ea12018-05-28 13:54:234092
Ehsan Karamad44fc72112019-02-26 18:15:474093 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
4094 // Avoid starting any new navigations since this node is now preparing for
4095 // attaching an inner delegate.
4096 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:204097 }
4098
Alex Moshchuk99242832023-05-22 17:21:444099 if (!IsValidURLForNavigation(frame_tree_node, entry->GetVirtualURL(),
4100 dest_url)) {
clamyea99ea12018-05-28 13:54:234101 return nullptr;
4102 }
4103
clamyea99ea12018-05-28 13:54:234104 // This will be used to set the Navigation Timing API navigationStart
4105 // parameter for browser navigations in new tabs (intents, tabs opened through
4106 // "Open link in new tab"). If the navigation must wait on the current
4107 // RenderFrameHost to execute its BeforeUnload event, the navigation start
4108 // will be updated when the BeforeUnload ack is received.
Mike Jacksone2aa7af2023-05-17 06:45:074109
clamyea99ea12018-05-28 13:54:234110 base::TimeTicks navigation_start = base::TimeTicks::Now();
Mike Jacksone2aa7af2023-05-17 06:45:074111 const auto navigation_start_system_entropy =
4112 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4113 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
clamyea99ea12018-05-28 13:54:234114
danakjd83d706d2020-11-25 22:11:124115 // Look for a pending commit that is to another document in this
4116 // FrameTreeNode. If one exists, then the last committed URL will not be the
4117 // current URL by the time this navigation commits.
4118 bool has_pending_cross_document_commit =
4119 frame_tree_node->render_manager()
4120 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:494121 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:214122 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:124123
Minggang Wangb9f3fa92021-07-01 15:30:314124 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:124125 /*old_url=*/frame_tree_node->current_url(),
4126 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:494127 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:494128 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:134129 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:494130 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:424131
4132 // A form submission may happen here if the navigation is a
4133 // back/forward/reload navigation that does a form resubmission.
4134 scoped_refptr<network::ResourceRequestBody> request_body;
4135 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:504136 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
4137 // entry. This way, it could be directly retrieved here. Right now, it is only
4138 // partially recovered when request.method == "POST" and request.body exists.
4139 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:424140 if (frame_entry->method() == "POST") {
4141 request_body = frame_entry->GetPostData(&post_content_type);
4142 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:304143 post_content_type = std::string(
4144 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:504145 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:424146 }
4147
4148 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:314149 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514150 entry->ConstructCommonNavigationParams(
4151 *frame_entry, request_body, dest_url,
4152 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:384153 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:534154 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:514155 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:554156 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:424157
4158 // TODO(clamy): |intended_as_new_entry| below should always be false once
4159 // Reload no longer leads to this being called for a pending NavigationEntry
4160 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:314161 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:144162 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:404163 *frame_entry, common_params->url, common_params->method,
4164 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:144165 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:534166 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:484167 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:134168 frame_tree_node->AncestorOrSelfHasCSPEE(),
Mike Jacksone2aa7af2023-05-17 06:45:074169 navigation_start_system_entropy, soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:144170 commit_params->post_content_type = post_content_type;
Mike Jacksone2aa7af2023-05-17 06:45:074171 commit_params->navigation_timing->system_entropy_at_navigation_start =
4172 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4173 frame_tree_node, blink::mojom::SystemEntropy::kNormal);
Camille Lamy5193caa2018-10-12 11:59:424174
W. James MacLeanb7d6092682022-10-05 15:23:264175 if (common_params->url.IsAboutSrcdoc()) {
4176 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
4177 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:594178 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:264179 }
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334180 const bool is_browser_initiated = !initiator_frame_token;
Alex Moshchuk9321e6a2022-12-07 21:58:314181 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:144182 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434183 is_browser_initiated, false /* was_opener_suppressed */,
Hiroshige Hayashizaki5466bfe82023-05-17 00:34:334184 initiator_frame_token, initiator_process_id, entry->extra_headers(),
4185 frame_entry, entry, is_form_submission, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374186 std::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294187 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4188 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474189 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234190}
4191
[email protected]d202a7c2012-01-04 07:53:474192void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214193 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274194 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404195
Takashi Toyoshimaea534ef22021-07-21 03:27:594196 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404197 // location bar will have up-to-date information about the security style
4198 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134199 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404200
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374201 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574202 delegate_->NotifyNavigationEntryCommitted(*details);
initial.commit09911bf2008-07-26 23:55:294203}
4204
initial.commit09911bf2008-07-26 23:55:294205// static
[email protected]d202a7c2012-01-04 07:53:474206size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234207 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154208 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214209 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234210}
4211
[email protected]d202a7c2012-01-04 07:53:474212void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224213 if (is_active && needs_reload_)
4214 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294215}
4216
[email protected]d202a7c2012-01-04 07:53:474217void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034218 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4219 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294220 if (!needs_reload_)
4221 return;
4222
Bo Liucdfa4b12018-11-06 00:21:444223 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4224 needs_reload_type_);
4225
initial.commit09911bf2008-07-26 23:55:294226 // Calling Reload() results in ignoring state, and not loading.
4227 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4228 // cached state.
avicc872d7242015-08-19 21:26:344229 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134230 NavigateToExistingPendingEntry(
4231 ReloadType::NONE,
4232 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374233 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134234 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454235 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434236 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274237 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344238 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134239 NavigateToExistingPendingEntry(
4240 ReloadType::NONE,
4241 /*initiator_rfh=*/nullptr,
Arthur Sonzognic686e8f2024-01-11 08:36:374242 /*soft_navigation_heuristics_task_id=*/std::nullopt,
Yoav Weiss8c573952022-11-17 17:35:134243 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344244 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434245 // We should never navigate to an existing initial NavigationEntry that is
4246 // the initial NavigationEntry for the initial empty document that hasn't
4247 // been overridden by the synchronous about:blank commit, to preserve
4248 // legacy behavior where trying to reload when the main frame is on the
4249 // initial empty document won't result in a navigation. See also
4250 // https://crbug.com/1277414. If there is something to reload, the
4251 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4252 // it here.
avicc872d7242015-08-19 21:26:344253 needs_reload_ = false;
4254 }
initial.commit09911bf2008-07-26 23:55:294255}
4256
Kevin McNeeccca6172021-10-19 17:11:144257base::WeakPtr<NavigationHandle>
4258NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364259 RenderFrameHost* render_frame_host,
4260 const GURL& url,
Lei Zhanga4770832023-07-19 18:02:364261 const std::string& error_page_html) {
Rakina Zata Amni919b7922020-12-11 09:03:134262 RenderFrameHostImpl* rfhi =
4263 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584264
4265 // Only active documents can load post-commit error pages:
4266 // - If the document is in pending deletion, the browser already committed to
4267 // destroying this RenderFrameHost so ignore loading the error page.
4268 // - If the document is in back-forward cache, it's not allowed to navigate as
4269 // it should remain frozen. Ignore the request and evict the document from
4270 // back-forward cache.
4271 // - If the document is prerendering, it can navigate but when loading error
4272 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114273 if (rfhi->IsInactiveAndDisallowActivation(
4274 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144275 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114276 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584277
Rakina Zata Amni919b7922020-12-11 09:03:134278 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414279
Minggang Wangb9f3fa92021-07-01 15:30:314280 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434281 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594282 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4283 // the frame actually committed (e.g. iframe with "src" set to a
4284 // slow-responding URL). We should rewrite the URL to about:blank in this
4285 // case, as the renderer will only think a page is an error page if it has a
4286 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134287 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314288 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434289 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334290 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414291
Mike Jacksone2aa7af2023-05-17 06:45:074292 commit_params->navigation_timing->system_entropy_at_navigation_start =
4293 SystemEntropyUtils::ComputeSystemEntropyForFrameTreeNode(
4294 node, blink::mojom::SystemEntropy::kNormal);
4295
arthursonzogni70ac7302020-05-28 08:49:054296 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4297 // error pages.
Liam Brady34639ec92023-10-13 19:50:454298 commit_params->frame_policy = node->pending_frame_policy();
arthursonzogni70ac7302020-05-28 08:49:054299
John Delaney131ad362019-08-08 21:57:414300 std::unique_ptr<NavigationRequest> navigation_request =
4301 NavigationRequest::CreateBrowserInitiated(
4302 node, std::move(common_params), std::move(commit_params),
Hiroshige Hayashizakif07ad7812023-05-10 02:26:094303 false /* was_opener_suppressed */, "" /* extra_headers */,
4304 nullptr /* frame_entry */, nullptr /* entry */,
4305 false /* is_form_submission */, nullptr /* navigation_ui_data */,
Arthur Sonzognic686e8f2024-01-11 08:36:374306 std::nullopt /* impression */, false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364307 navigation_request->set_post_commit_error_page_html(error_page_html);
Lei Zhanga4770832023-07-19 18:02:364308 navigation_request->set_net_error(net::ERR_BLOCKED_BY_CLIENT);
Charlie Reis09952ee2022-12-08 16:35:074309 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414310 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144311
4312 // Calling BeginNavigation may destroy the NavigationRequest.
4313 base::WeakPtr<NavigationRequest> created_navigation_request(
4314 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414315 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144316 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414317}
4318
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574319void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214320 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094321 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154322 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144323 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294324}
4325
[email protected]d202a7c2012-01-04 07:53:474326void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364327 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474328 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4329 // represent a no-committed-entry state.
4330 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364331 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474332 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4333 // if `entries_` contains pre-existing entries from the NavigationController
4334 // before restore, which would not be removed and will be at the front of the
4335 // entries list, causing the index to be off by the amount of pre-existing
4336 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294337 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294338}
[email protected]765b35502008-08-21 00:51:204339
arthursonzogni69a6a1b2019-09-17 09:23:004340void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004341 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4342}
4343
4344void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4345 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474346 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104347 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4348 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294349 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474350 return;
Michael Thiessenc5676d22019-09-25 22:32:104351 }
avi45a72532015-04-07 21:01:454352 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314353
4354 if (!delegate_)
4355 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374356 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484357}
4358
avi7c6f35e2015-05-08 17:52:384359int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4360 int nav_entry_id) const {
4361 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4362 if (entries_[i]->GetUniqueID() == nav_entry_id)
4363 return i;
4364 }
4365 return -1;
4366}
4367
[email protected]d202a7c2012-01-04 07:53:474368void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574369 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254370 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574371 DCHECK_LE(max_index, source->GetEntryCount());
Kevin McNee433daf242023-10-31 20:15:594372 NavigationEntryRestoreContextImpl context;
[email protected]e1cd5452010-08-26 18:03:254373 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374374 // Normally, cloning a NavigationEntryImpl results in sharing
4375 // FrameNavigationEntries between the original and the clone. However, when
4376 // cloning from a different NavigationControllerImpl, we want to fork the
4377 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374378 entries_.insert(entries_.begin() + i,
Kevin McNee433daf242023-10-31 20:15:594379 source->entries_[i]->CloneWithoutSharing(&context));
[email protected]e1cd5452010-08-26 18:03:254380 }
Rakina Zata Amnie2d31312022-11-18 03:38:454381 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274382 DCHECK(pending_entry_index_ == -1 ||
4383 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254384}
[email protected]c5b88d82012-10-06 17:03:334385
4386void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184387 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334388 get_timestamp_callback_ = get_timestamp_callback;
4389}
[email protected]8ff00d72012-10-23 19:12:214390
Shivani Sharmaffb32b82019-04-09 16:58:474391// History manipulation intervention:
4392void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474393 bool replace_entry,
Shivani Sharmaeef521b2024-01-18 13:03:564394 bool previous_document_had_history_intervention_activation,
Alexander Timine3ec4192020-04-20 16:39:404395 bool is_renderer_initiated,
4396 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharmaeef521b2024-01-18 13:03:564397 // Note that for a subframe,
4398 // previous_document_had_history_intervention_activation is true if the
Shivani Sharma712d5d72019-04-16 21:56:454399 // gesture happened in any subframe (propagated to main frame) or in the main
4400 // frame itself.
Shivani Sharmaeef521b2024-01-18 13:03:564401 if (replace_entry || previous_document_had_history_intervention_activation ||
shivanigithubcceeacf2020-03-06 20:00:274402 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474403 return;
4404 }
4405 if (last_committed_entry_index_ == -1)
4406 return;
4407
Shivani Sharmac4cc8922019-04-18 03:11:174408 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474409
Alexander Timine3ec4192020-04-20 16:39:404410 // Log UKM with the URL we are navigating away from.
4411 ukm::builders::HistoryManipulationIntervention(
4412 previous_page_load_ukm_source_id)
4413 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474414}
4415
Shivani Sharmac4cc8922019-04-18 03:11:174416void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4417 int reference_index,
4418 bool skippable) {
4419 auto* reference_entry = GetEntryAtIndex(reference_index);
4420 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4421
4422 int64_t document_sequence_number =
4423 reference_entry->root_node()->frame_entry->document_sequence_number();
4424 for (int index = 0; index < GetEntryCount(); index++) {
4425 auto* entry = GetEntryAtIndex(index);
4426 if (entry->root_node()->frame_entry->document_sequence_number() ==
4427 document_sequence_number) {
4428 entry->set_should_skip_on_back_forward_ui(skippable);
4429 }
4430 }
4431}
4432
arthursonzogni66f711c2019-10-08 14:40:364433std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4434NavigationControllerImpl::ReferencePendingEntry() {
4435 DCHECK(pending_entry_);
4436 auto pending_entry_ref =
4437 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4438 pending_entry_refs_.insert(pending_entry_ref.get());
4439 return pending_entry_ref;
4440}
4441
4442void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4443 // Ignore refs that don't correspond to the current pending entry.
4444 auto it = pending_entry_refs_.find(ref);
4445 if (it == pending_entry_refs_.end())
4446 return;
4447 pending_entry_refs_.erase(it);
4448
4449 if (!pending_entry_refs_.empty())
4450 return;
4451
4452 // The pending entry may be deleted before the last PendingEntryRef.
4453 if (!pending_entry_)
4454 return;
4455
4456 // We usually clear the pending entry when the matching NavigationRequest
4457 // fails, so that an arbitrary URL isn't left visible above a committed page.
4458 //
4459 // However, we do preserve the pending entry in some cases, such as on the
4460 // initial navigation of an unmodified blank tab. We also allow the delegate
4461 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4462 // user edit the URL and try again. This may be useful in cases that the
4463 // committed page cannot be attacker-controlled. In these cases, we still
4464 // allow the view to clear the pending entry and typed URL if the user
4465 // requests (e.g., hitting Escape with focus in the address bar).
4466 //
4467 // Do not leave the pending entry visible if it has an invalid URL, since this
4468 // might be formatted in an unexpected or unsafe way.
4469 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364470 bool should_preserve_entry =
4471 (pending_entry_ == GetVisibleEntry()) &&
4472 pending_entry_->GetURL().is_valid() &&
4473 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4474 if (should_preserve_entry)
4475 return;
4476
4477 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374478 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364479}
4480
Titouan Rigoudy6ec70402021-02-02 15:42:194481std::unique_ptr<PolicyContainerPolicies>
4482NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394483 RenderFrameHostImpl* rfh,
4484 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174485 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394486 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454487 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394488 FrameNavigationEntry* previous_frame_entry =
4489 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4490
4491 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4492 // ensure we always have a FrameNavigationEntry here.
4493 if (!previous_frame_entry)
4494 return nullptr;
4495
Titouan Rigoudy6ec70402021-02-02 15:42:194496 const PolicyContainerPolicies* previous_policies =
4497 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394498
Titouan Rigoudy6ec70402021-02-02 15:42:194499 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394500 return nullptr;
4501
4502 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234503 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394504 }
4505
Titouan Rigoudy72f892d2022-05-02 18:21:234506 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394507}
4508
Hayato Ito2c8c08d02021-06-23 03:38:434509void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504510 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434511 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4512 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4513 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504514
4515 auto callback = base::BindRepeating(
4516 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4517 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4518 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4519 }
4520 },
Hayato Ito2c8c08d02021-06-23 03:38:434521 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034522 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504523}
4524
4525void NavigationControllerImpl::DidAccessInitialMainDocument() {
4526 // We may have left a failed browser-initiated navigation in the address bar
4527 // to let the user edit it and try again. Clear it now that content might
4528 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034529 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504530 DiscardPendingEntry(false);
4531
4532 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374533 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504534}
4535
4536void NavigationControllerImpl::UpdateStateForFrame(
4537 RenderFrameHostImpl* rfhi,
4538 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564539 OPTIONAL_TRACE_EVENT1("content",
4540 "NavigationControllerImpl::UpdateStateForFrame",
4541 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504542 // The state update affects the last NavigationEntry associated with the given
4543 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4544 // in the case of an UpdateState from a frame being swapped out). We track
4545 // which entry this is in the RenderFrameHost's nav_entry_id.
4546 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4547 if (!entry)
4548 return;
4549
4550 FrameNavigationEntry* frame_entry =
4551 entry->GetFrameEntry(rfhi->frame_tree_node());
4552 if (!frame_entry)
4553 return;
4554
4555 // The SiteInstance might not match if we do a cross-process navigation with
4556 // replacement (e.g., auto-subframe), in which case the swap out of the old
4557 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4558 // has already been replaced and destroyed.
4559 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4560 return;
4561
4562 if (page_state == frame_entry->page_state())
4563 return; // Nothing to update.
4564
4565 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4566
4567 // The document_sequence_number and item_sequence_number recorded in the
4568 // FrameNavigationEntry should not differ from the one coming with the update,
4569 // since it must come from the same document. Do not update it if a difference
4570 // is detected, as this indicates that |frame_entry| is not the correct one.
4571 blink::ExplodedPageState exploded_state;
4572 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4573 return;
4574
4575 if (exploded_state.top.document_sequence_number !=
4576 frame_entry->document_sequence_number() ||
4577 exploded_state.top.item_sequence_number !=
4578 frame_entry->item_sequence_number()) {
4579 return;
4580 }
4581
4582 frame_entry->SetPageState(page_state);
4583 NotifyEntryChanged(entry);
4584}
4585
Nate Chapina2c881f52023-11-07 17:02:094586namespace {
4587
4588// The caller is responsible for ensuring the entry is same-origin to the
4589// origin to be committed.
4590blink::mojom::NavigationApiHistoryEntryPtr ToNavigationApiHistoryEntry(
4591 FrameNavigationEntry* frame_entry,
4592 int64_t pending_document_sequence_number) {
4593 blink::ExplodedPageState exploded_state;
4594 if (!blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4595 &exploded_state)) {
4596 return nullptr;
4597 }
4598 blink::ExplodedFrameState frame_state = exploded_state.top;
4599
4600 // If the document represented by this FNE hid its full url from appearing in
4601 // a referrer via a "no-referrer" or "origin" referrer policy, censor the url
4602 // in the navigation API as well (unless we're navigating to that document).
4603 std::u16string url;
4604 if (pending_document_sequence_number ==
4605 frame_entry->document_sequence_number() ||
4606 !frame_entry->protect_url_in_navigation_api()) {
4607 url = frame_state.url_string.value_or(std::u16string());
4608 }
4609
4610 return blink::mojom::NavigationApiHistoryEntry::New(
4611 frame_state.navigation_api_key.value_or(std::u16string()),
4612 frame_state.navigation_api_id.value_or(std::u16string()), url,
4613 frame_state.item_sequence_number, frame_state.document_sequence_number,
4614 frame_state.navigation_api_state);
4615}
4616
4617} // namespace
4618
Domenic Denicolacd30f5f82022-03-16 21:48:014619std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4620NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574621 Direction direction,
4622 int entry_index,
4623 const url::Origin& pending_origin,
4624 FrameTreeNode* node,
4625 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304626 int64_t pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094627 int64_t pending_document_sequence_number,
4628 int& last_index_checked) {
Domenic Denicolacd30f5f82022-03-16 21:48:014629 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454630 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174631 // Don't process the initial entry.
4632 DCHECK_EQ(GetEntryCount(), 1);
4633 return entries;
4634 }
Nate Chapind1fe3612021-04-16 20:45:574635 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304636 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574637 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4638 i += offset) {
Nate Chapina2c881f52023-11-07 17:02:094639 last_index_checked = i;
Nate Chapind1fe3612021-04-16 20:45:574640 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414641 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574642 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014643 // An entry should only appear in the navigation API entries if it is for
4644 // the same origin as the document being committed. Check the committed
4645 // origin, or if that is not available (during restore), check against the
4646 // FNE's url.
Nate Chapina2c881f52023-11-07 17:02:094647 // TODO(crbug.com/1209092): Move this into ToNavigationApiHistoryEntry()
4648 // once we can be sure that entries with the same ISN will never be
4649 // cross-origin.
Nate Chapindedfa642022-01-28 23:59:414650 url::Origin frame_entry_origin =
4651 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4652 frame_entry->url(),
4653 frame_entry->initiator_origin().value_or(url::Origin())));
4654 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574655 break;
4656 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4657 continue;
Nate Chapina2c881f52023-11-07 17:02:094658 if (blink::mojom::NavigationApiHistoryEntryPtr entry =
4659 ToNavigationApiHistoryEntry(frame_entry,
4660 pending_document_sequence_number)) {
Nate Chapin63db0d12022-01-20 22:03:304661 DCHECK(entry->url.empty() ||
4662 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574663 entries.push_back(std::move(entry));
4664 previous_item_sequence_number = frame_entry->item_sequence_number();
4665 }
4666 }
4667 // If |entries| was constructed by iterating backwards from
4668 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4669 // earliest-at-the-front. Reverse it.
4670 if (direction == Direction::kBack)
4671 std::reverse(entries.begin(), entries.end());
4672 return entries;
4673}
4674
Domenic Denicolacd30f5f82022-03-16 21:48:014675blink::mojom::NavigationApiHistoryEntryArraysPtr
4676NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554677 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574678 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404679 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444680 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404681 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574682
Nate Chapind1fe3612021-04-16 20:45:574683 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554684 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574685
Nate Chapine82339d02022-05-03 23:48:254686 // NOTE: |entry_index| is the index where this entry will commit if no
4687 // modifications are made between now and DidCommitNavigation. This is used to
4688 // walk |entries_| and determine which entries should be exposed by the
4689 // navigation API. It is important to calculate this correctly, because blink
4690 // will cancel a same-document history commit if it's not present in the
4691 // entries blink knows about.
4692 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574693 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304694 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254695 bool will_create_new_entry = false;
4696 if (GetPendingEntryIndex() != -1) {
4697 entry_index = GetPendingEntryIndex();
4698 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4699 pending_item_sequence_number = frame_entry->item_sequence_number();
4700 pending_document_sequence_number =
4701 frame_entry->document_sequence_number();
4702 }
4703 } else if (request &&
4704 !NavigationTypeUtils::IsReload(
4705 request->common_params().navigation_type) &&
4706 !NavigationTypeUtils::IsHistory(
4707 request->common_params().navigation_type) &&
4708 !request->common_params().should_replace_current_entry &&
4709 !request->common_params()
4710 .is_history_navigation_in_new_child_frame) {
4711 will_create_new_entry = true;
4712 entry_index = GetLastCommittedEntryIndex() + 1;
4713 // Don't set pending_item_sequence_number or
4714 // pending_document_sequence_number in this case - a new unique isn/dsn will
4715 // be calculated in the renderer later.
4716 } else if (GetLastCommittedEntryIndex() != -1) {
4717 entry_index = GetLastCommittedEntryIndex();
4718 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574719 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304720 pending_document_sequence_number =
4721 frame_entry->document_sequence_number();
4722 }
Nate Chapind1fe3612021-04-16 20:45:574723 }
4724
Domenic Denicolacd30f5f82022-03-16 21:48:014725 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254726 if (entry_index == -1) {
4727 // TODO(rakina): Exit early when there is no last committed entry.
4728 // Remove when InitialNavigationEntry ships.
4729 return entry_arrays;
4730 }
4731
Nate Chapina2c881f52023-11-07 17:02:094732 int backmost_index = entry_index;
Domenic Denicolacd30f5f82022-03-16 21:48:014733 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574734 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapina2c881f52023-11-07 17:02:094735 pending_item_sequence_number, pending_document_sequence_number,
4736 backmost_index);
Nate Chapind1fe3612021-04-16 20:45:574737
4738 // Don't populate forward entries if they will be truncated by a new entry.
Nate Chapina2c881f52023-11-07 17:02:094739 int forwardmost_index = entry_index;
Nate Chapind1fe3612021-04-16 20:45:574740 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014741 entry_arrays->forward_entries =
4742 PopulateSingleNavigationApiHistoryEntryVector(
4743 Direction::kForward, entry_index, pending_origin, node,
4744 site_instance.get(), pending_item_sequence_number,
Nate Chapina2c881f52023-11-07 17:02:094745 pending_document_sequence_number, forwardmost_index);
4746 }
4747
4748 // If the previous entry is within the block of contiguous entries being
4749 // provided, then report it as the `previous_entry`.
Nate Chapinc06cf80a2023-11-18 01:12:254750 FrameNavigationEntry* previous_entry = nullptr;
4751 if (frame_tree_->is_prerendering()) {
4752 int initiator_id = PrerenderHost::GetFromFrameTreeNode(*node)
4753 .initiator_frame_tree_node_id();
4754 if (initiator_id != RenderFrameHost::kNoFrameTreeNodeId) {
4755 auto* initiator_node = FrameTreeNode::GloballyFindByID(initiator_id);
4756 previous_entry = initiator_node->frame_tree()
4757 .controller()
4758 .GetLastCommittedEntry()
4759 ->GetFrameEntry(initiator_node);
4760 }
4761 } else if (GetLastCommittedEntryIndex() != -1 &&
4762 GetLastCommittedEntryIndex() >= backmost_index &&
4763 GetLastCommittedEntryIndex() <= forwardmost_index) {
4764 previous_entry = GetLastCommittedEntry()->GetFrameEntry(node);
4765 }
4766 if (previous_entry) {
4767 url::Origin previous_entry_origin =
4768 previous_entry->committed_origin().value_or(url::Origin::Resolve(
4769 previous_entry->url(),
4770 previous_entry->initiator_origin().value_or(url::Origin())));
4771 // TODO(crbug.com/1209092): Move this into ToNavigationApiHistoryEntry()
4772 // once we can be sure that entries with the same ISN will never be
4773 // cross-origin.
4774 if (pending_origin.IsSameOriginWith(previous_entry_origin)) {
4775 entry_arrays->previous_entry = ToNavigationApiHistoryEntry(
4776 previous_entry, pending_document_sequence_number);
Nate Chapina2c881f52023-11-07 17:02:094777 }
Nate Chapind1fe3612021-04-16 20:45:574778 }
Nate Chapinc06cf80a2023-11-18 01:12:254779
Nate Chapin4e657a472022-02-06 03:38:374780 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574781}
4782
Nate Chapinfbfe5af2021-06-10 17:22:084783NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574784NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084785 FrameNavigationEntry* current_entry,
4786 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574787 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084788 if (!target_entry || !target_entry->committed_origin())
4789 return HistoryNavigationAction::kStopLooking;
Nate Chapinfbfe5af2021-06-10 17:22:084790 if (!current_entry->committed_origin()->IsSameOriginWith(
4791 *target_entry->committed_origin())) {
4792 return HistoryNavigationAction::kStopLooking;
4793 }
4794
4795 // NOTE: We don't actually care between kSameDocument and
4796 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574797 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084798 return HistoryNavigationAction::kDifferentDocument;
4799 return HistoryNavigationAction::kKeepLooking;
4800}
4801
Domenic Denicolacc094fb2022-03-16 23:40:574802void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204803 RenderFrameHostImpl* initiator_rfh,
Arthur Sonzognic686e8f2024-01-11 08:36:374804 std::optional<blink::scheduler::TaskAttributionId>
Yoav Weissa7449c3b2022-11-22 15:15:144805 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574806 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204807 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084808 FrameNavigationEntry* current_entry =
4809 GetLastCommittedEntry()->GetFrameEntry(node);
4810 if (!current_entry)
4811 return;
4812
Yoav Weiss8c573952022-11-17 17:35:134813 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4814 // when `navigation.traverseTo()` is called.
4815
Nate Chapinfbfe5af2021-06-10 17:22:084816 // We want to find the nearest matching entry that is contiguously
4817 // same-instance and same-origin. Check back first, then forward.
4818 // TODO(japhet): Link spec here once it exists.
4819 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574820 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084821 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4822 if (result == HistoryNavigationAction::kStopLooking)
4823 break;
4824 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144825 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084826 return;
4827 }
4828 }
4829 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574830 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084831 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4832 if (result == HistoryNavigationAction::kStopLooking)
4833 break;
4834 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144835 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084836 return;
4837 }
4838 }
Nate Chapinbf682fa32022-09-26 22:41:204839
4840 // If we fall through to here, a matching NavigationEntry couldn't be found.
4841 // Notify the renderer that the navigation was cancelled.
4842 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4843 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084844}
4845
Domenic Denicolacc094fb2022-03-16 23:40:574846bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304847 network::mojom::ReferrerPolicy referrer_policy) {
4848 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4849 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4850}
4851
shivanigithubf405bf0d2021-11-05 17:58:334852bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4853 const FrameTreeNode* frame_tree_node) const {
4854 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4855 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544856 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Takashi Toyoshima4dad2c12023-11-13 10:04:464857 // The preview mode appears as prerendered page in renderers, and
4858 // GetDocument()->IsPrerendering() covers the case together.
Ali Hijazid87307d2022-11-07 20:15:034859 return frame_tree_->is_prerendering() ||
Takashi Toyoshima8dfc05c2024-01-29 21:03:514860 frame_tree_->page_delegate()->IsPageInPreviewMode() ||
shivanigithubf405bf0d2021-11-05 17:58:334861 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544862}
4863
Julie Jeongeun Kim0e242242022-11-30 10:45:094864void NavigationControllerImpl::DidChangeReferrerPolicy(
4865 FrameTreeNode* node,
4866 network::mojom::ReferrerPolicy referrer_policy) {
4867 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4868 if (!entry)
4869 return;
4870
4871 // The FrameNavigationEntry may want to change whether to protect its url
4872 // in the navigation API when the referrer policy changes.
4873 entry->set_protect_url_in_navigation_api(
4874 ShouldProtectUrlInNavigationApi(referrer_policy));
4875}
4876
[email protected]8ff00d72012-10-23 19:12:214877} // namespace content