blob: 0314b2350253ae18e0e730924681b2cf5c354f9d [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"
Carlos Caballeroede6f8c2021-01-28 11:01:5054#include "base/trace_event/trace_conversion_helper.h"
ssid3e765612015-01-28 04:03:4255#include "base/trace_event/trace_event.h"
Daniel Chengabb006862022-09-09 22:39:0856#include "base/types/optional_util.h"
servolkf3955532015-05-16 00:01:5957#include "build/build_config.h"
[email protected]eabfe1912014-05-12 10:07:2858#include "cc/base/switches.h"
jamescookda2505812015-03-20 18:01:1859#include "content/browser/bad_message.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:3960#include "content/browser/blob_storage/chrome_blob_storage_context.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"
danakjc492bf82020-09-09 20:02:4464#include "content/browser/renderer_host/debug_urls.h"
65#include "content/browser/renderer_host/frame_tree.h"
Carlos Caballero40b0efd2021-01-26 11:55:0066#include "content/browser/renderer_host/frame_tree_node.h"
Chris Bookholt27faf8d2022-01-20 01:03:3367#include "content/browser/renderer_host/navigation_controller_delegate.h"
danakjc492bf82020-09-09 20:02:4468#include "content/browser/renderer_host/navigation_entry_impl.h"
Nate Chapin214a86a2021-06-21 20:35:5769#include "content/browser/renderer_host/navigation_entry_restore_context_impl.h"
danakjc492bf82020-09-09 20:02:4470#include "content/browser/renderer_host/navigation_request.h"
71#include "content/browser/renderer_host/navigator.h"
72#include "content/browser/renderer_host/render_frame_host_delegate.h"
Carlos Caballero40b0efd2021-01-26 11:55:0073#include "content/browser/renderer_host/render_view_host_impl.h"
Sharon Yangd70a5392021-10-26 23:06:3274#include "content/browser/site_info.h"
[email protected]b6583592012-01-25 19:52:3375#include "content/browser/site_instance_impl.h"
Kunihiko Sakamoto346a74e2021-03-10 08:57:4876#include "content/browser/web_package/subresource_web_bundle_navigation_info.h"
Tsuyoshi Horo37493af2019-11-21 23:43:1477#include "content/browser/web_package/web_bundle_navigation_info.h"
Camille Lamy5193caa2018-10-12 11:59:4278#include "content/common/content_constants_internal.h"
Nate Chapind1fe3612021-04-16 20:45:5779#include "content/common/navigation_params_utils.h"
Nasko Oskovae49e292020-08-13 02:08:5180#include "content/common/trace_utils.h"
[email protected]ccb797302011-12-15 16:55:1181#include "content/public/browser/browser_context.h"
[email protected]d1198fd2012-08-13 22:50:1982#include "content/public/browser/content_browser_client.h"
Fergal Daly1336ac642021-09-14 15:13:1183#include "content/public/browser/disallow_activation_reason.h"
[email protected]d9083482012-01-06 00:38:4684#include "content/public/browser/invalidate_type.h"
[email protected]5b96836f2011-12-22 07:39:0085#include "content/public/browser/navigation_details.h"
[email protected]7f6f44c2011-12-14 13:23:3886#include "content/public/browser/notification_service.h"
[email protected]0d6e9bd2011-10-18 04:29:1687#include "content/public/browser/notification_types.h"
Lei Zhang96031532019-10-10 19:05:4788#include "content/public/browser/render_view_host.h"
[email protected]9677a3c2012-12-22 04:18:5889#include "content/public/browser/render_widget_host.h"
90#include "content/public/browser/render_widget_host_view.h"
Mikel Astizba9cf2fd2017-12-17 10:38:1091#include "content/public/browser/replaced_navigation_entry_data.h"
[email protected]4c3a23582012-08-18 08:54:3492#include "content/public/browser/storage_partition.h"
[email protected]d1198fd2012-08-13 22:50:1993#include "content/public/common/content_client.h"
[email protected]7f6f44c2011-12-14 13:23:3894#include "content/public/common/content_constants.h"
toyoshim86e34ec2016-02-25 08:56:1095#include "content/public/common/content_features.h"
Lei Zhang96031532019-10-10 19:05:4796#include "content/public/common/url_constants.h"
clamy7fced7b2017-11-16 19:52:4397#include "content/public/common/url_utils.h"
servolkf3955532015-05-16 00:01:5998#include "media/base/mime_util.h"
Arthur Sonzogni620cec62018-12-13 13:08:5799#include "net/http/http_status_code.h"
Shivani Sharma93329102019-01-24 19:44:18100#include "services/metrics/public/cpp/ukm_builders.h"
101#include "services/metrics/public/cpp/ukm_recorder.h"
Yue Ru Sun128804932020-09-30 22:19:17102#include "services/metrics/public/cpp/ukm_source_id.h"
Nan Lind91c8152021-10-21 16:22:37103#include "services/network/public/mojom/fetch_api.mojom.h"
William Liu2c825472022-10-31 12:01:44104#include "services/network/public/mojom/url_response_head.mojom-shared.h"
[email protected]9677a3c2012-12-22 04:18:58105#include "skia/ext/platform_canvas.h"
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:39106#include "third_party/blink/public/common/blob/blob_utils.h"
Gyuyoung Kim107c2a02021-04-13 01:49:30107#include "third_party/blink/public/common/chrome_debug_urls.h"
Miyoung Shin1c565c912021-03-17 12:11:21108#include "third_party/blink/public/common/history/session_history_constants.h"
Blink Reformata30d4232018-04-07 15:31:06109#include "third_party/blink/public/common/mime_util/mime_util.h"
Minggang Wanga13c796e2021-07-02 05:54:43110#include "third_party/blink/public/common/navigation/navigation_params.h"
Carlos Caballeroede6f8c2021-01-28 11:01:50111#include "third_party/blink/public/common/page_state/page_state_serialization.h"
Minggang Wangb9f3fa92021-07-01 15:30:31112#include "third_party/blink/public/mojom/navigation/navigation_params.mojom.h"
Minggang Wang7ee0c742021-06-16 16:16:51113#include "third_party/blink/public/mojom/navigation/prefetched_signed_exchange_info.mojom.h"
sbinglera07ae732022-12-02 20:49:05114#include "third_party/blink/public/mojom/runtime_feature_state/runtime_feature_state.mojom.h"
[email protected]cca6f392014-05-28 21:32:26115#include "url/url_constants.h"
initial.commit09911bf2008-07-26 23:55:29116
[email protected]8ff00d72012-10-23 19:12:21117namespace content {
[email protected]e9ba4472008-09-14 15:42:43118namespace {
119
120// Invoked when entries have been pruned, or removed. For example, if the
121// current entries are [google, digg, yahoo], with the current entry google,
122// and the user types in cnet, then digg and yahoo are pruned.
[email protected]d202a7c2012-01-04 07:53:47123void NotifyPrunedEntries(NavigationControllerImpl* nav_controller,
Shivani Sharmab9c46de82019-02-08 16:54:50124 int index,
[email protected]c12bf1a12008-09-17 16:28:49125 int count) {
[email protected]8ff00d72012-10-23 19:12:21126 PrunedDetails details;
Shivani Sharmab9c46de82019-02-08 16:54:50127 details.index = index;
[email protected]c12bf1a12008-09-17 16:28:49128 details.count = count;
Sam McNally5c087a32017-08-25 01:46:14129 nav_controller->delegate()->NotifyNavigationListPruned(details);
[email protected]e9ba4472008-09-14 15:42:43130}
131
[email protected]e9ba4472008-09-14 15:42:43132// Configure all the NavigationEntries in entries for restore. This resets
133// the transition type to reload and makes sure the content state isn't empty.
134void ConfigureEntriesForRestore(
dcheng9bfa5162016-04-09 01:00:57135 std::vector<std::unique_ptr<NavigationEntryImpl>>* entries,
toyoshim0df1d3a2016-09-09 09:52:48136 RestoreType type) {
Lei Zhang96031532019-10-10 19:05:47137 for (auto& entry : *entries) {
[email protected]e9ba4472008-09-14 15:42:43138 // Use a transition type of reload so that we don't incorrectly increase
139 // the typed count.
Lei Zhang96031532019-10-10 19:05:47140 entry->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
141 entry->set_restore_type(type);
[email protected]e9ba4472008-09-14 15:42:43142 }
143}
144
[email protected]bf70edce2012-06-20 22:32:22145// Determines whether or not we should be carrying over a user agent override
146// between two NavigationEntries.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57147bool ShouldKeepOverride(NavigationEntry* last_entry) {
[email protected]bf70edce2012-06-20 22:32:22148 return last_entry && last_entry->GetIsOverridingUserAgent();
149}
150
Camille Lamy5193caa2018-10-12 11:59:42151// Determines whether to override user agent for a navigation.
152bool ShouldOverrideUserAgent(
153 NavigationController::UserAgentOverrideOption override_user_agent,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57154 NavigationEntry* last_committed_entry) {
Camille Lamy5193caa2018-10-12 11:59:42155 switch (override_user_agent) {
156 case NavigationController::UA_OVERRIDE_INHERIT:
157 return ShouldKeepOverride(last_committed_entry);
158 case NavigationController::UA_OVERRIDE_TRUE:
159 return true;
160 case NavigationController::UA_OVERRIDE_FALSE:
161 return false;
Camille Lamy5193caa2018-10-12 11:59:42162 }
163 NOTREACHED();
164 return false;
165}
166
Rakina Zata Amni312822d72021-06-04 16:13:37167// Returns true if this navigation should be treated as a reload. For e.g.
clamy0a656e42018-02-06 18:18:28168// navigating to the last committed url via the address bar or clicking on a
Rakina Zata Amni312822d72021-06-04 16:13:37169// link which results in a navigation to the last committed URL (but wasn't
170// converted to do a replacement navigation in the renderer), etc.
Fergal Daly766177d2020-07-07 07:54:04171// |node| is the FrameTreeNode which is navigating. |url|, |virtual_url|,
172// |base_url_for_data_url|, |transition_type| correspond to the new navigation
173// (i.e. the pending NavigationEntry). |last_committed_entry| is the last
174// navigation that committed.
175bool ShouldTreatNavigationAsReload(FrameTreeNode* node,
176 const GURL& url,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57177 const GURL& virtual_url,
178 const GURL& base_url_for_data_url,
179 ui::PageTransition transition_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57180 bool is_post,
Rakina Zata Amni312822d72021-06-04 16:13:37181 bool should_replace_current_entry,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57182 NavigationEntryImpl* last_committed_entry) {
Rakina Zata Amni312822d72021-06-04 16:13:37183 // Navigations intended to do a replacement shouldn't be converted to do a
184 // reload.
185 if (should_replace_current_entry)
clamy0a656e42018-02-06 18:18:28186 return false;
clamy0a656e42018-02-06 18:18:28187 // Only convert to reload if at least one navigation committed.
Rakina Zata Amnie2d31312022-11-18 03:38:45188 if (last_committed_entry->IsInitialEntry())
ananta3bdd8ae2016-12-22 17:11:55189 return false;
190
arthursonzogni7a8243682017-12-14 16:41:42191 // Skip navigations initiated by external applications.
clamy0a656e42018-02-06 18:18:28192 if (transition_type & ui::PAGE_TRANSITION_FROM_API)
arthursonzogni7a8243682017-12-14 16:41:42193 return false;
194
ananta3bdd8ae2016-12-22 17:11:55195 // We treat (PAGE_TRANSITION_RELOAD | PAGE_TRANSITION_FROM_ADDRESS_BAR),
196 // PAGE_TRANSITION_TYPED or PAGE_TRANSITION_LINK transitions as navigations
197 // which should be treated as reloads.
clamy0a656e42018-02-06 18:18:28198 bool transition_type_can_be_converted = false;
199 if (ui::PageTransitionCoreTypeIs(transition_type,
200 ui::PAGE_TRANSITION_RELOAD) &&
201 (transition_type & ui::PAGE_TRANSITION_FROM_ADDRESS_BAR)) {
202 transition_type_can_be_converted = true;
ananta3bdd8ae2016-12-22 17:11:55203 }
clamy0a656e42018-02-06 18:18:28204 if (ui::PageTransitionCoreTypeIs(transition_type,
ananta3bdd8ae2016-12-22 17:11:55205 ui::PAGE_TRANSITION_TYPED)) {
clamy0a656e42018-02-06 18:18:28206 transition_type_can_be_converted = true;
207 }
208 if (ui::PageTransitionCoreTypeIs(transition_type, ui::PAGE_TRANSITION_LINK))
209 transition_type_can_be_converted = true;
210 if (!transition_type_can_be_converted)
211 return false;
212
213 // This check is required for cases like view-source:, etc. Here the URL of
214 // the navigation entry would contain the url of the page, while the virtual
215 // URL contains the full URL including the view-source prefix.
216 if (virtual_url != last_committed_entry->GetVirtualURL())
217 return false;
218
Fergal Daly766177d2020-07-07 07:54:04219 // Check that the URLs match.
220 FrameNavigationEntry* frame_entry = last_committed_entry->GetFrameEntry(node);
221 // If there's no frame entry then by definition the URLs don't match.
222 if (!frame_entry)
223 return false;
224
225 if (url != frame_entry->url())
clamy0a656e42018-02-06 18:18:28226 return false;
227
228 // This check is required for Android WebView loadDataWithBaseURL. Apps
229 // can pass in anything in the base URL and we need to ensure that these
230 // match before classifying it as a reload.
231 if (url.SchemeIs(url::kDataScheme) && base_url_for_data_url.is_valid()) {
232 if (base_url_for_data_url != last_committed_entry->GetBaseURLForDataURL())
233 return false;
ananta3bdd8ae2016-12-22 17:11:55234 }
235
clamy0a656e42018-02-06 18:18:28236 // Skip entries with SSL errors.
237 if (last_committed_entry->ssl_error())
238 return false;
239
240 // Don't convert to a reload when the last navigation was a POST or the new
241 // navigation is a POST.
Fergal Daly766177d2020-07-07 07:54:04242 if (frame_entry->get_has_post_data() || is_post)
clamy0a656e42018-02-06 18:18:28243 return false;
244
245 return true;
ananta3bdd8ae2016-12-22 17:11:55246}
247
Anton Bikineevf62d1bf2021-05-15 17:56:07248absl::optional<url::Origin> GetCommittedOriginForFrameEntry(
Rakina Zata Amni3a1c0ec2021-04-15 03:35:12249 const mojom::DidCommitProvisionalLoadParams& params,
250 NavigationRequest* request) {
Nasko Oskov03912102019-01-11 00:21:32251 // Error pages commit in an opaque origin, yet have the real URL that resulted
252 // in an error as the |params.url|. Since successful reload of an error page
253 // should commit in the correct origin, setting the opaque origin on the
254 // FrameNavigationEntry will be incorrect.
Rakina Zata Amniafd3c6582021-11-30 06:19:17255 if (request && request->DidEncounterError())
Anton Bikineevf62d1bf2021-05-15 17:56:07256 return absl::nullopt;
Nasko Oskov03912102019-01-11 00:21:32257
Anton Bikineevf62d1bf2021-05-15 17:56:07258 return absl::make_optional(params.origin);
Nasko Oskov03912102019-01-11 00:21:32259}
260
Camille Lamy5193caa2018-10-12 11:59:42261bool IsValidURLForNavigation(bool is_main_frame,
262 const GURL& virtual_url,
263 const GURL& dest_url) {
264 // Don't attempt to navigate if the virtual URL is non-empty and invalid.
265 if (is_main_frame && !virtual_url.is_valid() && !virtual_url.is_empty()) {
266 LOG(WARNING) << "Refusing to load for invalid virtual URL: "
267 << virtual_url.possibly_invalid_spec();
268 return false;
269 }
270
271 // Don't attempt to navigate to non-empty invalid URLs.
272 if (!dest_url.is_valid() && !dest_url.is_empty()) {
273 LOG(WARNING) << "Refusing to load invalid URL: "
274 << dest_url.possibly_invalid_spec();
275 return false;
276 }
277
278 // The renderer will reject IPC messages with URLs longer than
279 // this limit, so don't attempt to navigate with a longer URL.
280 if (dest_url.spec().size() > url::kMaxURLChars) {
281 LOG(WARNING) << "Refusing to load URL as it exceeds " << url::kMaxURLChars
282 << " characters.";
283 return false;
284 }
285
Aaron Colwell33109c592020-04-21 21:31:19286 // Reject renderer debug URLs because they should have been handled before
287 // we get to this point. This check handles renderer debug URLs
288 // that are inside a view-source: URL (e.g. view-source:chrome://kill) and
289 // provides defense-in-depth if a renderer debug URL manages to get here via
290 // some other path. We want to reject the navigation here so it doesn't
291 // violate assumptions in downstream code.
Gyuyoung Kim107c2a02021-04-13 01:49:30292 if (blink::IsRendererDebugURL(dest_url)) {
Aaron Colwell33109c592020-04-21 21:31:19293 LOG(WARNING) << "Refusing to load renderer debug URL: "
294 << dest_url.possibly_invalid_spec();
295 return false;
296 }
297
Camille Lamy5193caa2018-10-12 11:59:42298 return true;
299}
300
Mikel Astizba9cf2fd2017-12-17 10:38:10301// See replaced_navigation_entry_data.h for details: this information is meant
302// to ensure |*output_entry| keeps track of its original URL (landing page in
303// case of server redirects) as it gets replaced (e.g. history.replaceState()),
304// without overwriting it later, for main frames.
305void CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57306 NavigationEntryImpl* replaced_entry,
Mikel Astizba9cf2fd2017-12-17 10:38:10307 NavigationEntryImpl* output_entry) {
Rakina Zata Amniafd3c6582021-11-30 06:19:17308 if (output_entry->GetReplacedEntryData().has_value() ||
309 replaced_entry->IsInitialEntry()) {
Mikel Astizba9cf2fd2017-12-17 10:38:10310 return;
Rakina Zata Amniafd3c6582021-11-30 06:19:17311 }
Mikel Astizba9cf2fd2017-12-17 10:38:10312
313 ReplacedNavigationEntryData data;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57314 data.first_committed_url = replaced_entry->GetURL();
315 data.first_timestamp = replaced_entry->GetTimestamp();
316 data.first_transition_type = replaced_entry->GetTransitionType();
Charlie Reisb55438f2019-01-08 01:54:29317 output_entry->set_replaced_entry_data(data);
Mikel Astizba9cf2fd2017-12-17 10:38:10318}
319
Minggang Wangb9f3fa92021-07-01 15:30:31320blink::mojom::NavigationType GetNavigationType(
321 const GURL& old_url,
322 const GURL& new_url,
323 ReloadType reload_type,
324 NavigationEntryImpl* entry,
325 const FrameNavigationEntry& frame_entry,
326 bool has_pending_cross_document_commit,
327 bool is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:49328 bool is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:13329 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzer405f3402022-07-21 20:12:49330 bool is_unfenced_top_navigation) {
clamyea99ea12018-05-28 13:54:23331 // Reload navigations
332 switch (reload_type) {
333 case ReloadType::NORMAL:
Minggang Wangb9f3fa92021-07-01 15:30:31334 return blink::mojom::NavigationType::RELOAD;
clamyea99ea12018-05-28 13:54:23335 case ReloadType::BYPASSING_CACHE:
Minggang Wangb9f3fa92021-07-01 15:30:31336 return blink::mojom::NavigationType::RELOAD_BYPASSING_CACHE;
clamyea99ea12018-05-28 13:54:23337 case ReloadType::ORIGINAL_REQUEST_URL:
Minggang Wangb9f3fa92021-07-01 15:30:31338 return blink::mojom::NavigationType::RELOAD_ORIGINAL_REQUEST_URL;
clamyea99ea12018-05-28 13:54:23339 case ReloadType::NONE:
340 break; // Fall through to rest of function.
341 }
342
Lukasz Anforowicz6b75c0d2020-12-01 22:56:08343 if (entry->IsRestored()) {
Minggang Wangb9f3fa92021-07-01 15:30:31344 return entry->GetHasPostData()
345 ? blink::mojom::NavigationType::RESTORE_WITH_POST
346 : blink::mojom::NavigationType::RESTORE;
clamyea99ea12018-05-28 13:54:23347 }
348
danakjb952ef12021-01-14 19:58:49349 const bool can_be_same_document =
350 // A pending cross-document commit means this navigation will not occur in
351 // the current document, as that document would end up being replaced in
352 // the meantime.
353 !has_pending_cross_document_commit &&
354 // If the current document is an error page, we should always treat it as
355 // a different-document navigation so that we'll attempt to load the
356 // document we're navigating to (and not stay in the current error page).
Garrett Tanzer405f3402022-07-21 20:12:49357 !is_currently_error_page &&
Garrett Tanzer267c2b82022-07-26 16:53:13358 // If the navigation is an embedder-initiated navigation of a fenced
359 // frame root (i.e. enters a fenced frame tree from outside),
360 // same-document navigations should be disabled because we don't want to
361 // allow information to be joined across multiple embedder-initiated
362 // fenced frame navigations (which may contain separate cross-site data).
363 !is_embedder_initiated_fenced_frame_navigation &&
Garrett Tanzer405f3402022-07-21 20:12:49364 // If the navigation is to _unfencedTop (i.e. escapes a fenced frame),
365 // same-document navigations should be disabled because we want to force
366 // the creation of a new browsing context group.
367 !is_unfenced_top_navigation;
danakjd83d706d2020-11-25 22:11:12368
clamyea99ea12018-05-28 13:54:23369 // History navigations.
370 if (frame_entry.page_state().IsValid()) {
danakjd83d706d2020-11-25 22:11:12371 return can_be_same_document && is_same_document_history_load
Minggang Wangb9f3fa92021-07-01 15:30:31372 ? blink::mojom::NavigationType::HISTORY_SAME_DOCUMENT
373 : blink::mojom::NavigationType::HISTORY_DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23374 }
375 DCHECK(!is_same_document_history_load);
376
377 // A same-document fragment-navigation happens when the only part of the url
378 // that is modified is after the '#' character.
379 //
380 // When modifying this condition, please take a look at:
danakjd83d706d2020-11-25 22:11:12381 // FrameLoader::ShouldPerformFragmentNavigation().
clamyea99ea12018-05-28 13:54:23382 //
383 // Note: this check is only valid for navigations that are not history
384 // navigations. For instance, if the history is: 'A#bar' -> 'B' -> 'A#foo', a
385 // history navigation from 'A#foo' to 'A#bar' is not a same-document
386 // navigation, but a different-document one. This is why history navigation
387 // are classified before this check.
Lei Zhang96031532019-10-10 19:05:47388 bool is_same_doc = new_url.has_ref() && old_url.EqualsIgnoringRef(new_url) &&
389 frame_entry.method() == "GET";
danakjd83d706d2020-11-25 22:11:12390
391 // The one case where we do the wrong thing here and incorrectly choose
392 // SAME_DOCUMENT is if the navigation is browser-initiated but the document in
393 // the renderer is a frameset. All frameset navigations should be
394 // DIFFERENT_DOCUMENT, even if their URLs match. A renderer-initiated
395 // navigation would do the right thing, as it would send it to the browser and
396 // all renderer-initiated navigations are DIFFERENT_DOCUMENT (they don't get
397 // into this method). But since we can't tell that case here for browser-
398 // initiated navigations, we have to get the renderer involved. In that case
399 // the navigation would be restarted due to the renderer spending a reply of
400 // mojom::CommitResult::RestartCrossDocument.
401
402 return can_be_same_document && is_same_doc
Minggang Wangb9f3fa92021-07-01 15:30:31403 ? blink::mojom::NavigationType::SAME_DOCUMENT
404 : blink::mojom::NavigationType::DIFFERENT_DOCUMENT;
clamyea99ea12018-05-28 13:54:23405}
406
Camille Lamy5193caa2018-10-12 11:59:42407// Adjusts the original input URL if needed, to get the URL to actually load and
408// the virtual URL, which may differ.
409void RewriteUrlForNavigation(const GURL& original_url,
410 BrowserContext* browser_context,
411 GURL* url_to_load,
412 GURL* virtual_url,
413 bool* reverse_on_redirect) {
Camille Lamy5193caa2018-10-12 11:59:42414 // Allow the browser URL handler to rewrite the URL. This will, for example,
415 // remove "view-source:" from the beginning of the URL to get the URL that
416 // will actually be loaded. This real URL won't be shown to the user, just
417 // used internally.
Lukasz Anforowicz7b078792020-10-20 17:04:31418 *url_to_load = *virtual_url = original_url;
Camille Lamy5193caa2018-10-12 11:59:42419 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
420 url_to_load, browser_context, reverse_on_redirect);
421}
422
423#if DCHECK_IS_ON()
424// Helper sanity check function used in debug mode.
425void ValidateRequestMatchesEntry(NavigationRequest* request,
426 NavigationEntryImpl* entry) {
427 if (request->frame_tree_node()->IsMainFrame()) {
428 DCHECK_EQ(request->browser_initiated(), !entry->is_renderer_initiated());
429 DCHECK(ui::PageTransitionTypeIncludingQualifiersIs(
Minggang Wangb9f3fa92021-07-01 15:30:31430 ui::PageTransitionFromInt(request->common_params().transition),
431 entry->GetTransitionType()));
Camille Lamy5193caa2018-10-12 11:59:42432 }
Nasko Oskovc36327d2019-01-03 23:23:04433 DCHECK_EQ(request->commit_params().should_clear_history_list,
Camille Lamy5193caa2018-10-12 11:59:42434 entry->should_clear_history_list());
435 DCHECK_EQ(request->common_params().has_user_gesture,
436 entry->has_user_gesture());
437 DCHECK_EQ(request->common_params().base_url_for_data_url,
438 entry->GetBaseURLForDataURL());
Nasko Oskovc36327d2019-01-03 23:23:04439 DCHECK_EQ(request->commit_params().can_load_local_resources,
Camille Lamy5193caa2018-10-12 11:59:42440 entry->GetCanLoadLocalResources());
441 DCHECK_EQ(request->common_params().started_from_context_menu,
442 entry->has_started_from_context_menu());
443
444 FrameNavigationEntry* frame_entry =
445 entry->GetFrameEntry(request->frame_tree_node());
446 if (!frame_entry) {
447 NOTREACHED();
448 return;
449 }
450
Camille Lamy5193caa2018-10-12 11:59:42451 DCHECK_EQ(request->common_params().method, frame_entry->method());
452
Nasko Oskovc36327d2019-01-03 23:23:04453 size_t redirect_size = request->commit_params().redirects.size();
Camille Lamy5193caa2018-10-12 11:59:42454 if (redirect_size == frame_entry->redirect_chain().size()) {
455 for (size_t i = 0; i < redirect_size; ++i) {
Nasko Oskovc36327d2019-01-03 23:23:04456 DCHECK_EQ(request->commit_params().redirects[i],
Camille Lamy5193caa2018-10-12 11:59:42457 frame_entry->redirect_chain()[i]);
458 }
459 } else {
460 NOTREACHED();
461 }
462}
463#endif // DCHECK_IS_ON()
464
Dave Tapuska8bfd84c2019-03-26 20:47:16465// Returns whether the session history NavigationRequests in |navigations|
Nate Chapinbf682fa32022-09-26 22:41:20466// would stay within the subtree of |sandboxed_initiator_rfh|.
Dave Tapuska8bfd84c2019-03-26 20:47:16467bool DoesSandboxNavigationStayWithinSubtree(
Nate Chapinbf682fa32022-09-26 22:41:20468 RenderFrameHostImpl* sandboxed_initiator_rfh,
Dave Tapuska8bfd84c2019-03-26 20:47:16469 const std::vector<std::unique_ptr<NavigationRequest>>& navigations) {
Nate Chapinbf682fa32022-09-26 22:41:20470 DCHECK(sandboxed_initiator_rfh);
471 DCHECK(sandboxed_initiator_rfh->IsSandboxed(
472 network::mojom::WebSandboxFlags::kTopNavigation));
Dave Tapuska8bfd84c2019-03-26 20:47:16473 for (auto& item : navigations) {
474 bool within_subtree = false;
475 // Check whether this NavigationRequest affects a frame within the
476 // sandboxed frame's subtree by walking up the tree looking for the
477 // sandboxed frame.
478 for (auto* frame = item->frame_tree_node(); frame;
Alexander Timin381e7e182020-04-28 19:04:03479 frame = FrameTreeNode::From(frame->parent())) {
Nate Chapinbf682fa32022-09-26 22:41:20480 if (frame == sandboxed_initiator_rfh->frame_tree_node()) {
Dave Tapuska8bfd84c2019-03-26 20:47:16481 within_subtree = true;
482 break;
483 }
484 }
485 if (!within_subtree)
486 return false;
487 }
488 return true;
489}
490
[email protected]e9ba4472008-09-14 15:42:43491} // namespace
492
arthursonzogni66f711c2019-10-08 14:40:36493// NavigationControllerImpl::PendingEntryRef------------------------------------
494
495NavigationControllerImpl::PendingEntryRef::PendingEntryRef(
496 base::WeakPtr<NavigationControllerImpl> controller)
497 : controller_(controller) {}
498
499NavigationControllerImpl::PendingEntryRef::~PendingEntryRef() {
500 if (!controller_) // Can be null with interstitials.
501 return;
502
503 controller_->PendingEntryRefDeleted(this);
504}
505
[email protected]d202a7c2012-01-04 07:53:47506// NavigationControllerImpl ----------------------------------------------------
initial.commit09911bf2008-07-26 23:55:29507
[email protected]23a918b2014-07-15 09:51:36508const size_t kMaxEntryCountForTestingNotSet = static_cast<size_t>(-1);
[email protected]9b51970d2011-12-09 23:10:23509
[email protected]765b35502008-08-21 00:51:20510// static
[email protected]d202a7c2012-01-04 07:53:47511size_t NavigationControllerImpl::max_entry_count_for_testing_ =
[email protected]9b51970d2011-12-09 23:10:23512 kMaxEntryCountForTestingNotSet;
[email protected]765b35502008-08-21 00:51:20513
[email protected]e6fec472013-05-14 05:29:02514// Should Reload check for post data? The default is true, but is set to false
[email protected]cdcb1dee2012-01-04 00:46:20515// when testing.
516static bool g_check_for_repost = true;
initial.commit09911bf2008-07-26 23:55:29517
[email protected]71fde352011-12-29 03:29:56518// static
dcheng9bfa5162016-04-09 01:00:57519std::unique_ptr<NavigationEntry> NavigationController::CreateNavigationEntry(
520 const GURL& url,
Lukasz Anforowicz641234d52019-11-07 21:07:10521 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07522 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21523 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10524 ui::PageTransition transition,
525 bool is_renderer_initiated,
526 const std::string& extra_headers,
527 BrowserContext* browser_context,
528 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
529 return NavigationControllerImpl::CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:21530 url, referrer, std::move(initiator_origin), std::move(initiator_base_url),
Lukasz Anforowicz641234d52019-11-07 21:07:10531 nullptr /* source_site_instance */, transition, is_renderer_initiated,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17532 extra_headers, browser_context, std::move(blob_url_loader_factory),
533 true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10534}
535
536// static
537std::unique_ptr<NavigationEntryImpl>
538NavigationControllerImpl::CreateNavigationEntry(
539 const GURL& url,
540 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07541 absl::optional<url::Origin> initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:21542 absl::optional<GURL> initiator_base_url,
Lukasz Anforowicz641234d52019-11-07 21:07:10543 SiteInstance* source_site_instance,
dcheng9bfa5162016-04-09 01:00:57544 ui::PageTransition transition,
545 bool is_renderer_initiated,
546 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09547 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17548 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
549 bool rewrite_virtual_urls) {
550 GURL url_to_load = url;
551 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56552 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17553 if (rewrite_virtual_urls) {
554 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
555 &reverse_on_redirect);
556 }
Lukasz Anforowicz641234d52019-11-07 21:07:10557 // Let the NTP override the navigation params and pretend that this is a
558 // browser-initiated, bookmark-like navigation.
559 GetContentClient()->browser()->OverrideNavigationParams(
Scott Violetcf6ea7e2021-06-09 21:09:21560 source_site_instance, &transition, &is_renderer_initiated, &referrer,
561 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10562
Patrick Monettef507e982019-06-19 20:18:06563 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28564 nullptr, // The site instance for tabs is sent on navigation
565 // (WebContents::GetSiteInstance).
W. James MacLean23e90a12022-12-21 04:38:21566 url_to_load, referrer, initiator_origin, initiator_base_url,
567 std::u16string(), transition, is_renderer_initiated,
568 blob_url_loader_factory,
Rakina Zata Amniafd3c6582021-11-30 06:19:17569 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42570 entry->SetVirtualURL(virtual_url);
571 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56572 entry->set_update_virtual_url_with_url(reverse_on_redirect);
573 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06574 return entry;
[email protected]71fde352011-12-29 03:29:56575}
576
[email protected]cdcb1dee2012-01-04 00:46:20577// static
578void NavigationController::DisablePromptOnRepost() {
579 g_check_for_repost = false;
580}
581
[email protected]c5b88d82012-10-06 17:03:33582base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
583 base::Time t) {
584 // If |t| is between the water marks, we're in a run of duplicates
585 // or just getting out of it, so increase the high-water mark to get
586 // a time that probably hasn't been used before and return it.
587 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35588 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33589 return high_water_mark_;
590 }
591
592 // Otherwise, we're clear of the last duplicate run, so reset the
593 // water marks.
594 low_water_mark_ = high_water_mark_ = t;
595 return t;
596}
597
ckitagawa0faa5e42020-06-17 17:30:54598NavigationControllerImpl::ScopedShowRepostDialogForTesting::
599 ScopedShowRepostDialogForTesting()
600 : was_disallowed_(g_check_for_repost) {
601 g_check_for_repost = true;
602}
603
604NavigationControllerImpl::ScopedShowRepostDialogForTesting::
605 ~ScopedShowRepostDialogForTesting() {
606 g_check_for_repost = was_disallowed_;
607}
608
Nate Chapin9eb16be72022-09-23 22:54:31609NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
610 base::SafeRef<NavigationControllerImpl> controller)
611 : controller_(controller) {
612 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
613 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
614 frame_tree_node_id_to_keys_.insert(
615 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
616 if (auto* frame_entry = frame_tree_node->current_frame_host()
617 ->last_committed_frame_entry()) {
618 frame_tree_node_id_to_doc_seq_nos_.insert(
619 {frame_tree_node->frame_tree_node_id(),
620 frame_entry->document_sequence_number()});
621 }
622 }
623 PopulateKeySet(Direction::kBack);
624 PopulateKeySet(Direction::kForward);
625}
626
627void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
628 Direction direction) {
629 // Keep track of which FrameTreeNodes may still have relevant API keys in
630 // additional FrameNavigationEntries.
631 std::set<FrameTreeNode*> nodes_to_process;
632 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
633 nodes_to_process.insert(node);
634 }
635
636 const int offset = direction == Direction::kForward ? 1 : -1;
637 const int start = direction == Direction::kForward
638 ? controller_->GetLastCommittedEntryIndex()
639 : controller_->GetLastCommittedEntryIndex() - 1;
640 for (int i = start;
641 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
642 i += offset) {
643 std::set<FrameTreeNode*> nodes_to_continue_processing;
644
645 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
646 entry->ForEachFrameEntry([this, &nodes_to_process,
647 &nodes_to_continue_processing,
648 &entry](FrameNavigationEntry* frame_entry) {
649 // Find the |node| that matches |frame_entry|, if any.
650 FrameTreeNode* node = nullptr;
651 if (frame_entry == entry->root_node()->frame_entry) {
652 node = controller_->frame_tree().root();
653 } else {
654 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
655 if (it == names_to_nodes_.end())
656 return;
657 node = it->second;
658 }
659
660 // Skip this node if a previous step determine there are no longer
661 // relevant navigation API keys in this direction.
662 if (nodes_to_process.find(node) == nodes_to_process.end())
663 return;
664
665 // Stop processing |node| if we reach a point where it's cross-origin.
666 // See also PopulateSingleNavigationApiHistoryEntryVector().
667 url::Origin frame_entry_origin =
668 frame_entry->committed_origin().value_or(url::Origin::Resolve(
669 frame_entry->url(),
670 frame_entry->initiator_origin().value_or(url::Origin())));
671 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
672 return;
673
674 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
675 frame_entry->navigation_api_key());
676 // Mark |node| as needing more processing for the next entry.
677 nodes_to_continue_processing.insert(node);
678
679 // Check whether |node| went cross-document. If so, its children are
680 // no longer the same conceptual iframe as the current one, and
681 // should no longer be processed. This check is intentionally done
682 // after processing the current |node|, which may still have relevant
683 // discarded API keys.
684 if (frame_entry->document_sequence_number() !=
685 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
Arthur Sonzognif6785ec2022-12-05 10:11:50686 for (auto* descendant : node->frame_tree().SubtreeNodes(node))
Nate Chapin9eb16be72022-09-23 22:54:31687 nodes_to_process.erase(descendant);
688 }
689 });
690
691 nodes_to_process.swap(nodes_to_continue_processing);
692 }
693}
694
695NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
696 std::set<std::string> all_keys;
697 // Find all remaining navigation API keys after some entries have been
698 // removed.
699 for (auto& entry : controller_->entries_) {
700 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
701 all_keys.insert(frame_entry->navigation_api_key());
702 });
703 }
704
705 // Notify each frame in the renderer of any disposed navigation API keys.
706 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
707 std::vector<std::string> disposed_keys;
708 for (const auto& key : id_to_keys.second) {
709 if (all_keys.find(key) == all_keys.end())
710 disposed_keys.push_back(key);
711 }
712 if (disposed_keys.empty())
713 continue;
714
715 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
716 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
717 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
718 }
719}
720
[email protected]d202a7c2012-01-04 07:53:47721NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00722 BrowserContext* browser_context,
723 FrameTree& frame_tree,
724 NavigationControllerDelegate* delegate)
725 : frame_tree_(frame_tree),
726 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57727 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22728 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47729 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37730 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29731}
732
[email protected]d202a7c2012-01-04 07:53:47733NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00734 // The NavigationControllerImpl might be called inside its delegate
735 // destructor. Calling it is not valid anymore.
736 delegate_ = nullptr;
737 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29738}
739
Matt Falkenhagen548ed1562021-07-06 01:38:26740WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
741 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32742}
743
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57744BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55745 return browser_context_;
746}
747
[email protected]d202a7c2012-01-04 07:53:47748void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30749 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36750 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57751 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47752 // Note that it's possible for `entries_` to contain multiple entries at this
753 // point, as Restore() might be called on a NavigationController that is
754 // already used (e.g. due to WebView's restoreState() API), not only for fresh
755 // NavigationControllers. These entries are not cleared to preserve legacy
756 // behavior and also because `pending_entry_` might point to one of the
757 // pre-existing entries. An exception for this is when `entries_` contains
758 // only the initial NavigationEntry, which must be removed.
759
760 // Do not proceed if selected_navigation will be out of bounds for the updated
761 // entries_ list, since it will be assigned to last_committed_entry_index_ and
762 // used to index entries_.
763 // TODO(https://crbug.com/1287624): Consider also returning early if entries
764 // is empty, since there should be no work to do (rather than marking the
765 // existing entries as needing reload). Also consider returning early if the
766 // selected index is -1, which represents a no-committed-entry state.
767 if (selected_navigation < -1 ||
768 selected_navigation >=
769 base::checked_cast<int>(entries->size() + entries_.size())) {
770 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24771 }
Charlie Reis23c26da2022-01-29 00:57:47772
Rakina Zata Amni46087a12022-11-11 08:28:38773 // There will always be at least one entry (new NavigationControllers will
774 // have the initial NavigationEntry).
775 if (selected_navigation == -1)
776 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47777
Rakina Zata Amni46087a12022-11-11 08:28:38778 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
779 // If we are on the initial NavigationEntry, it must be the only entry in
780 // the list. Since it's impossible to do a history navigation to the
781 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
782 // `pending_entry` might be set for a new non-history navigation).
783 // Note that we should not clear `entries_` if `entries` is empty (when
784 // InitialNavigationEntry mode is enabled), since that would leave us
785 // without any NavigationEntry.
786 CHECK_EQ(1, GetEntryCount());
787 CHECK_EQ(-1, pending_entry_index_);
788 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47789 }
[email protected]ce3fa3c2009-04-20 19:55:57790
[email protected]ce3fa3c2009-04-20 19:55:57791 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44792 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03793 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47794 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43795 if (entry->GetURL().is_empty()) {
796 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01797 // persisting the initial NavigationEntry [which is no longer possible but
798 // some old persisted sessions might still contain it] or when the
799 // serializer failed to write the URL because it's too long). Trying to
800 // restore and navigate to an entry with an empty URL will result in
801 // crashes, so change the URL to about:blank. See also
802 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43803 entry->SetURL(GURL(url::kAboutBlankURL));
804 }
dcheng36b6aec92015-12-26 06:16:36805 entries_.push_back(
806 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47807 }
avif16f85a72015-11-13 18:25:03808
809 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
810 // cleared out safely.
811 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57812
813 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36814 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57815}
816
toyoshim6142d96f2016-12-19 09:07:25817void NavigationControllerImpl::Reload(ReloadType reload_type,
818 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03819 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
820 (int)reload_type);
821 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
822 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28823 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28824 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32825 int current_index = -1;
826
Carlos IL42b416592019-10-07 23:10:36827 if (entry_replaced_by_post_commit_error_) {
828 // If there is an entry that was replaced by a currently active post-commit
829 // error navigation, this can't be the initial navigation.
830 DCHECK(!IsInitialNavigation());
831 // If the current entry is a post commit error, we reload the entry it
832 // replaced instead. We leave the error entry in place until a commit
833 // replaces it, but the pending entry points to the original entry in the
834 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
835 // case that pending_entry_ != entries_[pending_entry_index_].
836 entry = entry_replaced_by_post_commit_error_.get();
837 current_index = GetCurrentEntryIndex();
838 } else if (IsInitialNavigation() && pending_entry_) {
839 // If we are reloading the initial navigation, just use the current
840 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32841 entry = pending_entry_;
842 // The pending entry might be in entries_ (e.g., after a Clone), so we
843 // should also update the current_index.
844 current_index = pending_entry_index_;
845 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00846 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32847 current_index = GetCurrentEntryIndex();
848 if (current_index != -1) {
creis3da03872015-02-20 21:12:32849 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32850 }
[email protected]979a4bc2013-04-24 01:27:15851 }
[email protected]241db352013-04-22 18:04:05852
[email protected]59167c22013-06-03 18:07:32853 // If we are no where, then we can't reload. TODO(darin): We should add a
854 // CanReload method.
855 if (!entry)
856 return;
857
Rakina Zata Amnif297a802022-01-18 03:53:43858 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
859 // We should never navigate to an existing initial NavigationEntry that is
860 // the initial NavigationEntry for the initial empty document that hasn't
861 // been overridden by the synchronous about:blank commit, to preserve
862 // legacy behavior where trying to reload when the main frame is on the
863 // initial empty document won't result in a navigation. See also
864 // https://crbug.com/1277414.
865 return;
866 }
867
Aran Gilman37d11632019-10-08 23:07:15868 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30869 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07870 // they really want to do this. If they do, the dialog will call us back
871 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57872 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02873
[email protected]106a0812010-03-18 00:15:12874 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57875 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47876 return;
initial.commit09911bf2008-07-26 23:55:29877 }
Lei Zhang96031532019-10-10 19:05:47878
Wang Huia25efabc2022-09-24 17:27:22879 // Set ReloadType for |entry|.
880 entry->set_reload_type(reload_type);
881
Lei Zhang96031532019-10-10 19:05:47882 if (!IsInitialNavigation())
883 DiscardNonCommittedEntries();
884
885 pending_entry_ = entry;
886 pending_entry_index_ = current_index;
887 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
888
Nate Chapin45f620582021-09-30 17:45:43889 // location.reload() goes through BeginNavigation, so all reloads triggered
890 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13891 NavigateToExistingPendingEntry(
892 reload_type,
893 /*initiator_rfh=*/nullptr,
894 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
895 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29896}
897
[email protected]d202a7c2012-01-04 07:53:47898void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48899 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12900}
901
[email protected]d202a7c2012-01-04 07:53:47902void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49903 // If the pending reload type has been cleared by another navigation
904 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48905 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49906 return;
[email protected]106a0812010-03-18 00:15:12907 }
Wang Hui96ab1012022-10-11 02:05:49908 Reload(pending_reload_, false);
909 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12910}
911
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57912bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09913 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11914}
915
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57916bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38917 // Check that we're on the initial NavigationEntry and that this is not a
918 // cloned tab.
919 return IsInitialNavigation() && GetEntryCount() == 1 &&
920 GetLastCommittedEntry()->IsInitialEntry() &&
921 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40922}
923
Aran Gilman37d11632019-10-08 23:07:15924NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
925 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58926 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03927 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58928}
929
Adithya Srinivasan9b0c99c2021-08-10 15:19:45930NavigationEntryImpl*
931NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
932 int nav_entry_id) const {
933 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
934 if (entry)
935 return entry;
936 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52937 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45938 : nullptr;
939}
940
W. James MacLeanc07dc41b2022-07-25 18:52:16941void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57942 const url::Origin& origin) {
943 for (int i = 0; i < GetEntryCount(); i++) {
944 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16945 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57946 }
947 if (entry_replaced_by_post_commit_error_) {
948 // It's possible we could come back to this entry if the error
949 // page/interstitial goes away.
950 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16951 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57952 }
W. James MacLean1c40862c2020-04-27 21:05:57953}
954
avi25764702015-06-23 15:43:37955void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57956 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00957 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37958 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27959 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20960}
961
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57962NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47963 if (pending_entry_)
964 return pending_entry_;
965 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20966}
967
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57968NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32969 // The pending entry is safe to return for new (non-history), browser-
970 // initiated navigations. Most renderer-initiated navigations should not
971 // show the pending entry, to prevent URL spoof attacks.
972 //
973 // We make an exception for renderer-initiated navigations in new tabs, as
974 // long as no other page has tried to access the initial empty document in
975 // the new tab. If another page modifies this blank page, a URL spoof is
976 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:32977 bool safe_to_show_pending =
978 pending_entry_ &&
979 // Require a new navigation.
avi0dca04d2015-01-26 20:21:09980 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:32981 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:46982 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:32983
984 // Also allow showing the pending entry for history navigations in a new tab,
985 // such as Ctrl+Back. In this case, no existing page is visible and no one
986 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:15987 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
988 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:32989 safe_to_show_pending = true;
990
991 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:19992 return pending_entry_;
993 return GetLastCommittedEntry();
994}
995
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57996int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:20997 if (pending_entry_index_ != -1)
998 return pending_entry_index_;
999 return last_committed_entry_index_;
1000}
1001
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571002NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381003 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031004 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201005}
1006
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571007bool NavigationControllerImpl::CanViewSource() {
Jeremy Roman2d8dfe132021-07-06 20:51:261008 const std::string& mime_type =
Ali Hijazid87307d2022-11-07 20:15:031009 frame_tree_->root()->current_frame_host()->GetPage().contents_mime_type();
Kinuko Yasuda74702f92017-07-31 03:27:531010 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1011 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271012 NavigationEntry* visible_entry = GetVisibleEntry();
1013 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391014 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161015}
1016
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571017int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271018 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451019 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271020 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551021 return last_committed_entry_index_;
1022}
1023
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571024int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451025 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291026 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551027 return static_cast<int>(entries_.size());
1028}
1029
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571030NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371031 if (index < 0 || index >= GetEntryCount())
1032 return nullptr;
1033
avif16f85a72015-11-13 18:25:031034 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251035}
1036
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571037NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471038 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201039}
1040
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571041int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461042 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031043}
1044
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571045bool NavigationControllerImpl::CanGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031046 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
1047 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1048 return true;
1049 }
1050 return false;
[email protected]765b35502008-08-21 00:51:201051}
1052
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571053bool NavigationControllerImpl::CanGoForward() {
WangHui74286d52021-03-31 16:17:151054 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1055 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1056 return true;
1057 }
1058 return false;
[email protected]765b35502008-08-21 00:51:201059}
1060
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571061bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031062 int index = GetIndexForOffset(offset);
1063 return index >= 0 && index < GetEntryCount();
1064}
1065
Xiaohan Wang7f8052e02022-01-14 18:44:281066#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151067bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151068 if (offset == 0)
1069 return true;
1070 int increment = offset > 0 ? 1 : -1;
1071 int non_skippable_entries = 0;
1072 for (int index = GetIndexForOffset(increment);
1073 index >= 0 && index < GetEntryCount(); index += increment) {
1074 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1075 non_skippable_entries++;
1076
1077 if (non_skippable_entries == std::abs(offset))
1078 return true;
1079 }
1080 return false;
1081}
1082#endif
1083
[email protected]d202a7c2012-01-04 07:53:471084void NavigationControllerImpl::GoBack() {
shivanisha55201872018-12-13 04:29:061085 int target_index = GetIndexForOffset(-1);
1086
Elly Fong-Jones40ee8112021-06-23 19:10:521087 // Move the target index past the skippable entries.
Shivani Sharma298d12852019-01-22 20:04:031088 bool all_skippable_entries = true;
Elly Fong-Jones40ee8112021-06-23 19:10:521089 while (target_index >= 0) {
1090 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui()) {
Shivani Sharma298d12852019-01-22 20:04:031091 all_skippable_entries = false;
shivanisha55201872018-12-13 04:29:061092 break;
Shivani Sharma2d5b4b6b2019-01-08 16:07:161093 }
Elly Fong-Jones40ee8112021-06-23 19:10:521094 target_index--;
shivanisha55201872018-12-13 04:29:061095 }
Miyoung Shin1c565c912021-03-17 12:11:211096
Shivani Sharma298d12852019-01-22 20:04:031097 // Do nothing if all entries are skippable. Normally this path would not
1098 // happen as consumers would have already checked it in CanGoBack but a lot of
1099 // tests do not do that.
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421100 if (all_skippable_entries)
Shivani Sharma298d12852019-01-22 20:04:031101 return;
shivanisha55201872018-12-13 04:29:061102
shivanisha55201872018-12-13 04:29:061103 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201104}
1105
[email protected]d202a7c2012-01-04 07:53:471106void NavigationControllerImpl::GoForward() {
shivanisha55201872018-12-13 04:29:061107 int target_index = GetIndexForOffset(1);
1108
Shivani Sharma2d5b4b6b2019-01-08 16:07:161109 // Note that at least one entry (the last one) will be non-skippable since
1110 // entries are marked skippable only when they add another entry because of
1111 // redirect or pushState.
Elly Fong-Jones40ee8112021-06-23 19:10:521112 while (target_index < static_cast<int>(entries_.size())) {
1113 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui())
shivanisha55201872018-12-13 04:29:061114 break;
Elly Fong-Jones40ee8112021-06-23 19:10:521115 target_index++;
shivanisha55201872018-12-13 04:29:061116 }
shivanisha55201872018-12-13 04:29:061117 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201118}
1119
[email protected]d202a7c2012-01-04 07:53:471120void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131121 GoToIndex(index, /*initiator_rfh=*/nullptr,
1122 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1123 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161124}
1125
Nate Chapinbf682fa32022-09-26 22:41:201126void NavigationControllerImpl::GoToIndex(
1127 int index,
1128 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131129 absl::optional<blink::scheduler::TaskAttributionId>
1130 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201131 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031132 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441133 TRACE_EVENT0("browser,navigation,benchmark",
1134 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201135 if (index < 0 || index >= static_cast<int>(entries_.size())) {
1136 NOTREACHED();
1137 return;
1138 }
1139
Rakina Zata Amnif297a802022-01-18 03:53:431140 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1141 // We should never navigate to an existing initial NavigationEntry that is
1142 // the initial NavigationEntry for the initial empty document that hasn't
1143 // been overridden by the synchronous about:blank commit, to preserve
1144 // legacy behavior where trying to reload when the main frame is on the
1145 // initial empty document won't result in a navigation. See also
1146 // https://crbug.com/1277414.
1147 return;
1148 }
1149
[email protected]cbab76d2008-10-13 22:42:471150 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201151
arthursonzogni5c4c202d2017-04-25 23:41:271152 DCHECK_EQ(nullptr, pending_entry_);
1153 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431154
arthursonzogni5c4c202d2017-04-25 23:41:271155 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201156 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271157 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1158 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201159 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131160 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201161 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201162}
1163
[email protected]d202a7c2012-01-04 07:53:471164void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121165 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031166 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201167 return;
1168
[email protected]9ba14052012-06-22 23:50:031169 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201170}
1171
Nate Chapinbf682fa32022-09-26 22:41:201172void NavigationControllerImpl::GoToOffsetFromRenderer(
1173 int offset,
Yoav Weiss8c573952022-11-17 17:35:131174 RenderFrameHostImpl* initiator_rfh,
1175 absl::optional<blink::scheduler::TaskAttributionId>
1176 soft_navigation_heuristics_task_id) {
Nate Chapin45f620582021-09-30 17:45:431177 // Note: This is actually reached in unit tests.
1178 if (!CanGoToOffset(offset))
1179 return;
1180
Nate Chapinbf682fa32022-09-26 22:41:201181 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131182 soft_navigation_heuristics_task_id,
1183 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431184}
1185
Xiaohan Wang7f8052e02022-01-14 18:44:281186#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151187void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1188 // Note: This is actually reached in unit tests.
1189 if (!CanGoToOffsetWithSkipping(offset))
1190 return;
1191
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421192 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151193 GoToIndex(GetIndexForOffset(offset));
1194 return;
1195 }
1196 int increment = offset > 0 ? 1 : -1;
1197 // Find the offset without counting skippable entries.
1198 int target_index = GetIndexForOffset(increment);
1199 int non_skippable_entries = 0;
1200 for (int index = target_index; index >= 0 && index < GetEntryCount();
1201 index += increment) {
1202 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1203 non_skippable_entries++;
1204
1205 if (non_skippable_entries == std::abs(offset)) {
1206 target_index = index;
1207 break;
1208 }
1209 }
1210
1211 GoToIndex(target_index);
1212}
1213#endif
1214
[email protected]41374f12013-07-24 02:49:281215bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151216 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281217 return false;
[email protected]6a13a6c2011-12-20 21:47:121218
[email protected]43032342011-03-21 14:10:311219 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281220 return true;
[email protected]cbab76d2008-10-13 22:42:471221}
1222
Michael Thiessen9b14d512019-09-23 21:19:471223void NavigationControllerImpl::PruneForwardEntries() {
1224 DiscardNonCommittedEntries();
1225 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471226 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471227 if (num_removed <= 0)
1228 return;
Nate Chapin9eb16be72022-09-23 22:54:311229 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471230 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1231 NotifyPrunedEntries(this, remove_start_index /* start index */,
1232 num_removed /* count */);
1233}
1234
Aran Gilman37d11632019-10-08 23:07:151235void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1236 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321237 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311238 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511239 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1240 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321241 }
1242}
1243
Harkiran Bolariaba823e42021-05-21 18:30:361244base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1245 const GURL& url,
1246 const Referrer& referrer,
1247 ui::PageTransition transition,
1248 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471249 LoadURLParams params(url);
1250 params.referrer = referrer;
1251 params.transition_type = transition;
1252 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361253 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471254}
1255
Harkiran Bolariaba823e42021-05-21 18:30:361256base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1257 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061258 if (params.is_renderer_initiated)
1259 DCHECK(params.initiator_origin.has_value());
1260
naskob8744d22014-08-28 17:07:431261 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151262 "NavigationControllerImpl::LoadURLWithParams", "url",
1263 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291264 bool is_explicit_navigation =
1265 GetContentClient()->browser()->IsExplicitNavigation(
1266 params.transition_type);
1267 if (HandleDebugURL(params.url, params.transition_type,
1268 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431269 // If Telemetry is running, allow the URL load to proceed as if it's
1270 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491271 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431272 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361273 return nullptr;
[email protected]47752982014-07-29 08:01:431274 }
[email protected]8bf1048012012-02-08 01:22:181275
[email protected]cf002332012-08-14 19:17:471276 // Checks based on params.load_type.
1277 switch (params.load_type) {
1278 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431279 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471280 break;
1281 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261282 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471283 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361284 return nullptr;
[email protected]cf002332012-08-14 19:17:471285 }
1286 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461287 }
[email protected]e47ae9472011-10-13 19:48:341288
[email protected]e47ae9472011-10-13 19:48:341289 // The user initiated a load, we don't need to reload anymore.
1290 needs_reload_ = false;
1291
Harkiran Bolariaba823e42021-05-21 18:30:361292 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441293}
1294
Mohamed Abdelhalim833de902019-09-16 17:41:451295bool NavigationControllerImpl::PendingEntryMatchesRequest(
1296 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191297 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451298 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191299}
1300
[email protected]d202a7c2012-01-04 07:53:471301bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321302 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071303 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331304 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441305 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251306 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471307 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131308 NavigationRequest* navigation_request) {
1309 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331310
1311 // Note: validation checks and renderer kills due to invalid commit messages
1312 // must happen before getting here, in
1313 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1314 // effects of the navigation have already occurred.
1315
[email protected]cd2e15742013-03-08 04:08:311316 is_initial_navigation_ = false;
1317
Wang Hui96ab1012022-10-11 02:05:491318 // Any pending request to repost a form submission is no longer valid, since a
1319 // different NavigationEntry is committing.
1320 pending_reload_ = ReloadType::NONE;
1321
[email protected]0e8db942008-09-24 21:21:481322 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431323 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451324 if (entry_replaced_by_post_commit_error_) {
1325 // Same document navigation events with a post-commit error should already
1326 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1327 // reaching here.
1328 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331329
Rakina Zata Amnie2d31312022-11-18 03:38:451330 // Any commit while a post-commit error page is showing should put the
1331 // original entry back, replacing the error page's entry. This includes
1332 // reloads, where the original entry was used as the pending entry and
1333 // should now be at the correct index at commit time.
1334 entries_[last_committed_entry_index_] =
1335 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481336 }
Rakina Zata Amnie2d31312022-11-18 03:38:451337 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1338 details->previous_entry_index = GetLastCommittedEntryIndex();
1339 if (PendingEntryMatchesRequest(navigation_request) &&
1340 pending_entry_->GetIsOverridingUserAgent() !=
1341 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1342 overriding_user_agent_changed = true;
1343 }
1344#if BUILDFLAG(IS_ANDROID)
1345 // TODO(crbug.com/1266277): Clean up the logic of setting
1346 // |overriding_user_agent_changed| post-launch.
1347 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1348 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1349 // Must honor user agent overrides in the |navigation_request|, such as
1350 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1351 // result, besides comparing |pending_entry_|'s user agent against
1352 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1353 // agent against LastCommittedEntry's.
1354 if (navigation_request->is_overriding_user_agent() !=
1355 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1356 overriding_user_agent_changed = true;
1357 }
1358 }
1359#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171360
Dave Tapuskaa2ab4f252021-07-08 21:31:281361 bool is_main_frame_navigation = !rfh->GetParent();
1362
Alexander Timind2f2e4f22019-04-02 20:04:531363 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1364 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281365 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141366 // BackForwardCacheMetrics to be associated with the new navigation's
1367 // NavigationEntry, by either creating a new object or reusing the previous
1368 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281369 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
Arthur Sonzognif6785ec2022-12-05 10:11:501370 if (navigation_request->frame_tree_node()->frame_tree().type() ==
Dave Tapuskaa2ab4f252021-07-08 21:31:281371 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141372 back_forward_cache_metrics = BackForwardCacheMetrics::
1373 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281374 GetLastCommittedEntry(), is_main_frame_navigation,
1375 params.document_sequence_number);
1376 }
Yuzu Saijo29f96ca92022-12-08 04:54:121377
Alexander Timind2f2e4f22019-04-02 20:04:531378 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281379 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451380 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1381 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531382 }
1383 }
1384
Rakina Zata Amnifd8370b2022-11-14 13:32:251385 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1386 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091387 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251388 details->did_replace_entry =
1389 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091390
fdegans9caf66a2015-07-30 21:10:421391 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111392 // except for restored entries. This should be true even if the current commit
1393 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291394 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481395 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081396 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111397
1398 // Only make changes based on the pending entry if the NavigationRequest
1399 // matches it. Otherwise, the pending entry may be for a different request
1400 // (e.g., if a slow history navigation is pending while an auto-subframe
1401 // commit occurs).
1402 if (PendingEntryMatchesRequest(navigation_request)) {
1403 // It is no longer necessary to consider the pending entry as restored.
1404 if (pending_entry_->IsRestored()) {
1405 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1406 was_restored = true;
1407 }
[email protected]e9ba4472008-09-14 15:42:431408
Charlie Reisf8cde712022-10-20 16:25:091409 // If the SiteInstance has changed from the matching pending entry, this
1410 // must be treated as a new navigation with replacement. Set the replacement
1411 // bit here and ClassifyNavigation will identify this case and return
1412 // NEW_ENTRY.
1413 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1414 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1415 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251416 // TODO(nasko,creis,rakina): Move this to happen before committing the
1417 // navigation. This is a bit complicated because we don't currently
1418 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091419 details->did_replace_entry = true;
1420 }
Nasko Oskovaee2f862018-06-15 00:05:521421 }
[email protected]bcd904482012-02-01 01:54:221422
[email protected]e9ba4472008-09-14 15:42:431423 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101424 NavigationType navigation_type =
1425 ClassifyNavigation(rfh, params, navigation_request);
1426 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451427
Rakina Zata Amnie2d31312022-11-18 03:38:451428 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451429 // Ensure that this navigation does not add a navigation entry, since
1430 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1431 // beyond the last committed one. Therefore, `should_replace_current_entry`
1432 // should be set, which replaces the current entry, or this should be a
1433 // reload, which does not create a new entry.
1434 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1435 // navigation that is restored will not be creating a new entry anyways, so
1436 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1437 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1438 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251439 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451440 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101441 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451442 }
1443
Rakina Zata Amnie2d31312022-11-18 03:38:451444 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551445 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241446 // This is a subframe navigation on the initial empty document, which used
1447 // to not have a NavigationEntry to attach to. Now it can attach to the
1448 // initial NavigationEntry, and we must ensure that its NavigationEntry
1449 // will keep the "initial NavigationEntry" status and won't append a new
1450 // NavigationEntry (it should always do replacement instead).
1451 // See also https://crbug.com/1277414.
1452 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551453 // Subframe navigation on initial NavigationEntry must not append a new
1454 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1455 // means every subframe navigation that happens while we're on the initial
1456 // NavigationEntry will always reuse the existing NavigationEntry and
1457 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101458 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1459 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551460 // This is a navigation that modifies the initial NavigationEntry, either
1461 // for a replacement or a reload. The initial NavigationEntry should
1462 // retain its "initial NavigationEntry" status in this case.
1463 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241464 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251465 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1466 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241467 // This is a synchronous about:blank navigation on the main frame, which
1468 // used to not create a NavigationEntry when we have no NavigationEntry on
1469 // FrameTree creation. We now have the initial NavigationEntry and are on
1470 // the initial NavigationEntry. To preserve old behavior, we should still
1471 // keep the "initial" status for the new NavigationEntry that we will
1472 // create for this navigation, so that subframe navigations under the
1473 // synchronously committed about:blank document will never append new
1474 // NavigationEntry, and instead will just reuse the initial
1475 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1476 // See also https://crbug.com/1277414.
1477 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551478 }
1479 }
1480 DCHECK(!details->should_stay_as_initial_entry ||
1481 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201482
eugenebutee08663a2017-04-27 17:43:121483 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441484 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121485
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071486 details->is_prerender_activation =
1487 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241488 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1489 ->GetOutermostMainFrame()
1490 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071491
Peter Boströmd7592132019-01-30 04:50:311492 // Make sure we do not discard the pending entry for a different ongoing
1493 // navigation when a same document commit comes in unexpectedly from the
1494 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1495 // other navigation types. See https://crbug.com/900036.
1496 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061497 bool keep_pending_entry =
1498 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101499 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061500 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311501
Miyoung Shin3299cbf2022-11-22 01:41:101502 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061503 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491504 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051505 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001506 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431507 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061508 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491509 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1510 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001511 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431512 break;
[email protected]8ff00d72012-10-23 19:12:211513 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471514 RendererDidNavigateNewSubframe(
1515 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001516 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431517 break;
[email protected]8ff00d72012-10-23 19:12:211518 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391519 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251520 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001521 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081522 // We don't send a notification about auto-subframe PageState during
1523 // UpdateStateForFrame, since it looks like nothing has changed. Send
1524 // it here at commit time instead.
1525 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431526 return false;
creis59d5a47cb2016-08-24 23:57:191527 }
[email protected]e9ba4472008-09-14 15:42:431528 break;
Aran Gilman37d11632019-10-08 23:07:151529 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431530 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151531 break;
[email protected]765b35502008-08-21 00:51:201532 }
1533
[email protected]688aa65c62012-09-28 04:32:221534 // At this point, we know that the navigation has just completed, so
1535 // record the time.
1536 //
1537 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261538 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331539 base::Time timestamp =
1540 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1541 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131542 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221543
Peter Boströmd7592132019-01-30 04:50:311544 // If we aren't keeping the pending entry, there shouldn't be one at this
1545 // point. Clear it again in case any error cases above forgot to do so.
1546 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1547 // been cleared instead of protecting against it.
1548 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551549 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141550
[email protected]e9ba4472008-09-14 15:42:431551 // All committed entries should have nonempty content state so WebKit doesn't
1552 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471553 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321554 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221555 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441556 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141557
Alexander Timind2f2e4f22019-04-02 20:04:531558 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1559 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281560 if (back_forward_cache_metrics &&
1561 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531562 active_entry->set_back_forward_cache_metrics(
1563 std::move(back_forward_cache_metrics));
1564 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281565
1566 // `back_forward_cache_metrics()` may return null as we do not record
1567 // back-forward cache metrics for navigations in non-primary frame trees.
1568 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141569 // TODO(https://crbug.com/1338089): Remove this.
1570 // These are both only available from details at this point, so we capture
1571 // them here.
1572 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101573 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141574 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1575 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281576 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1577 navigation_request,
1578 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1579 }
naskoc7533512016-05-06 17:01:121580
Charles Reisc0507202017-09-21 00:40:021581 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1582 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1583 // A mismatch can occur if the renderer lies or due to a unique name collision
1584 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121585 FrameNavigationEntry* frame_entry =
1586 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021587 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1588 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031589 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081590 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1591 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031592 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201593
1594 // Remember the bindings the renderer process has at this point, so that
1595 // we do not grant this entry additional bindings if we come back to it.
1596 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301597 }
[email protected]132e281a2012-07-31 18:32:441598
[email protected]97d8f0d2013-10-29 16:49:211599 // Once it is committed, we no longer need to track several pieces of state on
1600 // the entry.
naskoc7533512016-05-06 17:01:121601 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131602
[email protected]49bd30e62011-03-22 20:12:591603 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221604 // TODO(creis): This check won't pass for subframes until we create entries
1605 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001606 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421607 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591608
[email protected]e9ba4472008-09-14 15:42:431609 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001610 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001611 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311612 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531613
arthursonzogni7ddc6542021-04-09 09:16:501614 active_entry->SetIsOverridingUserAgent(
1615 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031616
[email protected]93f230e02011-06-01 14:40:001617 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291618
aelias100c9192017-01-13 00:01:431619 if (overriding_user_agent_changed)
1620 delegate_->UpdateOverridingUserAgent();
1621
creis03b48002015-11-04 00:54:561622 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1623 // one knows the latest NavigationEntry it is showing (whether it has
1624 // committed anything in this navigation or not). This allows things like
1625 // state and title updates from RenderFrames to apply to the latest relevant
1626 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381627 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031628 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381629 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431630
1631 if (navigation_request->IsPrerenderedPageActivation()) {
1632 BroadcastHistoryOffsetAndLength();
1633 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1634 // is activated. As a result, a "prerenderingchange" event listener sees the
1635 // history.length which is not updated yet. We should guarantee that
1636 // history's length and offset should be updated before a
1637 // "prerenderingchange" event listener runs. One possible approach is to use
1638 // the same IPC which "prerenderingchange" uses, and propagate history's
1639 // length and offset together with that.
1640 }
1641
[email protected]e9ba4472008-09-14 15:42:431642 return true;
initial.commit09911bf2008-07-26 23:55:291643}
1644
[email protected]8ff00d72012-10-23 19:12:211645NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321646 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101647 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241648 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591649 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511650 "ClassifyNavigation");
1651
avi7c6f35e2015-05-08 17:52:381652 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241653 // A new entry. We may or may not have a corresponding pending entry, and
1654 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001655 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491656 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061657 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381658 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241659 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511660 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381661 return NAVIGATION_TYPE_NEW_SUBFRAME;
1662 }
1663
Charlie Reisc0f17d2d2021-01-12 18:52:491664 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381665 DCHECK(!params.history_list_was_cleared);
1666
avi39c1edd32015-06-04 20:06:001667 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381668 // All manual subframes would be did_create_new_entry and handled above, so
1669 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081670 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1671 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381672 }
1673
Rakina Zata Amnif6950d552020-11-24 03:26:101674 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1675 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381676 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1677 // create a new page.
1678
Hayato Ito2ae49442021-07-02 02:59:251679 // This main frame navigation is not a history navigation (since
1680 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1681 // reload or a replacement navigation, which will modify the existing entry.
1682 //
Nasko Oskov332593c2018-08-16 17:21:341683 // TODO(nasko): With error page isolation, reloading an existing session
1684 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491685 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341686 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511687 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491688 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061689 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381690 }
1691
Charlie Reisf8cde712022-10-20 16:25:091692 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521693 // If the SiteInstance of the |pending_entry_| does not match the
1694 // SiteInstance that got committed, treat this as a new navigation with
1695 // replacement. This can happen if back/forward/reload encounters a server
1696 // redirect to a different site or an isolated error page gets successfully
1697 // reloaded into a different SiteInstance.
1698 if (pending_entry_->site_instance() &&
1699 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491700 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061701 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521702 }
creis77c9aa32015-09-25 19:59:421703
Nasko Oskovaee2f862018-06-15 00:05:521704 if (pending_entry_index_ == -1) {
1705 // In this case, we have a pending entry for a load of a new URL but Blink
1706 // didn't do a new navigation (params.did_create_new_entry). First check
1707 // to make sure Blink didn't treat a new cross-process navigation as
1708 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161709 // we must treat it as NEW rather than the converted reload case below,
1710 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451711 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161712 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061713 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521714 }
1715
1716 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161717 // We will create a pending entry, but NavigateWithoutEntry will convert
1718 // it to a reload since it's the same page and not create a new entry for
1719 // it. (The user doesn't want to have a new back/forward entry when they
1720 // do this.) Therefore we want to just ignore the pending entry and go
1721 // back to where we were (the "existing entry").
1722 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061723 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521724 }
avi7c6f35e2015-05-08 17:52:381725 }
1726
Rakina Zata Amni153d5702021-09-13 22:48:001727 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381728 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491729 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1730 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161731 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061732 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381733 }
1734
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121735 if (navigation_request->DidEncounterError() &&
1736 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101737 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381738 // If the renderer was going to a new pending entry that got cleared because
1739 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491740 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381741 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511742 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491743 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061744 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381745 }
1746
Charlie Reisc0f17d2d2021-01-12 18:52:491747 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101748 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511749 trace_return.traced_value()->SetInteger("existing_entry_index",
1750 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381751 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441752 // The renderer has committed a navigation to an entry that no longer
1753 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491754 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061755 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381756 }
1757
avi7c6f35e2015-05-08 17:52:381758 // Since we weeded out "new" navigations above, we know this is an existing
1759 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491760 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061761 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381762}
1763
Rakina Zata Amni3460d382021-10-29 00:43:371764void NavigationControllerImpl::UpdateNavigationEntryDetails(
1765 NavigationEntryImpl* entry,
1766 RenderFrameHostImpl* rfh,
1767 const mojom::DidCommitProvisionalLoadParams& params,
1768 NavigationRequest* request,
1769 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001770 bool is_new_entry,
1771 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371772 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171773 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371774 entry->AddOrUpdateFrameEntry(
1775 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571776 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371777 rfh->GetSiteInstance(), nullptr, params.url,
1778 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171779 Referrer(*params.referrer),
1780 request ? request->common_params().initiator_origin : params.origin,
W. James MacLean23e90a12022-12-21 04:38:211781 request ? request->common_params().initiator_base_url : absl::nullopt,
Rakina Zata Amniafd3c6582021-11-30 06:19:171782 request ? request->GetRedirectChain() : redirects, params.page_state,
1783 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
1784 (request && request->web_bundle_navigation_info())
Rakina Zata Amni3460d382021-10-29 00:43:371785 ? request->web_bundle_navigation_info()->Clone()
1786 : nullptr,
Rakina Zata Amniafd3c6582021-11-30 06:19:171787 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371788 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171789 rfh, request && request->IsSameDocument(),
1790 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371791
1792 if (rfh->GetParent()) {
1793 // Only modify the NavigationEntry for main frame navigations.
1794 return;
1795 }
1796 if (entry->update_virtual_url_with_url())
1797 UpdateVirtualURLToURL(entry, params.url);
1798 // Don't use the page type from the pending entry. Some interstitial page
1799 // may have set the type to interstitial. Once we commit, however, the page
1800 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171801 entry->set_page_type((request && request->DidEncounterError())
1802 ? PAGE_TYPE_ERROR
1803 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431804 if (commit_details && commit_details->should_stay_as_initial_entry) {
1805 // Retain the "initial NavigationEntry" status.
1806 if (request->IsSameDocument()) {
1807 // If this is for a same-document navigation, the NavigationEntry must be
1808 // reused and should already be marked as the initial NavigationEntry.
1809 DCHECK(entry->IsInitialEntry());
1810 } else {
1811 // If this is for a cross-document navigation, it can be caused by a
1812 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1813 // "for synchronous about:blank" in the latter case, and also when it is
1814 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1815 // is not for a synchronous about:blank commit.
1816 NavigationEntryImpl::InitialNavigationEntryState new_state =
1817 NavigationEntryImpl::InitialNavigationEntryState::
1818 kInitialNotForSynchronousAboutBlank;
1819 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1820 request->is_synchronous_renderer_commit()) {
1821 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1822 kInitialForSynchronousAboutBlank;
1823 }
1824 entry->set_initial_navigation_entry_state(new_state);
1825 }
1826 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1827 // Remove the "initial NavigationEntry" status.
1828 entry->set_initial_navigation_entry_state(
1829 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001830 }
Rakina Zata Amniddf10502022-01-15 02:56:551831
Rakina Zata Amni3460d382021-10-29 00:43:371832 if (is_new_entry) {
1833 // Some properties of the NavigationEntry are only set when the entry is
1834 // new (we aren't reusing it).
1835 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171836 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1837 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371838 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1839 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1840 } else {
1841 // We are reusing the NavigationEntry. The site instance will normally be
1842 // the same except for a few cases:
1843 // 1) session restore, when no site instance will be assigned or
1844 // 2) redirect, when the site instance is reset.
1845 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1846 entry->site_instance() == rfh->GetSiteInstance());
1847 }
1848}
1849
Rakina Zata Amniafd3c6582021-11-30 06:19:171850void NavigationControllerImpl::CreateInitialEntry() {
1851 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031852 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171853 auto params = mojom::DidCommitProvisionalLoadParams::New();
1854 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1855 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1856 // before we have initial NavigationEntries.
1857 params->url = GURL::EmptyGURL();
1858 params->http_status_code = 0;
1859 params->url_is_unreachable = false;
1860 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171861 params->post_id = -1;
1862 params->embedding_token = base::UnguessableToken::Create();
1863 params->navigation_token = base::UnguessableToken::Create();
1864 params->did_create_new_entry = true;
1865 params->origin = rfh->GetLastCommittedOrigin();
1866 params->should_update_history = true;
1867 params->item_sequence_number = 0;
1868 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151869 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171870 params->transition = is_in_fenced_frame_tree
1871 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1872 : ui::PAGE_TRANSITION_LINK;
1873 params->referrer = blink::mojom::Referrer::New();
1874
1875 // Create and insert the initial NavigationEntry.
1876 auto new_entry = std::make_unique<NavigationEntryImpl>(
1877 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
W. James MacLean78e2f872023-01-24 17:59:381878 rfh->GetLastCommittedOrigin(), rfh->GetInheritedBaseUrl(),
W. James MacLean23e90a12022-12-21 04:38:211879 std::u16string() /* title */, ui::PAGE_TRANSITION_TYPED,
1880 false /* renderer_initiated */, nullptr /* blob_url_loader_factory */,
1881 true /* is_initial_entry */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171882 UpdateNavigationEntryDetails(
1883 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001884 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1885 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171886
1887 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1888 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001889 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171890}
1891
Charlie Reisc0f17d2d2021-01-12 18:52:491892void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321893 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071894 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361895 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441896 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471897 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001898 NavigationRequest* request,
1899 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571900 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071901 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451902 request->common_params().initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:211903 const absl::optional<GURL>& initiator_base_url =
1904 request->common_params().initiator_base_url;
Lukasz Anforowicz435bcb582019-07-12 20:50:061905
creisf49dfc92016-07-26 17:05:181906 // First check if this is an in-page navigation. If so, clone the current
1907 // entry instead of looking at the pending entry, because the pending entry
1908 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451909 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301910 FrameNavigationEntry* previous_frame_entry =
1911 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451912 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481913 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571914 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081915 rfh->GetSiteInstance(), nullptr, params.url,
1916 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:211917 Referrer(*params.referrer), initiator_origin, initiator_base_url,
Rakina Zata Amni82fafba2021-03-11 07:07:091918 request->GetRedirectChain(), params.page_state, params.method,
1919 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:391920 nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481921 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391922 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301923 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571924 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301925 // FrameNavigationEntry.
1926 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571927 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031928
creisf49dfc92016-07-26 17:05:181929 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031930 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521931 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1932 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571933 // TODO(jam): we had one report of this with a URL that was redirecting to
1934 // only tildes. Until we understand that better, don't copy the cert in
1935 // this case.
1936 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571937 }
creisf49dfc92016-07-26 17:05:181938
Patrick Monette50e8bd82019-06-13 22:40:451939 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1940 // that |frame_entry| should now have a reference count of exactly 2: one
1941 // due to the local variable |frame_entry|, and another due to |new_entry|
1942 // also retaining one. This should never fail, because it's the main frame.
1943 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181944 }
1945
Harkiran Bolaria59290d62021-03-17 01:53:011946 // If this is an activation navigation from a prerendered page, transfer the
1947 // new entry from an entry already created and stored in the
1948 // NavigationRequest. |new_entry| will not have been set prior to this as
1949 // |is_same_document| is mutually exclusive with
1950 // |IsPrerenderedPageActivation|.
1951 if (request->IsPrerenderedPageActivation()) {
1952 DCHECK(!is_same_document);
1953 DCHECK(!new_entry);
1954 new_entry = request->TakePrerenderNavigationEntry();
1955 DCHECK(new_entry);
1956 }
1957
Charlie Reisc0f17d2d2021-01-12 18:52:491958 // Only make a copy of the pending entry if it is appropriate for the new
1959 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451960 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041961 // 1. The SiteInstance hasn't been assigned to something else.
1962 // 2. The pending entry was intended as a new entry, rather than being a
1963 // history navigation that was interrupted by an unrelated,
1964 // renderer-initiated navigation.
1965 // TODO(csharrison): Investigate whether we can remove some of the coarser
1966 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451967 if (!new_entry && PendingEntryMatchesRequest(request) &&
1968 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341969 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431970 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351971 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431972
Camille Lamy62b826012019-02-26 09:15:471973 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451974 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181975 }
1976
Charlie Reisc0f17d2d2021-01-12 18:52:491977 // For cross-document commits with no matching pending entry, create a new
1978 // entry.
creisf49dfc92016-07-26 17:05:181979 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061980 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:071981 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
W. James MacLean23e90a12022-12-21 04:38:211982 initiator_origin, initiator_base_url,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:581983 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:451984 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:171985 nullptr, // blob_url_loader_factory
1986 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:241987
1988 // Find out whether the new entry needs to update its virtual URL on URL
1989 // change and set up the entry accordingly. This is needed to correctly
1990 // update the virtual URL when replaceState is called after a pushState.
1991 GURL url = params.url;
1992 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:491993 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:411994 // update the virtual URL based on the new URL. For example, this is needed
1995 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1996 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:371997 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1998 &url, browser_context_, &needs_update);
1999 new_entry->set_update_virtual_url_with_url(needs_update);
2000
Camille Lamy62b826012019-02-26 09:15:472001 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452002 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:432003 }
2004
Harkiran Bolaria59290d62021-03-17 01:53:012005 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
2006 // for prerendered contents, if any. This is because prerendering/activation
2007 // technically won't be creating a new document. Unlike BFCache, prerendering
2008 // creates a new NavigationEntry rather than using an existing one.
2009 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372010 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2011 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002012 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082013
Harkiran Bolaria59290d62021-03-17 01:53:012014 // history.pushState() is classified as a navigation to a new page, but sets
2015 // is_same_document to true. In this case, we already have the title and
2016 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452017 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012018 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2019 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2020 }
[email protected]3a868f212014-08-09 10:41:192021 }
[email protected]ff64b3e2014-05-31 04:07:332022
[email protected]60d6cca2013-04-30 08:47:132023 DCHECK(!params.history_list_was_cleared || !replace_entry);
2024 // The browser requested to clear the session history when it initiated the
2025 // navigation. Now we know that the renderer has updated its state accordingly
2026 // and it is safe to also clear the browser side history.
2027 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552028 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132029 entries_.clear();
2030 last_committed_entry_index_ = -1;
2031 }
2032
Nasko Oskovaee2f862018-06-15 00:05:522033 // If this is a new navigation with replacement and there is a
2034 // pending_entry_ which matches the navigation reported by the renderer
2035 // process, then it should be the one replaced, so update the
2036 // last_committed_entry_index_ to use it.
2037 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092038 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522039 last_committed_entry_index_ = pending_entry_index_;
2040 }
2041
Alexander Timine3ec4192020-04-20 16:39:402042 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412043 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402044 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052045
Yuzu Saijoa725585f2022-11-28 04:14:032046 // If this is a history navigation and the old entry has an existing
2047 // back/forward cache metrics object, keep using the old one so that the
2048 // reasons logged from the last time the page navigated gets preserved.
2049 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2050 request)) {
2051 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2052 // because some tests do not have a pending entry.
2053 NavigationEntryImpl* entry =
2054 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2055 if (entry && entry->back_forward_cache_metrics()) {
2056 scoped_refptr<BackForwardCacheMetrics> metrics =
2057 entry->TakeBackForwardCacheMetrics();
2058 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2059 }
2060 }
2061
Carlos IL42b416592019-10-07 23:10:362062 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312063 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152064 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432065}
2066
Charlie Reisc0f17d2d2021-01-12 18:52:492067void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322068 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072069 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362070 bool is_same_document,
jam48cea9082017-02-15 06:13:292071 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452072 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002073 bool keep_pending_entry,
2074 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562075 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2076 << "that a last committed entry exists.";
2077
[email protected]e9ba4472008-09-14 15:42:432078 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002079 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432080
Charlie Reis7e2cb6d2021-01-26 01:27:162081 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002082 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162083 // We're guaranteed to have a last committed entry if intended_as_new_entry
2084 // is true.
avicbdc4c12015-07-01 16:07:112085 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162086
2087 // If the NavigationRequest matches a new pending entry and is classified as
2088 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2089 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092090 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162091 // Note: The pending entry will usually have a real ReloadType here, but
2092 // it can still be ReloadType::NONE in cases that
2093 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2094
2095 // If we classified this correctly, the SiteInstance should not have
2096 // changed.
2097 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2098
2099 // For converted reloads, we assign the entry's unique ID to be that of
2100 // the new one. Since this is always the result of a user action, we want
2101 // to dismiss infobars, etc. like a regular user-initiated navigation.
2102 entry->set_unique_id(pending_entry_->GetUniqueID());
2103
2104 // The extra headers may have changed due to reloading with different
2105 // headers.
2106 entry->set_extra_headers(pending_entry_->extra_headers());
2107 }
2108 // Otherwise, this was intended as a new entry but the pending entry was
2109 // lost in the meantime and no new entry was created. We are stuck at the
2110 // last committed entry.
2111
2112 // Even if this is a converted reload from pressing enter in the omnibox,
2113 // the server could redirect, requiring an update to the SSL status. If this
2114 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452115 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162116 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472117 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452118 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162119 }
Rakina Zata Amnif6950d552020-11-24 03:26:102120 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112121 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102122 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b90ce2016-09-01 16:58:162123
eugenebut604866f2017-05-10 21:35:362124 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452125 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362126 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2127 // this was a restored same document navigation entry, then it won't have
2128 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2129 // navigated it.
jam48cea9082017-02-15 06:13:292130 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522131 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2132 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292133 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2134 was_restored) {
2135 entry->GetSSL() = last_entry->GetSSL();
2136 }
2137 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452138 // In rapid back/forward navigations |request| sometimes won't have a cert
2139 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192140 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452141 if (request->GetSSLInfo().has_value() &&
2142 request->GetSSLInfo()->is_valid()) {
2143 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522144 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2145 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192146 entry->GetSSL() = SSLStatus();
2147 }
jam48cea9082017-02-15 06:13:292148 }
avicbdc4c12015-07-01 16:07:112149 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272150 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572151 // navigations that are EXISTING_ENTRY are same-document navigations that
2152 // result in replacement (e.g. history.replaceState(), location.replace(),
2153 // forced replacements for trivial session history contexts). For these
2154 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112155 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102156
Mikel Astizba9cf2fd2017-12-17 10:38:102157 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2158 // to avoid misleading interpretations (e.g. URLs paired with
2159 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2160 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2161 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2162
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572163 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102164
eugenebut604866f2017-05-10 21:35:362165 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452166 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362167 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472168 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452169 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112170 }
2171 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432172
Rakina Zata Amni3460d382021-10-29 00:43:372173 UpdateNavigationEntryDetails(entry, rfh, params, request,
2174 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002175 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302176
[email protected]5ccd4dc2012-10-24 02:28:142177 // The redirected to page should not inherit the favicon from the previous
2178 // page.
eugenebut604866f2017-05-10 21:35:362179 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482180 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142181
Peter Boströmd7592132019-01-30 04:50:312182 // We should also usually discard the pending entry if it corresponds to a
2183 // different navigation, since that one is now likely canceled. In rare
2184 // cases, we leave the pending entry for another navigation in place when we
2185 // know it is still ongoing, to avoid a flicker in the omnibox (see
2186 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432187 //
2188 // Note that we need to use the "internal" version since we don't want to
2189 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312190 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002191 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392192
Carlos IL4dea8902020-05-26 15:14:292193 // Update the last committed index to reflect the committed entry.
avicbdc4c12015-07-01 16:07:112194 last_committed_entry_index_ = GetIndexOfEntry(entry);
[email protected]e9ba4472008-09-14 15:42:432195}
2196
[email protected]d202a7c2012-01-04 07:53:472197void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322198 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072199 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362200 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472201 bool replace_entry,
2202 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002203 NavigationRequest* request,
2204 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262205 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2206 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552207 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2208 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112209
[email protected]e9ba4472008-09-14 15:42:432210 // Manual subframe navigations just get the current entry cloned so the user
2211 // can go back or forward to it. The actual subframe information will be
2212 // stored in the page state for each of those entries. This happens out of
2213 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092214 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2215 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382216
Mikel Astizba9cf2fd2017-12-17 10:38:102217 // The DCHECK below documents the fact that we don't know of any situation
2218 // where |replace_entry| is true for subframe navigations. This simplifies
2219 // reasoning about the replacement struct for subframes (see
2220 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2221 DCHECK(!replace_entry);
2222
Patrick Monette50e8bd82019-06-13 22:40:452223 // This FrameNavigationEntry might not end up being used in the
2224 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072225 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452226 request->common_params().initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212227 const absl::optional<GURL>& initiator_base_url =
2228 request->common_params().initiator_base_url;
Nate Chapin63db0d12022-01-20 22:03:302229 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2230 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2231 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572232 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302233 if (is_same_document) {
2234 FrameNavigationEntry* previous_frame_entry =
2235 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572236 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302237 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572238 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302239 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572240 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302241 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572242 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302243 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572244 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302245 policy_container_policies->referrer_policy);
2246 }
2247
Patrick Monette50e8bd82019-06-13 22:40:452248 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482249 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572250 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082251 rfh->GetSiteInstance(), nullptr, params.url,
2252 GetCommittedOriginForFrameEntry(params, request),
W. James MacLean23e90a12022-12-21 04:38:212253 Referrer(*params.referrer), initiator_origin, initiator_base_url,
2254 request->GetRedirectChain(), params.page_state, params.method,
2255 params.post_id, nullptr /* blob_url_loader_factory */,
Tsuyoshi Horo0c605782020-05-27 00:21:032256 request->web_bundle_navigation_info()
2257 ? request->web_bundle_navigation_info()->Clone()
Antonio Sartori78a749f2020-11-30 12:03:392258 : nullptr,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482259 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572260 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032261
creisce0ef3572017-01-26 17:53:082262 std::unique_ptr<NavigationEntryImpl> new_entry =
2263 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452264 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032265 frame_tree_->root());
creise062d542015-08-25 02:01:552266
Alexander Timine3ec4192020-04-20 16:39:402267 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412268 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402269 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472270
creisce0ef3572017-01-26 17:53:082271 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452272 // to replace, which can happen due to a unique name change. See
2273 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2274 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382275
Dave Tapuska87696ae2021-11-18 18:48:312276 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152277 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432278}
2279
[email protected]d202a7c2012-01-04 07:53:472280bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322281 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072282 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392283 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252284 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002285 NavigationRequest* request,
2286 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292287 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2288 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2289
[email protected]e9ba4472008-09-14 15:42:432290 // We're guaranteed to have a previously committed entry, and we now need to
2291 // handle navigation inside of a subframe in it without creating a new entry.
2292 DCHECK(GetLastCommittedEntry());
2293
creis913c63ce2016-07-16 19:52:522294 // For newly created subframes, we don't need to send a commit notification.
2295 // This is only necessary for history navigations in subframes.
2296 bool send_commit_notification = false;
2297
Rakina Zata Amnif6950d552020-11-24 03:26:102298 // If |nav_entry_id| is non-zero and matches an existing entry, this
2299 // is a history navigation. Update the last committed index accordingly. If
2300 // we don't recognize the |nav_entry_id|, it might be a recently
2301 // pruned entry. We'll handle it below.
2302 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2303 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472304 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062305 // Make sure that a subframe commit isn't changing the main frame's
2306 // origin. Otherwise the renderer process may be confused, leading to a
2307 // URL spoof. We can't check the path since that may change
2308 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572309 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2310 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242311 // We should use checks similar to RenderFrameHostImpl's
2312 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2313 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572314 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2315 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2316 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2317 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522318 current_top_url.DeprecatedGetOriginAsURL() !=
2319 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442320 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512321 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062322 }
creis3cdc3b02015-05-29 23:00:472323
creis913c63ce2016-07-16 19:52:522324 // We only need to discard the pending entry in this history navigation
2325 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062326 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002327 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522328
2329 // History navigations should send a commit notification.
2330 send_commit_notification = true;
avi98405c22015-05-21 20:47:062331 }
[email protected]e9ba4472008-09-14 15:42:432332 }
[email protected]f233e4232013-02-23 00:55:142333
creisce0ef3572017-01-26 17:53:082334 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2335 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372336 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2337 // exists), or we may want to clobber it and create a new one. We update in
2338 // cases where the corresponding FrameNavigationEntry is conceptually similar
2339 // to the document described by the commit params: same-document
2340 // navigations, history traversal to an existing entry, and reloads (including
2341 // a "soft reload" where we navigate to the same url without flagging it as a
2342 // reload). But in the case of a different document that is not logically
2343 // related to the committed FrameNavigationEntry's document (cross-document,
2344 // not same url, not a reload, not a history traversal), we replace rather
2345 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252346 //
Nate Chapin9f169072021-06-09 19:32:372347 // In the case where we update, the FrameNavigationEntry will potentially be
2348 // shared across multiple NavigationEntries, and any updates will be reflected
2349 // in all of those NavigationEntries. In the replace case, any existing
2350 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252351 //
2352 // When navigating away from the initial empty document, we also update rather
2353 // than replace. Either update or replace will overwrite the initial empty
2354 // document state for |last_committed|, but if the FrameNavigationEntry for
2355 // the initial empty document is shared across multiple NavigationEntries (due
2356 // to a navigation in another frame), we want to make sure we overwrite the
2357 // initial empty document state everywhere this FrameNavigationEntry is used,
2358 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452359 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372360 FrameNavigationEntry* last_committed_frame_entry =
2361 last_committed->GetFrameEntry(rfh->frame_tree_node());
2362 NavigationEntryImpl::UpdatePolicy update_policy =
2363 NavigationEntryImpl::UpdatePolicy::kUpdate;
2364 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312365 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372366 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252367 last_committed_frame_entry->url() != params.url &&
2368 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372369 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2370 }
2371
Rakina Zata Amni3460d382021-10-29 00:43:372372 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002373 update_policy, false /* is_new_entry */,
2374 commit_details);
creis625a0c7d2015-03-24 23:17:122375
creis913c63ce2016-07-16 19:52:522376 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432377}
2378
[email protected]d202a7c2012-01-04 07:53:472379int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232380 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032381 for (size_t i = 0; i < entries_.size(); ++i) {
2382 if (entries_[i].get() == entry)
2383 return i;
2384 }
2385 return -1;
[email protected]765b35502008-08-21 00:51:202386}
2387
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572388void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242389 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572390 NavigationControllerImpl* source =
2391 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572392 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382393 DCHECK_EQ(1, GetEntryCount());
2394 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472395 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172396 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572397
Francois Dorayeaace782017-06-21 16:37:242398 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442399 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572400 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572401
Fergal Dalya1d569972021-03-16 03:24:532402 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302403 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532404 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2405 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302406 }
[email protected]4e6419c2010-01-15 04:50:342407
Lukasz Anforowicz0de0f452020-12-02 19:57:152408 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572409}
2410
Aran Gilman37d11632019-10-08 23:07:152411void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2412 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162413 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012414 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162415
[email protected]d202a7c2012-01-04 07:53:472416 NavigationControllerImpl* source =
2417 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252418
avi2b177592014-12-10 02:08:022419 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012420 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252421
[email protected]474f8512013-05-31 22:31:162422 // We now have one entry, possibly with a new pending entry. Ensure that
2423 // adding the entries from source won't put us over the limit.
2424 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572425 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572426 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252427
Carlos IL4dea8902020-05-26 15:14:292428 // Insert the entries from source. Ignore any pending entry, since it has not
2429 // committed in source.
[email protected]474f8512013-05-31 22:31:162430 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172431 DCHECK_NE(max_source_index, -1);
2432 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572433
2434 // Ignore the source's current entry if merging with replacement.
2435 // TODO(davidben): This should preserve entries forward of the current
2436 // too. http://crbug.com/317872
2437 if (replace_entry && max_source_index > 0)
2438 max_source_index--;
2439
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572440 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252441
2442 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552443 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142444
Hayato Ito2c8c08d02021-06-23 03:38:432445 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252446}
2447
[email protected]79368982013-11-13 01:11:012448bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162449 // If there is no last committed entry, we cannot prune. Even if there is a
2450 // pending entry, it may not commit, leaving this WebContents blank, despite
2451 // possibly giving it new entries via CopyStateFromAndPrune.
2452 if (last_committed_entry_index_ == -1)
2453 return false;
[email protected]9350602e2013-02-26 23:27:442454
[email protected]474f8512013-05-31 22:31:162455 // We cannot prune if there is a pending entry at an existing entry index.
2456 // It may not commit, so we have to keep the last committed entry, and thus
2457 // there is no sensible place to keep the pending entry. It is ok to have
2458 // a new pending entry, which can optionally commit as a new navigation.
2459 if (pending_entry_index_ != -1)
2460 return false;
2461
[email protected]474f8512013-05-31 22:31:162462 return true;
2463}
2464
[email protected]79368982013-11-13 01:11:012465void NavigationControllerImpl::PruneAllButLastCommitted() {
2466 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162467
avi2b177592014-12-10 02:08:022468 DCHECK_EQ(0, last_committed_entry_index_);
2469 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442470
Hayato Ito2c8c08d02021-06-23 03:38:432471 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442472}
2473
[email protected]79368982013-11-13 01:11:012474void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162475 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012476 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262477
Nate Chapin9eb16be72022-09-23 22:54:312478 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2479
[email protected]474f8512013-05-31 22:31:162480 // Erase all entries but the last committed entry. There may still be a
2481 // new pending entry after this.
2482 entries_.erase(entries_.begin(),
2483 entries_.begin() + last_committed_entry_index_);
2484 entries_.erase(entries_.begin() + 1, entries_.end());
2485 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262486}
2487
Christian Dullweber1af31e62018-02-22 11:49:482488void NavigationControllerImpl::DeleteNavigationEntries(
2489 const DeletionPredicate& deletionPredicate) {
2490 // It is up to callers to check the invariants before calling this.
2491 CHECK(CanPruneAllButLastCommitted());
2492 std::vector<int> delete_indices;
2493 for (size_t i = 0; i < entries_.size(); i++) {
2494 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572495 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482496 delete_indices.push_back(i);
2497 }
2498 }
2499 if (delete_indices.empty())
2500 return;
2501
2502 if (delete_indices.size() == GetEntryCount() - 1U) {
2503 PruneAllButLastCommitted();
2504 } else {
2505 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382506 for (const auto& index : base::Reversed(delete_indices)) {
2507 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482508 }
Hayato Ito2c8c08d02021-06-23 03:38:432509 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482510 }
2511 delegate()->NotifyNavigationEntriesDeleted();
2512}
2513
Shivani Sharma883f5f32019-02-12 18:20:012514bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2515 auto* entry = GetEntryAtIndex(index);
2516 return entry && entry->should_skip_on_back_forward_ui();
2517}
2518
Carlos Caballero35ce710c2019-09-19 10:59:452519BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2520 return back_forward_cache_;
2521}
2522
clamy987a3752018-05-03 17:36:262523void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2524 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2525 // progress, since this will cause a use-after-free. (We only allow this
2526 // when the tab is being destroyed for shutdown, since it won't return to
2527 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032528 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262529
2530 if (was_failure && pending_entry_) {
2531 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2532 } else {
2533 failed_pending_entry_id_ = 0;
2534 }
2535
2536 if (pending_entry_) {
2537 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332538 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262539 pending_entry_index_ = -1;
2540 pending_entry_ = nullptr;
2541 }
arthursonzogni66f711c2019-10-08 14:40:362542
2543 // Ensure any refs to the current pending entry are ignored if they get
2544 // deleted, by clearing the set of known refs. All future pending entries will
2545 // only be affected by new refs.
2546 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262547}
2548
2549void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2550 if (pending_entry_)
2551 pending_entry_->set_ssl_error(error);
2552}
2553
Xiaohan Wang7f8052e02022-01-14 18:44:282554#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422555// static
2556bool NavigationControllerImpl::ValidateDataURLAsString(
2557 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2558 if (!data_url_as_string)
2559 return false;
2560
2561 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2562 return false;
2563
2564 // The number of characters that is enough for validating a data: URI.
2565 // From the GURL's POV, the only important part here is scheme, it doesn't
2566 // check the actual content. Thus we can take only the prefix of the url, to
2567 // avoid unneeded copying of a potentially long string.
2568 const size_t kDataUriPrefixMaxLen = 64;
2569 GURL data_url(
2570 std::string(data_url_as_string->front_as<char>(),
2571 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2572 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2573 return false;
2574
2575 return true;
2576}
2577#endif
2578
Shivani Sharma194877032019-03-07 17:52:472579void NavigationControllerImpl::NotifyUserActivation() {
2580 // When a user activation occurs, ensure that all adjacent entries for the
2581 // same document clear their skippable bit, so that the history manipulation
2582 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372583 if (base::FeatureList::IsEnabled(
2584 features::kDebugHistoryInterventionNoUserActivation)) {
2585 return;
2586 }
2587
Shivani Sharmac4cc8922019-04-18 03:11:172588 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472589}
2590
clamy987a3752018-05-03 17:36:262591bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2592 RenderFrameHostImpl* render_frame_host,
Julie Jeongeun Kimed2e5ba72019-09-12 10:14:172593 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client) {
clamy987a3752018-05-03 17:36:262594 NavigationEntryImpl* entry =
2595 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2596 if (!entry)
2597 return false;
2598
2599 FrameNavigationEntry* frame_entry =
2600 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2601 if (!frame_entry)
2602 return false;
2603
Nate Chapin45f620582021-09-30 17:45:432604 // |is_browser_initiated| is false here because a navigation in a new subframe
2605 // always begins with renderer action (i.e., an HTML element being inserted
2606 // into the DOM), so it is always renderer-initiated.
Camille Lamy5193caa2018-10-12 11:59:422607 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572608 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232609 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432610 true /* is_history_navigation_in_new_child */,
2611 false /* is_browser_initiated */);
clamyea99ea12018-05-28 13:54:232612
2613 if (!request)
2614 return false;
2615
arthursonzognif046d4a2019-12-12 19:08:102616 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412617
Lukasz Anforowicz9ee83c272020-12-01 20:14:052618 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2619 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232620
2621 return true;
clamy987a3752018-05-03 17:36:262622}
2623
Tsuyoshi Horo52fd08e2020-07-07 07:03:452624bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2625 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2626 if (!entry)
2627 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432628
2629 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2630 // We should never navigate to an existing initial NavigationEntry that is
2631 // the initial NavigationEntry for the initial empty document that hasn't
2632 // been overridden by the synchronous about:blank commit, to preserve
2633 // legacy behavior where trying to reload when the main frame is on the
2634 // initial empty document won't result in a navigation. See also
2635 // https://crbug.com/1277414.
2636 return false;
2637 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452638 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2639 if (!frame_entry)
2640 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142641 ReloadType reload_type = ReloadType::NORMAL;
2642 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452643 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142644 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452645 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432646 false /* is_history_navigation_in_new_child */,
2647 true /* is_browser_initiated */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452648 if (!request)
2649 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052650 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452651 return true;
2652}
2653
clamy987a3752018-05-03 17:36:262654void NavigationControllerImpl::NavigateFromFrameProxy(
2655 RenderFrameHostImpl* render_frame_host,
2656 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022657 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452658 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072659 const absl::optional<url::Origin>& initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212660 const absl::optional<GURL>& initiator_base_url,
clamy987a3752018-05-03 17:36:262661 bool is_renderer_initiated,
2662 SiteInstance* source_site_instance,
2663 const Referrer& referrer,
2664 ui::PageTransition page_transition,
2665 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252666 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262667 const std::string& method,
2668 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092669 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142670 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212671 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502672 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392673 const absl::optional<blink::Impression>& impression,
Yao Xiao720ef9d62022-12-09 05:18:292674 blink::mojom::NavigationInitiatorActivationAndAdStatus
2675 initiator_activation_and_ad_status,
Nan Lin944e9b4e2022-04-12 13:51:222676 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492677 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462678 bool is_unfenced_top_navigation,
2679 bool force_new_browsing_instance) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582680 if (is_renderer_initiated)
2681 DCHECK(initiator_origin.has_value());
2682
clamy987a3752018-05-03 17:36:262683 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582684
Rakina Zata Amni2322f4f82022-01-24 13:24:242685 // Don't allow an entry replacement if there is no entry to replace.
2686 // http://crbug.com/457149
2687 if (GetEntryCount() == 0)
2688 should_replace_current_entry = false;
2689
clamy987a3752018-05-03 17:36:262690 // Create a NavigationEntry for the transfer, without making it the pending
2691 // entry. Subframe transfers should have a clone of the last committed entry
2692 // with a FrameNavigationEntry for the target frame. Main frame transfers
2693 // should have a new NavigationEntry.
2694 // TODO(creis): Make this unnecessary by creating (and validating) the params
2695 // directly, passing them to the destination RenderFrameHost. See
2696 // https://crbug.com/536906.
2697 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262698 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262699 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452700 DCHECK(GetLastCommittedEntry());
2701 entry = GetLastCommittedEntry()->Clone();
2702 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172703 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2704 // Renderer-initiated navigation that target a remote frame are currently
2705 // classified as browser-initiated when this one has already navigated.
2706 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372707 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2708 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2709 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2710 // same-document navigation), they will still be present in the
2711 // committed NavigationEntry that will be referenced to construct the new
2712 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262713 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082714 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582715 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072716 absl::nullopt /* commit_origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212717 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Antonio Sartori78a749f2020-11-30 12:03:392718 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482719 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542720 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262721 } else {
2722 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172723 // If `node` is the outermost main frame, it rewrites a virtual url in order
2724 // to adjust the original input url if needed. For inner frames such as
2725 // fenced frames or subframes, they don't rewrite urls as the urls are not
2726 // input urls by users.
2727 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy987a3752018-05-03 17:36:262728 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
W. James MacLean23e90a12022-12-21 04:38:212729 url, referrer, initiator_origin, initiator_base_url,
2730 source_site_instance, page_transition, is_renderer_initiated,
2731 extra_headers, browser_context_, blob_url_loader_factory,
2732 rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262733 entry->root_node()->frame_entry->set_source_site_instance(
2734 static_cast<SiteInstanceImpl*>(source_site_instance));
2735 entry->root_node()->frame_entry->set_method(method);
2736 }
clamy987a3752018-05-03 17:36:262737
Camille Lamy5193caa2018-10-12 11:59:422738 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452739 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262740 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422741 override_user_agent = true;
clamy987a3752018-05-03 17:36:262742 }
2743 // TODO(creis): Set user gesture and intent received timestamp on Android.
2744
2745 // We may not have successfully added the FrameNavigationEntry to |entry|
2746 // above (per https://crbug.com/608402), in which case we create it from
2747 // scratch. This works because we do not depend on |frame_entry| being inside
2748 // |entry| during NavigateToEntry. This will go away when we shortcut this
2749 // further in https://crbug.com/536906.
2750 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2751 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452752 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082753 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582754 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072755 absl::nullopt /* origin */, referrer, initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:212756 initiator_base_url, std::vector<GURL>(), blink::PageState(), method, -1,
Rakina Zata Amni3a1c0ec2021-04-15 03:35:122757 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482758 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302759 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572760 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262761 }
2762
Camille Lamy5193caa2018-10-12 11:59:422763 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022764 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452765 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292766 params.initiator_origin = initiator_origin;
W. James MacLean23e90a12022-12-21 04:38:212767 params.initiator_base_url = initiator_base_url;
Camille Lamy5193caa2018-10-12 11:59:422768 params.source_site_instance = source_site_instance;
2769 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2770 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032771 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422772 params.referrer = referrer;
2773 /* params.redirect_chain: skip */
2774 params.extra_headers = extra_headers;
2775 params.is_renderer_initiated = is_renderer_initiated;
2776 params.override_user_agent = UA_OVERRIDE_INHERIT;
2777 /* params.base_url_for_data_url: skip */
2778 /* params.virtual_url_for_data_url: skip */
2779 /* params.data_url_as_string: skip */
2780 params.post_data = post_body;
2781 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582782 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422783 /* params.frame_name: skip */
2784 // TODO(clamy): See if user gesture should be propagated to this function.
2785 params.has_user_gesture = false;
2786 params.should_clear_history_list = false;
2787 params.started_from_context_menu = false;
2788 /* params.navigation_ui_data: skip */
2789 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222790 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542791 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212792 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412793 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502794 params.is_form_submission = is_form_submission;
Yao Xiao720ef9d62022-12-09 05:18:292795 params.initiator_activation_and_ad_status =
2796 initiator_activation_and_ad_status;
Camille Lamy5193caa2018-10-12 11:59:422797
2798 std::unique_ptr<NavigationRequest> request =
2799 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032800 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142801 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392802 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492803 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
2804 is_unfenced_top_navigation);
clamyea99ea12018-05-28 13:54:232805
2806 if (!request)
2807 return;
2808
Garrett Tanzerbb8db412022-09-27 21:59:462809 // Force the navigation to take place in a new browsing instance.
2810 // This is used by _unfencedTop in fenced frames to ensure that navigations
2811 // leaving the fenced context create a new browsing instance.
2812 if (force_new_browsing_instance) {
2813 request->coop_status().ForceBrowsingInstanceSwap();
2814 }
2815
Arthur Hemery948742762019-09-18 10:06:242816 // At this stage we are proceeding with this navigation. If this was renderer
2817 // initiated with user gesture, we need to make sure we clear up potential
2818 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2819 DiscardNonCommittedEntries();
2820
Lukasz Anforowicz9ee83c272020-12-01 20:14:052821 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262822}
2823
[email protected]d1198fd2012-08-13 22:50:192824void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252825 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212826 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192827 if (!session_storage_namespace)
2828 return;
2829
2830 // We can't overwrite an existing SessionStorage without violating spec.
2831 // Attempts to do so may give a tab access to another tab's session storage
2832 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152833 bool successful_insert =
2834 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252835 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052836 static_cast<SessionStorageNamespaceImpl*>(
2837 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302838 .second;
2839 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192840}
2841
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572842bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452843 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032844 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462845}
2846
Aran Gilman37d11632019-10-08 23:07:152847SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252848 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302849 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252850 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032851 DOMStorageContextWrapper* context_wrapper =
2852 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2853
2854 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252855 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032856 if (it != session_storage_namespace_map_.end()) {
2857 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152858 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2859 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472860
michaelnbacbcbd2016-02-09 00:32:032861 return it->second.get();
2862 }
2863
2864 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102865 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2866 SessionStorageNamespaceImpl::Create(context_wrapper);
2867 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2868 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252869 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102870 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302871
Daniel Murphy31bbb8b12018-02-07 21:44:102872 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302873}
2874
2875SessionStorageNamespace*
2876NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252877 return GetSessionStorageNamespace(
2878 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302879}
2880
2881const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572882NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302883 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552884}
[email protected]d202a7c2012-01-04 07:53:472885
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572886bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562887 return needs_reload_;
2888}
[email protected]a26023822011-12-29 00:23:552889
[email protected]46bb5e9c2013-10-03 22:16:472890void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412891 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2892}
2893
2894void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472895 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412896 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542897
2898 if (last_committed_entry_index_ != -1) {
2899 entries_[last_committed_entry_index_]->SetTransitionType(
2900 ui::PAGE_TRANSITION_RELOAD);
2901 }
[email protected]46bb5e9c2013-10-03 22:16:472902}
2903
[email protected]d202a7c2012-01-04 07:53:472904void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572905 DCHECK_LT(index, GetEntryCount());
2906 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312907 DiscardNonCommittedEntries();
2908
Nate Chapin9eb16be72022-09-23 22:54:312909 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312910 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122911 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312912 last_committed_entry_index_--;
2913}
2914
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572915NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272916 // If there is no pending_entry_, there should be no pending_entry_index_.
2917 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2918
2919 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362920 // at that index. An exception is while a reload of a post commit error page
2921 // is ongoing; in that case pending entry will point to the entry replaced
2922 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272923 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362924 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2925 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272926
[email protected]022af742011-12-28 18:37:252927 return pending_entry_;
2928}
2929
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572930int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272931 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:272932 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:552933 return pending_entry_index_;
2934}
2935
avi25764702015-06-23 15:43:372936void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:572937 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:362938 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:312939 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:002940 bool in_fenced_frame_tree,
2941 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:312942 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
2943 // set because:
2944 // 1) They don't influence the history of the outer page.
2945 // 2) They are always replace only navigation (there is always only one entry
2946 // in their history stack).
2947 // 3) Are not top level navigations and appear similar to iframes.
2948 // Navigations of the fenced frame might create a new NavigationEntry, which
2949 // will call this function. Non fenced frame navigations will never have
2950 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
2951 // InsertOrReplaceEntry.
2952 DCHECK_EQ(in_fenced_frame_tree,
2953 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
2954 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:202955
avi5cad4912015-06-19 05:25:442956 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
2957 // need to keep continuity with the pending entry, so copy the pending entry's
2958 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
2959 // then the renderer navigated on its own, independent of the pending entry,
2960 // so don't copy anything.
2961 if (pending_entry_ && pending_entry_index_ == -1)
2962 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:202963
Rakina Zata Amnia4e27222021-12-22 01:05:002964 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:202965
creisee17e932015-07-17 17:56:222966 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:452967 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:102968 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572969 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:362970 // If the new entry is a post-commit error page, we store the current last
2971 // committed entry to the side so that we can put it back when navigating
2972 // away from the error.
2973 if (was_post_commit_error) {
2974 DCHECK(!entry_replaced_by_post_commit_error_);
2975 entry_replaced_by_post_commit_error_ =
2976 std::move(entries_[last_committed_entry_index_]);
2977 }
dcheng36b6aec92015-12-26 06:16:362978 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:222979 return;
2980 }
[email protected]765b35502008-08-21 00:51:202981
creis37979a62015-08-04 19:48:182982 // We shouldn't see replace == true when there's no committed entries.
2983 DCHECK(!replace);
2984
Michael Thiessen9b14d512019-09-23 21:19:472985 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:202986
Shivani Sharmad8c8d652019-02-13 17:27:572987 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:202988
dcheng36b6aec92015-12-26 06:16:362989 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:202990 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:292991}
2992
Shivani Sharmad8c8d652019-02-13 17:27:572993void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:162994 if (entries_.size() < max_entry_count())
2995 return;
2996
2997 DCHECK_EQ(max_entry_count(), entries_.size());
2998 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:572999 CHECK_EQ(pending_entry_index_, -1);
3000
3001 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:423002 // Retrieve the oldest skippable entry.
3003 for (; index < GetEntryCount(); index++) {
3004 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
3005 break;
Shivani Sharmad8c8d652019-02-13 17:27:573006 }
3007
3008 // If there is no skippable entry or if it is the last committed entry then
3009 // fall back to pruning the oldest entry. It is not safe to prune the last
3010 // committed entry.
3011 if (index == GetEntryCount() || index == last_committed_entry_index_)
3012 index = 0;
3013
3014 bool should_succeed = RemoveEntryAtIndex(index);
3015 DCHECK_EQ(true, should_succeed);
3016
3017 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253018}
3019
clamy3cb9bea92018-07-10 12:42:023020void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163021 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203022 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133023 absl::optional<blink::scheduler::TaskAttributionId>
3024 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203025 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503026 TRACE_EVENT0("navigation",
3027 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273028 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023029 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363030 if (pending_entry_index_ != -1) {
3031 // The pending entry may not be in entries_ if a post-commit error page is
3032 // showing.
3033 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3034 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3035 }
Gyuyoung Kim107c2a02021-04-13 01:49:303036 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573037 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013038 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033039 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573040 int nav_entry_id = pending_entry_->GetUniqueID();
Nate Chapinbf682fa32022-09-26 22:41:203041 bool is_browser_initiated = !initiator_rfh;
Yoav Weiss8c573952022-11-17 17:35:133042 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3043 // the same as the top level frame being navigated.
3044 if (root->current_frame_host() != initiator_rfh) {
3045 soft_navigation_heuristics_task_id = absl::nullopt;
3046 }
Arthur Sonzogni620cec62018-12-13 13:08:573047
[email protected]83c2e232011-10-07 21:36:463048 // If we were navigating to a slow-to-commit page, and the user performs
3049 // a session history navigation to the last committed page, RenderViewHost
3050 // will force the throbber to start, but WebKit will essentially ignore the
3051 // navigation, and won't send a message to stop the throbber. To prevent this
3052 // from happening, we drop the navigation here and stop the slow-to-commit
3053 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023054 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083055 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273056 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033057 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123058
[email protected]83c2e232011-10-07 21:36:463059 DiscardNonCommittedEntries();
3060 return;
3061 }
3062
creisce0ef3572017-01-26 17:53:083063 // Compare FrameNavigationEntries to see which frames in the tree need to be
3064 // navigated.
clamy3cb9bea92018-07-10 12:42:023065 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3066 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Nate Chapin45f620582021-09-30 17:45:433067 FindFramesToNavigate(root, reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133068 soft_navigation_heuristics_task_id, &same_document_loads,
3069 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303070
3071 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573072 // We were unable to match any frames to navigate. This can happen if a
3073 // history navigation targets a subframe that no longer exists
3074 // (https://crbug.com/705550). In this case, we need to update the current
3075 // history entry to the pending one but keep the main document loaded. We
3076 // also need to ensure that observers are informed about the updated
3077 // current history entry (e.g., for greying out back/forward buttons), and
3078 // that renderer processes update their history offsets. The easiest way
3079 // to do all that is to schedule a "redundant" same-document navigation in
3080 // the main frame.
3081 //
3082 // Note that we don't want to remove this history entry, as it might still
3083 // be valid later, since a frame that it's targeting may be recreated.
3084 //
3085 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3086 // need to repeat history navigations until finding the one that works.
3087 // Consider changing this behavior to keep looking for the first valid
3088 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023089 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423090 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573091 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573092 ReloadType::NONE /* reload_type */,
3093 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433094 false /* is_history_navigation_in_new_child */,
3095 is_browser_initiated);
clamy3cb9bea92018-07-10 12:42:023096 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573097 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023098 DiscardPendingEntry(false);
3099 return;
3100 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573101 same_document_loads.push_back(std::move(navigation_request));
3102
3103 // Sanity check that we never take this branch for any kinds of reloads,
3104 // as those should've queued a different-document load in the main frame.
3105 DCHECK(!is_forced_reload);
3106 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303107 }
3108
Nate Chapinbf682fa32022-09-26 22:41:203109 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163110 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203111 if (initiator_rfh && initiator_rfh->IsSandboxed(
3112 network::mojom::WebSandboxFlags::kTopNavigation)) {
3113 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3114 initiator_rfh, same_document_loads) &&
3115 DoesSandboxNavigationStayWithinSubtree(
3116 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503117 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163118 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203119 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3120 initiator_rfh,
3121 navigates_inside_tree
3122 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3123 : blink::mojom::WebFeature::
3124 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523125
3126 // If the navigation occurred outside the tree discard it because
3127 // the sandboxed frame didn't have permission to navigate outside
3128 // its tree. If it is possible that the navigation is both inside and
3129 // outside the frame tree and we discard it entirely because we don't
3130 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143131 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203132 // If a |navigation_api_key| was provided, this navigation originated from
3133 // the navigation API. Notify the renderer that the navigation was
3134 // cancelled so the navigation API can fire an error event and reject the
3135 // relevant promise.
3136 if (navigation_api_key) {
3137 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3138 *navigation_api_key,
3139 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3140 }
Dave Tapuska855c1e12019-08-23 20:45:523141 DiscardPendingEntry(false);
3142 return;
3143 }
Dave Tapuska8bfd84c2019-03-26 20:47:163144 }
3145
Carlos Caballero539a421c2020-07-06 10:25:573146 // BackForwardCache:
3147 // Navigate immediately if the document is in the BackForwardCache.
3148 if (back_forward_cache_.GetEntry(nav_entry_id)) {
3149 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3150 DCHECK_EQ(reload_type, ReloadType::NONE);
3151 auto navigation_request = CreateNavigationRequestFromEntry(
3152 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3153 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433154 false /* is_history_navigation_in_new_child */, is_browser_initiated);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053155 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573156
3157 return;
3158 }
3159
3160 // History navigation might try to reuse a specific BrowsingInstance, already
3161 // used by a page in the cache. To avoid having two different main frames that
3162 // live in the same BrowsingInstance, evict the all pages with this
3163 // BrowsingInstance from the cache.
3164 //
3165 // For example, take the following scenario:
3166 //
3167 // A1 = Some page on a.com
3168 // A2 = Some other page on a.com
3169 // B3 = An uncacheable page on b.com
3170 //
3171 // Then the following navigations occur:
3172 // A1->A2->B3->A1
3173 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3174 // take its place) and A1 will be created in the same BrowsingInstance (and
3175 // SiteInstance), as A2.
3176 //
3177 // If we didn't do anything, both A1 and A2 would remain alive in the same
3178 // BrowsingInstance/SiteInstance, which is unsupported by
3179 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3180 // A2 from the cache.
3181 if (pending_entry_->site_instance()) {
3182 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3183 pending_entry_->site_instance());
3184 }
3185
Rakina Zata Amnid605d462022-06-01 10:17:033186 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3187 pending_entry_ && pending_entry_->IsRestored());
3188 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3189 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3190 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3191 pending_entry_index_);
3192 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3193 last_committed_entry_index_);
3194 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3195 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3196 pending_entry_ && pending_entry_->IsInitialEntry());
3197 SCOPED_CRASH_KEY_BOOL(
3198 "nav_reentrancy", "pending_entry_initial2",
3199 pending_entry_ &&
3200 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3201 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3202 IsInitialNavigation());
3203 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3204 IsInitialBlankNavigation());
3205 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3206 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3207 (int)pending_reload_);
3208
clamy3cb9bea92018-07-10 12:42:023209 // This call does not support re-entrancy. See http://crbug.com/347742.
3210 CHECK(!in_navigate_to_pending_entry_);
3211 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303212
Rakina Zata Amnid605d462022-06-01 10:17:033213 // If the navigation-reentrancy is caused by calling
3214 // NavigateToExistingPendingEntry twice, this will note the previous call's
3215 // pending entry's ID.
3216 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3217 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3218
arthursonzogni66f711c2019-10-08 14:40:363219 // It is not possible to delete the pending NavigationEntry while navigating
3220 // to it. Grab a reference to delay potential deletion until the end of this
3221 // function.
3222 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3223
creis4e2ecb72015-06-20 00:46:303224 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023225 for (auto& item : same_document_loads) {
3226 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053227 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303228 }
clamy3cb9bea92018-07-10 12:42:023229 for (auto& item : different_document_loads) {
3230 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053231 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303232 }
clamy3cb9bea92018-07-10 12:42:023233
3234 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303235}
3236
Alex Moshchuk3a4e77a2020-05-29 21:32:573237NavigationControllerImpl::HistoryNavigationAction
3238NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303239 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573240 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423241 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583242 // Only active and prerendered documents are allowed to navigate in their
3243 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423244 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013245 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583246 // - If the document is in pending deletion, the browser already committed
3247 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3248 // - If the document is in back-forward cache, it's not allowed to navigate
3249 // as it should remain frozen. Ignore the request and evict the document
3250 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423251 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583252 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423253 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113254 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3255 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423256 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113257 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423258 }
arthursonzogni03f76152019-02-12 10:35:203259
Alex Moshchuk3a4e77a2020-05-29 21:32:573260 // Reloads should result in a different-document load. Note that reloads may
3261 // also happen via the |needs_reload_| mechanism where the reload_type is
3262 // NONE, so detect this by comparing whether we're going to the same
3263 // entry that we're currently on. Similarly to above, only main frames
3264 // should reach this. Note that subframes support reloads, but that's done
3265 // via a different path that doesn't involve FindFramesToNavigate (see
3266 // RenderFrameHost::Reload()).
3267 if (reload_type != ReloadType::NONE ||
3268 pending_entry_index_ == last_committed_entry_index_) {
3269 DCHECK(frame->IsMainFrame());
3270 return HistoryNavigationAction::kDifferentDocument;
3271 }
3272
Alex Moshchuk47d1a4bd2020-06-01 22:15:343273 // If there is no new FrameNavigationEntry for the frame, ignore the
3274 // load. For example, this may happen when going back to an entry before a
3275 // frame was created. Suppose we commit a same-document navigation that also
3276 // results in adding a new subframe somewhere in the tree. If we go back,
3277 // the new subframe will be missing a FrameNavigationEntry in the previous
3278 // NavigationEntry, but we shouldn't delete or change what's loaded in
3279 // it.
3280 //
Alex Moshchuke65c39272020-06-03 17:55:373281 // Note that in this case, there is no need to keep looking for navigations
3282 // in subframes, which would be missing FrameNavigationEntries as well.
3283 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343284 // It's important to check this before checking |old_item| below, since both
3285 // might be null, and in that case we still shouldn't change what's loaded in
3286 // this frame. Note that scheduling any loads assumes that |new_item| is
3287 // non-null. See https://crbug.com/1088354.
3288 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3289 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373290 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343291
Charlie Reisa474fb62022-03-17 02:31:363292 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3293 // which history item it is currently on, since this may be different than the
3294 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3295 // (e.g., if a history navigation is targeting multiple frames and only some
3296 // have committed so far).
creis4e2ecb72015-06-20 00:46:303297 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363298 frame->current_frame_host()->last_committed_frame_entry();
3299 if (!old_item) {
3300 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3301 // fall back to the last committed NavigationEntry's record for this frame.
3302 // This may happen in cases like the initial state of the RenderFrameHost.
3303 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3304 // accurate FrameNavigationEntry and eliminate this case.
3305 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3306 }
3307 // If neither approach finds a FrameNavigationEntry, schedule a
3308 // different-document load.
3309 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573310 if (!old_item)
3311 return HistoryNavigationAction::kDifferentDocument;
3312
Alex Moshchuk3a4e77a2020-05-29 21:32:573313 // If the new item is not in the same SiteInstance, schedule a
3314 // different-document load. Newly restored items may not have a SiteInstance
3315 // yet, in which case it will be assigned on first commit.
3316 if (new_item->site_instance() &&
3317 new_item->site_instance() != old_item->site_instance())
3318 return HistoryNavigationAction::kDifferentDocument;
3319
3320 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313321 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3322 // that we do this even if the history navigation would not be modifying this
3323 // frame were it live.
3324 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573325 return HistoryNavigationAction::kDifferentDocument;
3326
3327 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313328 // Starting a navigation after a crash early-promotes the speculative
3329 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3330 // committed yet, so we can not possibly perform a same-document history
3331 // navigation. The frame would need to be reloaded with a cross-document
3332 // navigation.
3333 if (!frame->current_frame_host()->has_committed_any_navigation())
3334 return HistoryNavigationAction::kDifferentDocument;
3335
creis54131692016-08-12 18:32:253336 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493337 // sequence number but different item sequence number.
3338 if (new_item->document_sequence_number() ==
3339 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573340 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493341 }
avib48cb312016-05-05 21:35:003342
Alex Moshchuk3a4e77a2020-05-29 21:32:573343 // Otherwise, if both item and document sequence numbers differ, this
3344 // should be a different document load.
3345 return HistoryNavigationAction::kDifferentDocument;
3346 }
3347
3348 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373349 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573350 DCHECK_EQ(new_item->document_sequence_number(),
3351 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373352 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573353}
3354
3355void NavigationControllerImpl::FindFramesToNavigate(
3356 FrameTreeNode* frame,
3357 ReloadType reload_type,
Nate Chapin45f620582021-09-30 17:45:433358 bool is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133359 absl::optional<blink::scheduler::TaskAttributionId>
3360 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573361 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3362 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3363 DCHECK(pending_entry_);
3364 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3365
3366 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3367
3368 if (action == HistoryNavigationAction::kSameDocument) {
3369 std::unique_ptr<NavigationRequest> navigation_request =
3370 CreateNavigationRequestFromEntry(
3371 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133372 /*is_same_document_history_load=*/true,
3373 /*is_history_navigation_in_new_child_frame=*/false,
3374 is_browser_initiated, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573375 if (navigation_request) {
3376 // Only add the request if was properly created. It's possible for the
3377 // creation to fail in certain cases, e.g. when the URL is invalid.
3378 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303379 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573380 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473381 std::unique_ptr<NavigationRequest> navigation_request =
3382 CreateNavigationRequestFromEntry(
3383 frame, pending_entry_, new_item, reload_type,
3384 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433385 false /* is_history_navigation_in_new_child */,
3386 is_browser_initiated);
Lei Zhang96031532019-10-10 19:05:473387 if (navigation_request) {
3388 // Only add the request if was properly created. It's possible for the
3389 // creation to fail in certain cases, e.g. when the URL is invalid.
3390 different_document_loads->push_back(std::move(navigation_request));
3391 }
3392 // For a different document, the subframes will be destroyed, so there's
3393 // no need to consider them.
3394 return;
Alex Moshchuke65c39272020-06-03 17:55:373395 } else if (action == HistoryNavigationAction::kStopLooking) {
3396 return;
creis4e2ecb72015-06-20 00:46:303397 }
3398
Yoav Weiss8c573952022-11-17 17:35:133399 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3400 // we currently only support soft navigation heuristics for the top level
3401 // frame.
creis4e2ecb72015-06-20 00:46:303402 for (size_t i = 0; i < frame->child_count(); i++) {
Nate Chapin45f620582021-09-30 17:45:433403 FindFramesToNavigate(frame->child_at(i), reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133404 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433405 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303406 }
3407}
3408
Harkiran Bolariaba823e42021-05-21 18:30:363409base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243410 const LoadURLParams& params) {
3411 // Find the appropriate FrameTreeNode.
3412 FrameTreeNode* node = nullptr;
3413 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3414 !params.frame_name.empty()) {
3415 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033416 ? frame_tree_->FindByID(params.frame_tree_node_id)
3417 : frame_tree_->FindByName(params.frame_name);
Arthur Sonzognif6785ec2022-12-05 10:11:503418 DCHECK(!node || &node->frame_tree() == &frame_tree());
clamy21718cc22018-06-13 13:34:243419 }
3420
3421 // If no FrameTreeNode was specified, navigate the main frame.
3422 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033423 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243424
Camille Lamy5193caa2018-10-12 11:59:423425 // Compute overrides to the LoadURLParams for |override_user_agent|,
3426 // |should_replace_current_entry| and |has_user_gesture| that will be used
3427 // both in the creation of the NavigationEntry and the NavigationRequest.
3428 // Ideally, the LoadURLParams themselves would be updated, but since they are
3429 // passed as a const reference, this is not possible.
3430 // TODO(clamy): When we only create a NavigationRequest, move this to
3431 // CreateNavigationRequestFromLoadURLParams.
3432 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3433 GetLastCommittedEntry());
3434
Rakina Zata Amnie2d31312022-11-18 03:38:453435 // An entry replacement must happen if the current browsing context should
3436 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333437 bool should_replace_current_entry =
3438 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453439 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423440
clamy21718cc22018-06-13 13:34:243441 // Javascript URLs should not create NavigationEntries. All other navigations
3442 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243443 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373444 std::unique_ptr<NavigationEntryImpl> entry =
3445 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3446 should_replace_current_entry,
3447 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243448 DiscardPendingEntry(false);
3449 SetPendingEntry(std::move(entry));
3450 }
3451
3452 // Renderer-debug URLs are sent to the renderer process immediately for
3453 // processing and don't need to create a NavigationRequest.
3454 // Note: this includes navigations to JavaScript URLs, which are considered
3455 // renderer-debug URLs.
3456 // Note: we intentionally leave the pending entry in place for renderer debug
3457 // URLs, unlike the cases below where we clear it if the navigation doesn't
3458 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303459 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483460 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3461 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153462 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Oleg Davydov2cc0167b2019-02-05 14:32:483463 params.url, browser_context_)) {
3464 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363465 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483466 }
3467
clamy21718cc22018-06-13 13:34:243468 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363469 return nullptr;
clamy21718cc22018-06-13 13:34:243470 }
3471
Antonio Sartori78a749f2020-11-30 12:03:393472 DCHECK(pending_entry_);
3473
clamy21718cc22018-06-13 13:34:243474 // Convert navigations to the current URL to a reload.
3475 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3476 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3477 // DevTools sometimes issues navigations to main frames that they do not
3478 // expect to see treated as reload, and it only works because they pass a
3479 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3480 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543481 ReloadType reload_type = params.reload_type;
3482 if (reload_type == ReloadType::NONE &&
3483 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043484 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243485 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243486 params.load_type ==
3487 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543488 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243489 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473490 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393491
3492 // If this is a reload of an existing FrameNavigationEntry and we had a
3493 // policy container for it, then we should copy it into the pending entry,
3494 // so that it is copied to the navigation request in
3495 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453496 FrameNavigationEntry* previous_frame_entry =
3497 GetLastCommittedEntry()->GetFrameEntry(node);
3498 if (previous_frame_entry &&
3499 previous_frame_entry->policy_container_policies()) {
3500 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3501 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393502 }
3503 }
3504
3505 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173506 // document, then we should copy the document polices from RenderFrameHost's
3507 // PolicyContainerHost. The NavigationRequest will create a new
3508 // PolicyContainerHost with the document policies from the |pending_entry_|,
3509 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3510 // the navigation. This way, we ensure that we keep enforcing the right
3511 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453512 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393513 if (node->current_frame_host() &&
3514 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193515 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163516 node->current_frame_host()
3517 ->policy_container_host()
3518 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233519 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393520 }
clamy21718cc22018-06-13 13:34:243521 }
3522
3523 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263524 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243525
Tsuyoshi Horo167ca6432022-03-09 05:16:393526 // This will be used to set the Navigation Timing API navigationStart
3527 // parameter for browser navigations in new tabs (intents, tabs opened through
3528 // "Open link in new tab"). If the navigation must wait on the current
3529 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3530 // will be updated when the BeforeUnload ack is received.
3531 const auto navigation_start_time = base::TimeTicks::Now();
3532
Camille Lamy5193caa2018-10-12 11:59:423533 std::unique_ptr<NavigationRequest> request =
3534 CreateNavigationRequestFromLoadParams(
3535 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143536 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393537 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3538 navigation_start_time);
clamy21718cc22018-06-13 13:34:243539
3540 // If the navigation couldn't start, return immediately and discard the
3541 // pending NavigationEntry.
3542 if (!request) {
3543 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363544 return nullptr;
clamy21718cc22018-06-13 13:34:243545 }
3546
Camille Lamy5193caa2018-10-12 11:59:423547#if DCHECK_IS_ON()
3548 // Safety check that NavigationRequest and NavigationEntry match.
3549 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3550#endif
3551
clamy21718cc22018-06-13 13:34:243552 // This call does not support re-entrancy. See http://crbug.com/347742.
3553 CHECK(!in_navigate_to_pending_entry_);
3554 in_navigate_to_pending_entry_ = true;
3555
arthursonzogni66f711c2019-10-08 14:40:363556 // It is not possible to delete the pending NavigationEntry while navigating
3557 // to it. Grab a reference to delay potential deletion until the end of this
3558 // function.
3559 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3560
Harkiran Bolariaba823e42021-05-21 18:30:363561 base::WeakPtr<NavigationHandle> created_navigation_handle(
3562 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053563 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243564
3565 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363566 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243567}
3568
clamyea99ea12018-05-28 13:54:233569void NavigationControllerImpl::HandleRendererDebugURL(
3570 FrameTreeNode* frame_tree_node,
3571 const GURL& url) {
3572 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243573 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3574 // the renderer process is not live, unless it is the initial navigation
3575 // of the tab.
clamyea99ea12018-05-28 13:54:233576 if (!IsInitialNavigation()) {
3577 DiscardNonCommittedEntries();
3578 return;
3579 }
Fergal Dalyecd3b0202020-06-25 01:57:373580 // The current frame is always a main frame. If IsInitialNavigation() is
3581 // true then there have been no navigations and any frames of this tab must
3582 // be in the same renderer process. If that has crashed then the only frame
3583 // that can be revived is the main frame.
3584 frame_tree_node->render_manager()
3585 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233586 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223587
3588 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3589 // notification, so set is loading to true here to properly surface it when
3590 // the renderer process is done handling the URL.
3591 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3592 if (!url.SchemeIs(url::kJavaScriptScheme)) {
3593 bool was_loading = frame_tree_node->frame_tree()
Arthur Sonzognif6785ec2022-12-05 10:11:503594 .LoadingTree()
Julie Jeongeun Kim50d124c2022-10-21 13:51:223595 ->IsLoadingIncludingInnerFrameTrees();
3596 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
3597 frame_tree_node->DidStartLoading(true /* should_show_loading_ui */,
3598 was_loading);
3599 }
clamyea99ea12018-05-28 13:54:233600 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3601}
3602
clamy21718cc22018-06-13 13:34:243603std::unique_ptr<NavigationEntryImpl>
3604NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3605 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423606 const LoadURLParams& params,
3607 bool override_user_agent,
3608 bool should_replace_current_entry,
3609 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393610 // Browser initiated navigations might not have a blob_url_loader_factory set
3611 // in params even if the navigation is to a blob URL. If that happens, lookup
3612 // the correct url loader factory to use here.
3613 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483614 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473615 // Resolve the blob URL in the storage partition associated with the target
3616 // frame. This is the storage partition the URL will be loaded in, and only
3617 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393618 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473619 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393620 }
3621
clamy21718cc22018-06-13 13:34:243622 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443623 // extra_headers in params are \n separated; navigation entries want \r\n.
3624 std::string extra_headers_crlf;
3625 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243626
3627 // For subframes, create a pending entry with a corresponding frame entry.
3628 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453629 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243630 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083631 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243632 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073633 params.url, absl::nullopt, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213634 params.initiator_base_url, params.redirect_chain, blink::PageState(),
3635 "GET", -1, blob_url_loader_factory,
3636 nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483637 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393638 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163639 // a conversion of a new navigation into a reload, we will set the right
3640 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193641 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243642 } else {
3643 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173644 // If `node` is the outermost main frame, it rewrites a virtual url in order
3645 // to adjust the original input url if needed. For inner frames such as
3646 // fenced frames or subframes, they don't rewrite urls as the urls are not
3647 // input urls by users.
3648 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy21718cc22018-06-13 13:34:243649 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063650 params.url, params.referrer, params.initiator_origin,
W. James MacLean23e90a12022-12-21 04:38:213651 params.initiator_base_url, params.source_site_instance.get(),
3652 params.transition_type, params.is_renderer_initiated,
3653 extra_headers_crlf, browser_context_, blob_url_loader_factory,
3654 rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243655 entry->set_source_site_instance(
3656 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3657 entry->SetRedirectChain(params.redirect_chain);
3658 }
3659
3660 // Set the FTN ID (only used in non-site-per-process, for tests).
3661 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243662 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423663 entry->SetIsOverridingUserAgent(override_user_agent);
3664 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543665 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243666
clamy21718cc22018-06-13 13:34:243667 switch (params.load_type) {
3668 case LOAD_TYPE_DEFAULT:
3669 break;
3670 case LOAD_TYPE_HTTP_POST:
3671 entry->SetHasPostData(true);
3672 entry->SetPostData(params.post_data);
3673 break;
3674 case LOAD_TYPE_DATA:
3675 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3676 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283677#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243678 entry->SetDataURLAsString(params.data_url_as_string);
3679#endif
3680 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3681 break;
clamy21718cc22018-06-13 13:34:243682 }
3683
3684 // TODO(clamy): NavigationEntry is meant for information that will be kept
3685 // after the navigation ended and therefore is not appropriate for
3686 // started_from_context_menu. Move started_from_context_menu to
3687 // NavigationUIData.
3688 entry->set_started_from_context_menu(params.started_from_context_menu);
3689
3690 return entry;
3691}
3692
clamyea99ea12018-05-28 13:54:233693std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423694NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3695 FrameTreeNode* node,
3696 const LoadURLParams& params,
3697 bool override_user_agent,
3698 bool should_replace_current_entry,
3699 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143700 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423701 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573702 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393703 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223704 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493705 bool is_embedder_initiated_fenced_frame_navigation,
3706 bool is_unfenced_top_navigation) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573707 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283708 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533709 // All renderer-initiated navigations must have an initiator_origin.
3710 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513711
Camille Lamy5193caa2018-10-12 11:59:423712 GURL url_to_load;
3713 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323714
Camille Lamy2baa8022018-10-19 16:43:173715 // For main frames, rewrite the URL if necessary and compute the virtual URL
3716 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263717 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423718 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173719 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423720 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423721
Camille Lamy2baa8022018-10-19 16:43:173722 // For DATA loads, override the virtual URL.
3723 if (params.load_type == LOAD_TYPE_DATA)
3724 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423725
Camille Lamy2baa8022018-10-19 16:43:173726 if (virtual_url.is_empty())
3727 virtual_url = url_to_load;
3728
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573729 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283730
Aran Gilman249eb122019-12-02 23:32:463731 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3732 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3733 // return different results, leading to a different URL in the
3734 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3735 // pending NavigationEntry, as we'll only make one call to
3736 // RewriteUrlForNavigation.
3737 VLOG_IF(1, (url_to_load != frame_entry->url()))
3738 << "NavigationRequest and FrameEntry have different URLs: "
3739 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283740
Camille Lamy2baa8022018-10-19 16:43:173741 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423742 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173743 // NavigationRequest.
3744 } else {
3745 url_to_load = params.url;
3746 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243747 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173748 }
Camille Lamy5193caa2018-10-12 11:59:423749
Ehsan Karamad44fc72112019-02-26 18:15:473750 if (node->render_manager()->is_attaching_inner_delegate()) {
3751 // Avoid starting any new navigations since this node is now preparing for
3752 // attaching an inner delegate.
3753 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203754 }
Camille Lamy5193caa2018-10-12 11:59:423755
Ian Vollick1c6dd3e2022-04-13 02:06:263756 if (!IsValidURLForNavigation(node->IsOutermostMainFrame(), virtual_url,
3757 url_to_load))
Camille Lamy5193caa2018-10-12 11:59:423758 return nullptr;
3759
danakjd83d706d2020-11-25 22:11:123760 // Look for a pending commit that is to another document in this
3761 // FrameTreeNode. If one exists, then the last committed URL will not be the
3762 // current URL by the time this navigation commits.
3763 bool has_pending_cross_document_commit =
3764 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213765 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123766
Minggang Wangb9f3fa92021-07-01 15:30:313767 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493768 /*old_url=*/node->current_url(),
3769 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3770 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133771 /*is_same_document_history_load=*/false,
3772 is_embedder_initiated_fenced_frame_navigation,
3773 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423774
3775 // Create the NavigationParams based on |params|.
3776
Hiroki Nakagawa4ed61282021-06-18 05:37:233777 bool is_view_source_mode = entry->IsViewSourceMode();
3778 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293779
Antonio Sartori6984c742021-08-26 08:03:413780 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Yao Xiao720ef9d62022-12-09 05:18:293781
Hiroki Nakagawa4ed61282021-06-18 05:37:233782 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293783 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253784 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293785
Minggang Wangb9f3fa92021-07-01 15:30:313786 blink::mojom::CommonNavigationParamsPtr common_params =
3787 blink::mojom::CommonNavigationParams::New(
W. James MacLean23e90a12022-12-21 04:38:213788 url_to_load, params.initiator_origin, params.initiator_base_url,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513789 blink::mojom::Referrer::New(params.referrer.url,
3790 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213791 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513792 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393793 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513794 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143795 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413796 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273797 false /* has_text_fragment_token */,
3798 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3799 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513800 false /* is_history_navigation_in_new_child_frame */,
Nan Lind91c8152021-10-21 16:22:373801 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423802
Minggang Wangb9f3fa92021-07-01 15:30:313803 blink::mojom::CommitNavigationParamsPtr commit_params =
3804 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403805 absl::nullopt,
Ari Chivukula43d2cf82023-01-24 03:16:073806 // The correct storage key and session storage key will be computed
3807 // before committing the navigation.
3808 blink::StorageKey(), blink::StorageKey(), override_user_agent,
3809 params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323810 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503811 std::vector<net::RedirectInfo>(), params.post_content_type,
3812 common_params->url, common_params->method,
3813 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313814 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133815 entry->GetSubframeUniqueNames(node),
3816 /*intended_as_new_entry=*/true,
3817 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143818 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3819 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133820 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313821 params.should_clear_history_list,
3822 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223823 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133824 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513825 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283826#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133827 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143828#endif
Yoav Weiss8c573952022-11-17 17:35:133829 /*is_browser_initiated=*/!params.is_renderer_initiated,
3830 /*web_bundle_physical_url=*/GURL(),
3831 /*base_url_override_for_web_bundle=*/GURL(),
3832 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073833 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133834 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3835 /*origin_agent_cluster=*/false,
3836 /*origin_agent_cluster_left_as_default=*/true,
3837 /*enabled_client_hints=*/
3838 std::vector<network::mojom::WebClientHintsType>(),
3839 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3840 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013841 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133842 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
Clark DuVall8ee487a22021-11-10 02:25:583843 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133844 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
Yoav Weiss8c573952022-11-17 17:35:133845 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283846 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133847 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443848 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423849 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133850 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053851 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3852 /*modified_runtime_features=*/
Garrett Tanzer29de7112022-12-06 21:26:323853 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>(),
Yuzu Saijo29f96ca92022-12-08 04:54:123854 /*fenced_frame_properties=*/absl::nullopt,
3855 /*not_restored_reasons=*/nullptr);
Xiaohan Wang7f8052e02022-01-14 18:44:283856#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423857 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143858 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423859 }
3860#endif
3861
Lucas Furukawa Gadania9c45682019-07-31 22:05:143862 commit_params->was_activated = params.was_activated;
Camille Lamy5193caa2018-10-12 11:59:423863
Camille Lamy5193caa2018-10-12 11:59:423864 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3865 std::string extra_headers_crlf;
3866 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093867
Alex Moshchuk9321e6a2022-12-07 21:58:313868 auto navigation_request = NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143869 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083870 !params.is_renderer_initiated, params.was_opener_suppressed,
Antonio Sartori9a82f6f32020-12-14 09:22:453871 params.initiator_frame_token.has_value()
3872 ? &(params.initiator_frame_token.value())
3873 : nullptr,
3874 params.initiator_process_id, extra_headers_crlf, frame_entry, entry,
jongdeok.kim5de823b32022-06-14 04:37:503875 params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213876 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Yao Xiao720ef9d62022-12-09 05:18:293877 params.impression, params.initiator_activation_and_ad_status,
3878 params.is_pdf, is_embedder_initiated_fenced_frame_navigation);
Yao Xiaodc5ed102019-06-04 19:19:093879 navigation_request->set_from_download_cross_origin_redirect(
3880 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:553881 navigation_request->set_force_new_browsing_instance(
3882 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:093883 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:423884}
3885
3886std::unique_ptr<NavigationRequest>
3887NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:233888 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573889 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:233890 FrameNavigationEntry* frame_entry,
3891 ReloadType reload_type,
3892 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:433893 bool is_history_navigation_in_new_child_frame,
Yoav Weiss8c573952022-11-17 17:35:133894 bool is_browser_initiated,
3895 absl::optional<blink::scheduler::TaskAttributionId>
3896 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:343897 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:233898 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:433899 // We should never navigate to an existing initial NavigationEntry that is the
3900 // initial NavigationEntry for the initial empty document that hasn't been
3901 // overridden by the synchronous about:blank commit, to preserve previous
3902 // behavior where trying to reload when the main frame is on the initial empty
3903 // document won't result in a navigation.
3904 // See also https://crbug.com/1277414.
3905 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:323906
clamyea99ea12018-05-28 13:54:233907 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:013908 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573909 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:233910 // We may have been redirected when navigating to the current URL.
3911 // Use the URL the user originally intended to visit as signaled by the
3912 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:013913 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573914 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:233915 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:233916 }
3917
Ehsan Karamad44fc72112019-02-26 18:15:473918 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
3919 // Avoid starting any new navigations since this node is now preparing for
3920 // attaching an inner delegate.
3921 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203922 }
3923
Ian Vollick1c6dd3e2022-04-13 02:06:263924 if (!IsValidURLForNavigation(frame_tree_node->IsOutermostMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573925 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:233926 return nullptr;
3927 }
3928
clamyea99ea12018-05-28 13:54:233929 // This will be used to set the Navigation Timing API navigationStart
3930 // parameter for browser navigations in new tabs (intents, tabs opened through
3931 // "Open link in new tab"). If the navigation must wait on the current
3932 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3933 // will be updated when the BeforeUnload ack is received.
3934 base::TimeTicks navigation_start = base::TimeTicks::Now();
clamyea99ea12018-05-28 13:54:233935
danakjd83d706d2020-11-25 22:11:123936 // Look for a pending commit that is to another document in this
3937 // FrameTreeNode. If one exists, then the last committed URL will not be the
3938 // current URL by the time this navigation commits.
3939 bool has_pending_cross_document_commit =
3940 frame_tree_node->render_manager()
3941 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:493942 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:213943 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123944
Minggang Wangb9f3fa92021-07-01 15:30:313945 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:123946 /*old_url=*/frame_tree_node->current_url(),
3947 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:493948 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:493949 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:133950 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:493951 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:423952
3953 // A form submission may happen here if the navigation is a
3954 // back/forward/reload navigation that does a form resubmission.
3955 scoped_refptr<network::ResourceRequestBody> request_body;
3956 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:503957 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
3958 // entry. This way, it could be directly retrieved here. Right now, it is only
3959 // partially recovered when request.method == "POST" and request.body exists.
3960 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:423961 if (frame_entry->method() == "POST") {
3962 request_body = frame_entry->GetPostData(&post_content_type);
3963 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:303964 post_content_type = std::string(
3965 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:503966 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:423967 }
3968
3969 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:313970 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513971 entry->ConstructCommonNavigationParams(
3972 *frame_entry, request_body, dest_url,
3973 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:383974 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:533975 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513976 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:553977 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:423978
3979 // TODO(clamy): |intended_as_new_entry| below should always be false once
3980 // Reload no longer leads to this being called for a pending NavigationEntry
3981 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:313982 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:143983 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:403984 *frame_entry, common_params->url, common_params->method,
3985 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143986 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:533987 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:483988 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133989 frame_tree_node->AncestorOrSelfHasCSPEE(),
3990 soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:143991 commit_params->post_content_type = post_content_type;
Camille Lamy5193caa2018-10-12 11:59:423992
W. James MacLeanb7d6092682022-10-05 15:23:263993 if (common_params->url.IsAboutSrcdoc()) {
3994 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
3995 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:593996 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:263997 }
Alex Moshchuk9321e6a2022-12-07 21:58:313998 return NavigationRequest::Create(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143999 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:434000 is_browser_initiated, false /* was_opener_suppressed */,
Takashi Toyoshimae87b7be2021-01-22 11:51:084001 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454002 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
jongdeok.kim5de823b32022-06-14 04:37:504003 entry->extra_headers(), frame_entry, entry, is_form_submission,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474004 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
Yao Xiao720ef9d62022-12-09 05:18:294005 blink::mojom::NavigationInitiatorActivationAndAdStatus::
4006 kDidNotStartWithTransientActivation,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474007 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:234008}
4009
[email protected]d202a7c2012-01-04 07:53:474010void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:214011 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:274012 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:404013
Takashi Toyoshimaea534ef22021-07-21 03:27:594014 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:404015 // location bar will have up-to-date information about the security style
4016 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:134017 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:404018
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374019 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:574020 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:464021
[email protected]b0f724c2013-09-05 04:21:134022 // TODO(avi): Remove. http://crbug.com/170921
4023 NotificationDetails notification_details =
4024 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154025 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4026 Source<NavigationController>(this),
4027 notification_details);
initial.commit09911bf2008-07-26 23:55:294028}
4029
initial.commit09911bf2008-07-26 23:55:294030// static
[email protected]d202a7c2012-01-04 07:53:474031size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234032 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154033 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214034 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234035}
4036
[email protected]d202a7c2012-01-04 07:53:474037void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224038 if (is_active && needs_reload_)
4039 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294040}
4041
[email protected]d202a7c2012-01-04 07:53:474042void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034043 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4044 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294045 if (!needs_reload_)
4046 return;
4047
Bo Liucdfa4b12018-11-06 00:21:444048 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4049 needs_reload_type_);
4050
initial.commit09911bf2008-07-26 23:55:294051 // Calling Reload() results in ignoring state, and not loading.
4052 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4053 // cached state.
avicc872d7242015-08-19 21:26:344054 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134055 NavigateToExistingPendingEntry(
4056 ReloadType::NONE,
4057 /*initiator_rfh=*/nullptr,
4058 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4059 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454060 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434061 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274062 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344063 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134064 NavigateToExistingPendingEntry(
4065 ReloadType::NONE,
4066 /*initiator_rfh=*/nullptr,
4067 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4068 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344069 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434070 // We should never navigate to an existing initial NavigationEntry that is
4071 // the initial NavigationEntry for the initial empty document that hasn't
4072 // been overridden by the synchronous about:blank commit, to preserve
4073 // legacy behavior where trying to reload when the main frame is on the
4074 // initial empty document won't result in a navigation. See also
4075 // https://crbug.com/1277414. If there is something to reload, the
4076 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4077 // it here.
avicc872d7242015-08-19 21:26:344078 needs_reload_ = false;
4079 }
initial.commit09911bf2008-07-26 23:55:294080}
4081
Kevin McNeeccca6172021-10-19 17:11:144082base::WeakPtr<NavigationHandle>
4083NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364084 RenderFrameHost* render_frame_host,
4085 const GURL& url,
4086 const std::string& error_page_html,
4087 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134088 RenderFrameHostImpl* rfhi =
4089 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584090
4091 // Only active documents can load post-commit error pages:
4092 // - If the document is in pending deletion, the browser already committed to
4093 // destroying this RenderFrameHost so ignore loading the error page.
4094 // - If the document is in back-forward cache, it's not allowed to navigate as
4095 // it should remain frozen. Ignore the request and evict the document from
4096 // back-forward cache.
4097 // - If the document is prerendering, it can navigate but when loading error
4098 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114099 if (rfhi->IsInactiveAndDisallowActivation(
4100 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144101 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114102 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584103
Rakina Zata Amni919b7922020-12-11 09:03:134104 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414105
Minggang Wangb9f3fa92021-07-01 15:30:314106 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434107 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594108 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4109 // the frame actually committed (e.g. iframe with "src" set to a
4110 // slow-responding URL). We should rewrite the URL to about:blank in this
4111 // case, as the renderer will only think a page is an error page if it has a
4112 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134113 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314114 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434115 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334116 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414117
arthursonzogni70ac7302020-05-28 08:49:054118 // Error pages have a fully permissive FramePolicy.
4119 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4120 // error pages.
4121 commit_params->frame_policy = blink::FramePolicy();
4122
John Delaney131ad362019-08-08 21:57:414123 std::unique_ptr<NavigationRequest> navigation_request =
4124 NavigationRequest::CreateBrowserInitiated(
4125 node, std::move(common_params), std::move(commit_params),
Alex Moshchuk9321e6a2022-12-07 21:58:314126 false /* was_opener_suppressed */,
Lingqi Chi82efa95e2020-12-29 05:31:194127 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454128 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
John Delaneyf43556d2020-05-04 23:19:064129 "" /* extra_headers */, nullptr /* frame_entry */,
jongdeok.kim5de823b32022-06-14 04:37:504130 nullptr /* entry */, false /* is_form_submission */,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474131 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
4132 false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364133 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414134 navigation_request->set_net_error(error);
Charlie Reis09952ee2022-12-08 16:35:074135 node->TakeNavigationRequest(std::move(navigation_request));
John Delaney131ad362019-08-08 21:57:414136 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144137
4138 // Calling BeginNavigation may destroy the NavigationRequest.
4139 base::WeakPtr<NavigationRequest> created_navigation_request(
4140 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414141 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144142 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414143}
4144
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574145void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214146 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094147 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154148 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144149 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294150}
4151
[email protected]d202a7c2012-01-04 07:53:474152void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364153 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474154 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4155 // represent a no-committed-entry state.
4156 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364157 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474158 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4159 // if `entries_` contains pre-existing entries from the NavigationController
4160 // before restore, which would not be removed and will be at the front of the
4161 // entries list, causing the index to be off by the amount of pre-existing
4162 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294163 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294164}
[email protected]765b35502008-08-21 00:51:204165
arthursonzogni69a6a1b2019-09-17 09:23:004166void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004167 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4168}
4169
4170void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4171 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474172 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104173 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4174 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294175 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474176 return;
Michael Thiessenc5676d22019-09-25 22:32:104177 }
avi45a72532015-04-07 21:01:454178 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314179
4180 if (!delegate_)
4181 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374182 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484183}
4184
avi7c6f35e2015-05-08 17:52:384185int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4186 int nav_entry_id) const {
4187 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4188 if (entries_[i]->GetUniqueID() == nav_entry_id)
4189 return i;
4190 }
4191 return -1;
4192}
4193
[email protected]d202a7c2012-01-04 07:53:474194void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574195 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254196 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574197 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574198 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4199 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254200 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374201 // Normally, cloning a NavigationEntryImpl results in sharing
4202 // FrameNavigationEntries between the original and the clone. However, when
4203 // cloning from a different NavigationControllerImpl, we want to fork the
4204 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374205 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574206 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254207 }
Rakina Zata Amnie2d31312022-11-18 03:38:454208 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274209 DCHECK(pending_entry_index_ == -1 ||
4210 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254211}
[email protected]c5b88d82012-10-06 17:03:334212
4213void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184214 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334215 get_timestamp_callback_ = get_timestamp_callback;
4216}
[email protected]8ff00d72012-10-23 19:12:214217
Shivani Sharmaffb32b82019-04-09 16:58:474218// History manipulation intervention:
4219void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474220 bool replace_entry,
4221 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404222 bool is_renderer_initiated,
4223 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454224 // Note that for a subframe, previous_document_was_activated is true if the
4225 // gesture happened in any subframe (propagated to main frame) or in the main
4226 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474227 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274228 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474229 return;
4230 }
4231 if (last_committed_entry_index_ == -1)
4232 return;
4233
Shivani Sharmac4cc8922019-04-18 03:11:174234 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474235
Alexander Timine3ec4192020-04-20 16:39:404236 // Log UKM with the URL we are navigating away from.
4237 ukm::builders::HistoryManipulationIntervention(
4238 previous_page_load_ukm_source_id)
4239 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474240}
4241
Shivani Sharmac4cc8922019-04-18 03:11:174242void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4243 int reference_index,
4244 bool skippable) {
4245 auto* reference_entry = GetEntryAtIndex(reference_index);
4246 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4247
4248 int64_t document_sequence_number =
4249 reference_entry->root_node()->frame_entry->document_sequence_number();
4250 for (int index = 0; index < GetEntryCount(); index++) {
4251 auto* entry = GetEntryAtIndex(index);
4252 if (entry->root_node()->frame_entry->document_sequence_number() ==
4253 document_sequence_number) {
4254 entry->set_should_skip_on_back_forward_ui(skippable);
4255 }
4256 }
4257}
4258
arthursonzogni66f711c2019-10-08 14:40:364259std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4260NavigationControllerImpl::ReferencePendingEntry() {
4261 DCHECK(pending_entry_);
4262 auto pending_entry_ref =
4263 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4264 pending_entry_refs_.insert(pending_entry_ref.get());
4265 return pending_entry_ref;
4266}
4267
4268void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4269 // Ignore refs that don't correspond to the current pending entry.
4270 auto it = pending_entry_refs_.find(ref);
4271 if (it == pending_entry_refs_.end())
4272 return;
4273 pending_entry_refs_.erase(it);
4274
4275 if (!pending_entry_refs_.empty())
4276 return;
4277
4278 // The pending entry may be deleted before the last PendingEntryRef.
4279 if (!pending_entry_)
4280 return;
4281
4282 // We usually clear the pending entry when the matching NavigationRequest
4283 // fails, so that an arbitrary URL isn't left visible above a committed page.
4284 //
4285 // However, we do preserve the pending entry in some cases, such as on the
4286 // initial navigation of an unmodified blank tab. We also allow the delegate
4287 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4288 // user edit the URL and try again. This may be useful in cases that the
4289 // committed page cannot be attacker-controlled. In these cases, we still
4290 // allow the view to clear the pending entry and typed URL if the user
4291 // requests (e.g., hitting Escape with focus in the address bar).
4292 //
4293 // Do not leave the pending entry visible if it has an invalid URL, since this
4294 // might be formatted in an unexpected or unsafe way.
4295 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364296 bool should_preserve_entry =
4297 (pending_entry_ == GetVisibleEntry()) &&
4298 pending_entry_->GetURL().is_valid() &&
4299 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4300 if (should_preserve_entry)
4301 return;
4302
4303 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374304 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364305}
4306
Titouan Rigoudy6ec70402021-02-02 15:42:194307std::unique_ptr<PolicyContainerPolicies>
4308NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394309 RenderFrameHostImpl* rfh,
4310 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174311 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394312 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454313 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394314 FrameNavigationEntry* previous_frame_entry =
4315 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4316
4317 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4318 // ensure we always have a FrameNavigationEntry here.
4319 if (!previous_frame_entry)
4320 return nullptr;
4321
Titouan Rigoudy6ec70402021-02-02 15:42:194322 const PolicyContainerPolicies* previous_policies =
4323 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394324
Titouan Rigoudy6ec70402021-02-02 15:42:194325 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394326 return nullptr;
4327
4328 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234329 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394330 }
4331
Titouan Rigoudy72f892d2022-05-02 18:21:234332 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394333}
4334
Hayato Ito2c8c08d02021-06-23 03:38:434335void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504336 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434337 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4338 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4339 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504340
4341 auto callback = base::BindRepeating(
4342 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4343 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4344 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4345 }
4346 },
Hayato Ito2c8c08d02021-06-23 03:38:434347 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034348 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504349}
4350
4351void NavigationControllerImpl::DidAccessInitialMainDocument() {
4352 // We may have left a failed browser-initiated navigation in the address bar
4353 // to let the user edit it and try again. Clear it now that content might
4354 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034355 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504356 DiscardPendingEntry(false);
4357
4358 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374359 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504360}
4361
4362void NavigationControllerImpl::UpdateStateForFrame(
4363 RenderFrameHostImpl* rfhi,
4364 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564365 OPTIONAL_TRACE_EVENT1("content",
4366 "NavigationControllerImpl::UpdateStateForFrame",
4367 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504368 // The state update affects the last NavigationEntry associated with the given
4369 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4370 // in the case of an UpdateState from a frame being swapped out). We track
4371 // which entry this is in the RenderFrameHost's nav_entry_id.
4372 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4373 if (!entry)
4374 return;
4375
4376 FrameNavigationEntry* frame_entry =
4377 entry->GetFrameEntry(rfhi->frame_tree_node());
4378 if (!frame_entry)
4379 return;
4380
4381 // The SiteInstance might not match if we do a cross-process navigation with
4382 // replacement (e.g., auto-subframe), in which case the swap out of the old
4383 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4384 // has already been replaced and destroyed.
4385 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4386 return;
4387
4388 if (page_state == frame_entry->page_state())
4389 return; // Nothing to update.
4390
4391 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4392
4393 // The document_sequence_number and item_sequence_number recorded in the
4394 // FrameNavigationEntry should not differ from the one coming with the update,
4395 // since it must come from the same document. Do not update it if a difference
4396 // is detected, as this indicates that |frame_entry| is not the correct one.
4397 blink::ExplodedPageState exploded_state;
4398 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4399 return;
4400
4401 if (exploded_state.top.document_sequence_number !=
4402 frame_entry->document_sequence_number() ||
4403 exploded_state.top.item_sequence_number !=
4404 frame_entry->item_sequence_number()) {
4405 return;
4406 }
4407
4408 frame_entry->SetPageState(page_state);
4409 NotifyEntryChanged(entry);
4410}
4411
Domenic Denicolacd30f5f82022-03-16 21:48:014412std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4413NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574414 Direction direction,
4415 int entry_index,
4416 const url::Origin& pending_origin,
4417 FrameTreeNode* node,
4418 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304419 int64_t pending_item_sequence_number,
4420 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014421 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454422 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174423 // Don't process the initial entry.
4424 DCHECK_EQ(GetEntryCount(), 1);
4425 return entries;
4426 }
Nate Chapind1fe3612021-04-16 20:45:574427 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304428 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574429 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4430 i += offset) {
4431 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414432 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574433 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014434 // An entry should only appear in the navigation API entries if it is for
4435 // the same origin as the document being committed. Check the committed
4436 // origin, or if that is not available (during restore), check against the
4437 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414438 url::Origin frame_entry_origin =
4439 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4440 frame_entry->url(),
4441 frame_entry->initiator_origin().value_or(url::Origin())));
4442 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574443 break;
4444 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4445 continue;
4446 blink::ExplodedPageState exploded_page_state;
4447 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4448 &exploded_page_state)) {
4449 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304450
4451 // If the document represented by this FNE hid its full url from appearing
4452 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014453 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304454 // document).
4455 std::u16string url;
4456 if (pending_document_sequence_number ==
4457 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574458 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304459 url = frame_state.url_string.value_or(std::u16string());
4460 }
4461
Domenic Denicolacd30f5f82022-03-16 21:48:014462 blink::mojom::NavigationApiHistoryEntryPtr entry =
4463 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574464 frame_state.navigation_api_key.value_or(std::u16string()),
4465 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094466 frame_state.item_sequence_number,
4467 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304468 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174469
Nate Chapin63db0d12022-01-20 22:03:304470 DCHECK(entry->url.empty() ||
4471 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574472 entries.push_back(std::move(entry));
4473 previous_item_sequence_number = frame_entry->item_sequence_number();
4474 }
4475 }
4476 // If |entries| was constructed by iterating backwards from
4477 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4478 // earliest-at-the-front. Reverse it.
4479 if (direction == Direction::kBack)
4480 std::reverse(entries.begin(), entries.end());
4481 return entries;
4482}
4483
Domenic Denicolacd30f5f82022-03-16 21:48:014484blink::mojom::NavigationApiHistoryEntryArraysPtr
4485NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554486 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574487 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404488 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444489 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404490 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574491
Nate Chapind1fe3612021-04-16 20:45:574492 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554493 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574494
Nate Chapine82339d02022-05-03 23:48:254495 // NOTE: |entry_index| is the index where this entry will commit if no
4496 // modifications are made between now and DidCommitNavigation. This is used to
4497 // walk |entries_| and determine which entries should be exposed by the
4498 // navigation API. It is important to calculate this correctly, because blink
4499 // will cancel a same-document history commit if it's not present in the
4500 // entries blink knows about.
4501 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574502 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304503 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254504 bool will_create_new_entry = false;
4505 if (GetPendingEntryIndex() != -1) {
4506 entry_index = GetPendingEntryIndex();
4507 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4508 pending_item_sequence_number = frame_entry->item_sequence_number();
4509 pending_document_sequence_number =
4510 frame_entry->document_sequence_number();
4511 }
4512 } else if (request &&
4513 !NavigationTypeUtils::IsReload(
4514 request->common_params().navigation_type) &&
4515 !NavigationTypeUtils::IsHistory(
4516 request->common_params().navigation_type) &&
4517 !request->common_params().should_replace_current_entry &&
4518 !request->common_params()
4519 .is_history_navigation_in_new_child_frame) {
4520 will_create_new_entry = true;
4521 entry_index = GetLastCommittedEntryIndex() + 1;
4522 // Don't set pending_item_sequence_number or
4523 // pending_document_sequence_number in this case - a new unique isn/dsn will
4524 // be calculated in the renderer later.
4525 } else if (GetLastCommittedEntryIndex() != -1) {
4526 entry_index = GetLastCommittedEntryIndex();
4527 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574528 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304529 pending_document_sequence_number =
4530 frame_entry->document_sequence_number();
4531 }
Nate Chapind1fe3612021-04-16 20:45:574532 }
4533
Domenic Denicolacd30f5f82022-03-16 21:48:014534 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254535 if (entry_index == -1) {
4536 // TODO(rakina): Exit early when there is no last committed entry.
4537 // Remove when InitialNavigationEntry ships.
4538 return entry_arrays;
4539 }
4540
Domenic Denicolacd30f5f82022-03-16 21:48:014541 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574542 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374543 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574544
4545 // Don't populate forward entries if they will be truncated by a new entry.
4546 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014547 entry_arrays->forward_entries =
4548 PopulateSingleNavigationApiHistoryEntryVector(
4549 Direction::kForward, entry_index, pending_origin, node,
4550 site_instance.get(), pending_item_sequence_number,
4551 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574552 }
Nate Chapin4e657a472022-02-06 03:38:374553 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574554}
4555
Nate Chapinfbfe5af2021-06-10 17:22:084556NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574557NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084558 FrameNavigationEntry* current_entry,
4559 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574560 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084561 if (!target_entry || !target_entry->committed_origin())
4562 return HistoryNavigationAction::kStopLooking;
4563 if (current_entry->site_instance() != target_entry->site_instance())
4564 return HistoryNavigationAction::kStopLooking;
4565 if (!current_entry->committed_origin()->IsSameOriginWith(
4566 *target_entry->committed_origin())) {
4567 return HistoryNavigationAction::kStopLooking;
4568 }
4569
4570 // NOTE: We don't actually care between kSameDocument and
4571 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574572 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084573 return HistoryNavigationAction::kDifferentDocument;
4574 return HistoryNavigationAction::kKeepLooking;
4575}
4576
Domenic Denicolacc094fb2022-03-16 23:40:574577void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204578 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144579 absl::optional<blink::scheduler::TaskAttributionId>
4580 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574581 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204582 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084583 FrameNavigationEntry* current_entry =
4584 GetLastCommittedEntry()->GetFrameEntry(node);
4585 if (!current_entry)
4586 return;
4587
Yoav Weiss8c573952022-11-17 17:35:134588 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4589 // when `navigation.traverseTo()` is called.
4590
Nate Chapinfbfe5af2021-06-10 17:22:084591 // We want to find the nearest matching entry that is contiguously
4592 // same-instance and same-origin. Check back first, then forward.
4593 // TODO(japhet): Link spec here once it exists.
4594 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574595 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084596 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4597 if (result == HistoryNavigationAction::kStopLooking)
4598 break;
4599 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144600 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084601 return;
4602 }
4603 }
4604 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574605 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084606 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4607 if (result == HistoryNavigationAction::kStopLooking)
4608 break;
4609 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144610 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084611 return;
4612 }
4613 }
Nate Chapinbf682fa32022-09-26 22:41:204614
4615 // If we fall through to here, a matching NavigationEntry couldn't be found.
4616 // Notify the renderer that the navigation was cancelled.
4617 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4618 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084619}
4620
Domenic Denicolacc094fb2022-03-16 23:40:574621bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304622 network::mojom::ReferrerPolicy referrer_policy) {
4623 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4624 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4625}
4626
shivanigithubf405bf0d2021-11-05 17:58:334627bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4628 const FrameTreeNode* frame_tree_node) const {
4629 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4630 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544631 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034632 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334633 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544634}
4635
Julie Jeongeun Kim0e242242022-11-30 10:45:094636void NavigationControllerImpl::DidChangeReferrerPolicy(
4637 FrameTreeNode* node,
4638 network::mojom::ReferrerPolicy referrer_policy) {
4639 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4640 if (!entry)
4641 return;
4642
4643 // The FrameNavigationEntry may want to change whether to protect its url
4644 // in the navigation API when the referrer policy changes.
4645 entry->set_protect_url_in_navigation_api(
4646 ShouldProtectUrlInNavigationApi(referrer_policy));
4647}
4648
[email protected]8ff00d72012-10-23 19:12:214649} // namespace content