blob: f2e7e5039a16b5d449c5290f1820191091a0b170 [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]c5b88d82012-10-06 17:03:3341#include "base/bind.h"
[email protected]eabfe1912014-05-12 10:07:2842#include "base/command_line.h"
Ayu Ishii2f825852022-03-08 19:47:3843#include "base/containers/adapters.h"
Rakina Zata Amni627360d2022-02-24 00:53:4044#include "base/debug/dump_without_crashing.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,
Lukasz Anforowicz641234d52019-11-07 21:07:10523 ui::PageTransition transition,
524 bool is_renderer_initiated,
525 const std::string& extra_headers,
526 BrowserContext* browser_context,
527 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory) {
528 return NavigationControllerImpl::CreateNavigationEntry(
529 url, referrer, std::move(initiator_origin),
530 nullptr /* source_site_instance */, transition, is_renderer_initiated,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17531 extra_headers, browser_context, std::move(blob_url_loader_factory),
532 true /* rewrite_virtual_urls */);
Lukasz Anforowicz641234d52019-11-07 21:07:10533}
534
535// static
536std::unique_ptr<NavigationEntryImpl>
537NavigationControllerImpl::CreateNavigationEntry(
538 const GURL& url,
539 Referrer referrer,
Anton Bikineevf62d1bf2021-05-15 17:56:07540 absl::optional<url::Origin> initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:10541 SiteInstance* source_site_instance,
dcheng9bfa5162016-04-09 01:00:57542 ui::PageTransition transition,
543 bool is_renderer_initiated,
544 const std::string& extra_headers,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:09545 BrowserContext* browser_context,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17546 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
547 bool rewrite_virtual_urls) {
548 GURL url_to_load = url;
549 GURL virtual_url = url;
[email protected]71fde352011-12-29 03:29:56550 bool reverse_on_redirect = false;
Julie Jeongeun Kim5b9aff72022-05-02 02:10:17551 if (rewrite_virtual_urls) {
552 RewriteUrlForNavigation(url, browser_context, &url_to_load, &virtual_url,
553 &reverse_on_redirect);
554 }
Lukasz Anforowicz641234d52019-11-07 21:07:10555 // Let the NTP override the navigation params and pretend that this is a
556 // browser-initiated, bookmark-like navigation.
557 GetContentClient()->browser()->OverrideNavigationParams(
Scott Violetcf6ea7e2021-06-09 21:09:21558 source_site_instance, &transition, &is_renderer_initiated, &referrer,
559 &initiator_origin);
Lukasz Anforowicz641234d52019-11-07 21:07:10560
Patrick Monettef507e982019-06-19 20:18:06561 auto entry = std::make_unique<NavigationEntryImpl>(
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28562 nullptr, // The site instance for tabs is sent on navigation
563 // (WebContents::GetSiteInstance).
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:58564 url_to_load, referrer, initiator_origin, std::u16string(), transition,
Rakina Zata Amniafd3c6582021-11-30 06:19:17565 is_renderer_initiated, blob_url_loader_factory,
566 /* is_initial_entry = */ false);
Camille Lamy5193caa2018-10-12 11:59:42567 entry->SetVirtualURL(virtual_url);
568 entry->set_user_typed_url(virtual_url);
[email protected]71fde352011-12-29 03:29:56569 entry->set_update_virtual_url_with_url(reverse_on_redirect);
570 entry->set_extra_headers(extra_headers);
Patrick Monettef507e982019-06-19 20:18:06571 return entry;
[email protected]71fde352011-12-29 03:29:56572}
573
[email protected]cdcb1dee2012-01-04 00:46:20574// static
575void NavigationController::DisablePromptOnRepost() {
576 g_check_for_repost = false;
577}
578
[email protected]c5b88d82012-10-06 17:03:33579base::Time NavigationControllerImpl::TimeSmoother::GetSmoothedTime(
580 base::Time t) {
581 // If |t| is between the water marks, we're in a run of duplicates
582 // or just getting out of it, so increase the high-water mark to get
583 // a time that probably hasn't been used before and return it.
584 if (low_water_mark_ <= t && t <= high_water_mark_) {
Peter Kastinge5a38ed2021-10-02 03:06:35585 high_water_mark_ += base::Microseconds(1);
[email protected]c5b88d82012-10-06 17:03:33586 return high_water_mark_;
587 }
588
589 // Otherwise, we're clear of the last duplicate run, so reset the
590 // water marks.
591 low_water_mark_ = high_water_mark_ = t;
592 return t;
593}
594
ckitagawa0faa5e42020-06-17 17:30:54595NavigationControllerImpl::ScopedShowRepostDialogForTesting::
596 ScopedShowRepostDialogForTesting()
597 : was_disallowed_(g_check_for_repost) {
598 g_check_for_repost = true;
599}
600
601NavigationControllerImpl::ScopedShowRepostDialogForTesting::
602 ~ScopedShowRepostDialogForTesting() {
603 g_check_for_repost = was_disallowed_;
604}
605
Nate Chapin9eb16be72022-09-23 22:54:31606NavigationControllerImpl::RemovedEntriesTracker::RemovedEntriesTracker(
607 base::SafeRef<NavigationControllerImpl> controller)
608 : controller_(controller) {
609 for (FrameTreeNode* frame_tree_node : controller_->frame_tree().Nodes()) {
610 names_to_nodes_.insert({frame_tree_node->unique_name(), frame_tree_node});
611 frame_tree_node_id_to_keys_.insert(
612 {frame_tree_node->frame_tree_node_id(), std::set<std::string>()});
613 if (auto* frame_entry = frame_tree_node->current_frame_host()
614 ->last_committed_frame_entry()) {
615 frame_tree_node_id_to_doc_seq_nos_.insert(
616 {frame_tree_node->frame_tree_node_id(),
617 frame_entry->document_sequence_number()});
618 }
619 }
620 PopulateKeySet(Direction::kBack);
621 PopulateKeySet(Direction::kForward);
622}
623
624void NavigationControllerImpl::RemovedEntriesTracker::PopulateKeySet(
625 Direction direction) {
626 // Keep track of which FrameTreeNodes may still have relevant API keys in
627 // additional FrameNavigationEntries.
628 std::set<FrameTreeNode*> nodes_to_process;
629 for (FrameTreeNode* node : controller_->frame_tree().Nodes()) {
630 nodes_to_process.insert(node);
631 }
632
633 const int offset = direction == Direction::kForward ? 1 : -1;
634 const int start = direction == Direction::kForward
635 ? controller_->GetLastCommittedEntryIndex()
636 : controller_->GetLastCommittedEntryIndex() - 1;
637 for (int i = start;
638 i >= 0 && i < controller_->GetEntryCount() && !nodes_to_process.empty();
639 i += offset) {
640 std::set<FrameTreeNode*> nodes_to_continue_processing;
641
642 NavigationEntryImpl* entry = controller_->GetEntryAtIndex(i);
643 entry->ForEachFrameEntry([this, &nodes_to_process,
644 &nodes_to_continue_processing,
645 &entry](FrameNavigationEntry* frame_entry) {
646 // Find the |node| that matches |frame_entry|, if any.
647 FrameTreeNode* node = nullptr;
648 if (frame_entry == entry->root_node()->frame_entry) {
649 node = controller_->frame_tree().root();
650 } else {
651 auto it = names_to_nodes_.find(frame_entry->frame_unique_name());
652 if (it == names_to_nodes_.end())
653 return;
654 node = it->second;
655 }
656
657 // Skip this node if a previous step determine there are no longer
658 // relevant navigation API keys in this direction.
659 if (nodes_to_process.find(node) == nodes_to_process.end())
660 return;
661
662 // Stop processing |node| if we reach a point where it's cross-origin.
663 // See also PopulateSingleNavigationApiHistoryEntryVector().
664 url::Origin frame_entry_origin =
665 frame_entry->committed_origin().value_or(url::Origin::Resolve(
666 frame_entry->url(),
667 frame_entry->initiator_origin().value_or(url::Origin())));
668 if (!node->current_origin().IsSameOriginWith(frame_entry_origin))
669 return;
670
671 frame_tree_node_id_to_keys_[node->frame_tree_node_id()].insert(
672 frame_entry->navigation_api_key());
673 // Mark |node| as needing more processing for the next entry.
674 nodes_to_continue_processing.insert(node);
675
676 // Check whether |node| went cross-document. If so, its children are
677 // no longer the same conceptual iframe as the current one, and
678 // should no longer be processed. This check is intentionally done
679 // after processing the current |node|, which may still have relevant
680 // discarded API keys.
681 if (frame_entry->document_sequence_number() !=
682 frame_tree_node_id_to_doc_seq_nos_[node->frame_tree_node_id()]) {
683 for (auto* descendant : node->frame_tree()->SubtreeNodes(node))
684 nodes_to_process.erase(descendant);
685 }
686 });
687
688 nodes_to_process.swap(nodes_to_continue_processing);
689 }
690}
691
692NavigationControllerImpl::RemovedEntriesTracker::~RemovedEntriesTracker() {
693 std::set<std::string> all_keys;
694 // Find all remaining navigation API keys after some entries have been
695 // removed.
696 for (auto& entry : controller_->entries_) {
697 entry->ForEachFrameEntry([&all_keys](FrameNavigationEntry* frame_entry) {
698 all_keys.insert(frame_entry->navigation_api_key());
699 });
700 }
701
702 // Notify each frame in the renderer of any disposed navigation API keys.
703 for (auto& id_to_keys : frame_tree_node_id_to_keys_) {
704 std::vector<std::string> disposed_keys;
705 for (const auto& key : id_to_keys.second) {
706 if (all_keys.find(key) == all_keys.end())
707 disposed_keys.push_back(key);
708 }
709 if (disposed_keys.empty())
710 continue;
711
712 FrameTreeNode* node = controller_->frame_tree().FindByID(id_to_keys.first);
713 auto& frame = node->current_frame_host()->GetAssociatedLocalFrame();
714 frame->NotifyNavigationApiOfDisposedEntries(disposed_keys);
715 }
716}
717
[email protected]d202a7c2012-01-04 07:53:47718NavigationControllerImpl::NavigationControllerImpl(
Carlos Caballero40b0efd2021-01-26 11:55:00719 BrowserContext* browser_context,
720 FrameTree& frame_tree,
721 NavigationControllerDelegate* delegate)
722 : frame_tree_(frame_tree),
723 browser_context_(browser_context),
[email protected]ec6c05f2013-10-23 18:41:57724 delegate_(delegate),
[email protected]69e797f2013-04-30 01:10:22725 ssl_manager_(this),
Lei Zhang96031532019-10-10 19:05:47726 get_timestamp_callback_(base::BindRepeating(&base::Time::Now)) {
[email protected]3d7474ff2011-07-27 17:47:37727 DCHECK(browser_context_);
initial.commit09911bf2008-07-26 23:55:29728}
729
[email protected]d202a7c2012-01-04 07:53:47730NavigationControllerImpl::~NavigationControllerImpl() {
arthursonzogni69a6a1b2019-09-17 09:23:00731 // The NavigationControllerImpl might be called inside its delegate
732 // destructor. Calling it is not valid anymore.
733 delegate_ = nullptr;
734 DiscardNonCommittedEntries();
initial.commit09911bf2008-07-26 23:55:29735}
736
Matt Falkenhagen548ed1562021-07-06 01:38:26737WebContents* NavigationControllerImpl::DeprecatedGetWebContents() {
738 return delegate_->DeprecatedGetWebContents();
[email protected]fbc5e5f92012-01-02 06:08:32739}
740
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57741BrowserContext* NavigationControllerImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:55742 return browser_context_;
743}
744
[email protected]d202a7c2012-01-04 07:53:47745void NavigationControllerImpl::Restore(
[email protected]5e369672009-11-03 23:48:30746 int selected_navigation,
[email protected]2ca1ea662012-10-04 02:26:36747 RestoreType type,
dcheng9bfa5162016-04-09 01:00:57748 std::vector<std::unique_ptr<NavigationEntry>>* entries) {
Charlie Reis23c26da2022-01-29 00:57:47749 // Note that it's possible for `entries_` to contain multiple entries at this
750 // point, as Restore() might be called on a NavigationController that is
751 // already used (e.g. due to WebView's restoreState() API), not only for fresh
752 // NavigationControllers. These entries are not cleared to preserve legacy
753 // behavior and also because `pending_entry_` might point to one of the
754 // pre-existing entries. An exception for this is when `entries_` contains
755 // only the initial NavigationEntry, which must be removed.
756
757 // Do not proceed if selected_navigation will be out of bounds for the updated
758 // entries_ list, since it will be assigned to last_committed_entry_index_ and
759 // used to index entries_.
760 // TODO(https://crbug.com/1287624): Consider also returning early if entries
761 // is empty, since there should be no work to do (rather than marking the
762 // existing entries as needing reload). Also consider returning early if the
763 // selected index is -1, which represents a no-committed-entry state.
764 if (selected_navigation < -1 ||
765 selected_navigation >=
766 base::checked_cast<int>(entries->size() + entries_.size())) {
767 return;
Rakina Zata Amni2322f4f82022-01-24 13:24:24768 }
Charlie Reis23c26da2022-01-29 00:57:47769
Rakina Zata Amni46087a12022-11-11 08:28:38770 // There will always be at least one entry (new NavigationControllers will
771 // have the initial NavigationEntry).
772 if (selected_navigation == -1)
773 selected_navigation = 0;
Charlie Reis23c26da2022-01-29 00:57:47774
Rakina Zata Amni46087a12022-11-11 08:28:38775 if (GetLastCommittedEntry()->IsInitialEntry() && entries->size() > 0) {
776 // If we are on the initial NavigationEntry, it must be the only entry in
777 // the list. Since it's impossible to do a history navigation to the
778 // initial NavigationEntry, `pending_entry_index_` must be -1 (but
779 // `pending_entry` might be set for a new non-history navigation).
780 // Note that we should not clear `entries_` if `entries` is empty (when
781 // InitialNavigationEntry mode is enabled), since that would leave us
782 // without any NavigationEntry.
783 CHECK_EQ(1, GetEntryCount());
784 CHECK_EQ(-1, pending_entry_index_);
785 entries_.clear();
Charlie Reis23c26da2022-01-29 00:57:47786 }
[email protected]ce3fa3c2009-04-20 19:55:57787
[email protected]ce3fa3c2009-04-20 19:55:57788 needs_reload_ = true;
Bo Liucdfa4b12018-11-06 00:21:44789 needs_reload_type_ = NeedsReloadType::kRestoreSession;
avif16f85a72015-11-13 18:25:03790 entries_.reserve(entries->size());
Charlie Reis23c26da2022-01-29 00:57:47791 for (auto& entry : *entries) {
Rakina Zata Amni996ee412022-02-17 04:51:43792 if (entry->GetURL().is_empty()) {
793 // We're trying to restore an entry with an empty URL (e.g. from
Rakina Zata Amni2729a512022-03-16 05:54:01794 // persisting the initial NavigationEntry [which is no longer possible but
795 // some old persisted sessions might still contain it] or when the
796 // serializer failed to write the URL because it's too long). Trying to
797 // restore and navigate to an entry with an empty URL will result in
798 // crashes, so change the URL to about:blank. See also
799 // https://crbug.com/1240138 and https://crbug.com/1299335.
Rakina Zata Amni996ee412022-02-17 04:51:43800 entry->SetURL(GURL(url::kAboutBlankURL));
801 }
dcheng36b6aec92015-12-26 06:16:36802 entries_.push_back(
803 NavigationEntryImpl::FromNavigationEntry(std::move(entry)));
Charlie Reis23c26da2022-01-29 00:57:47804 }
avif16f85a72015-11-13 18:25:03805
806 // At this point, the |entries| is full of empty scoped_ptrs, so it can be
807 // cleared out safely.
808 entries->clear();
[email protected]ce3fa3c2009-04-20 19:55:57809
810 // And finish the restore.
[email protected]2ca1ea662012-10-04 02:26:36811 FinishRestore(selected_navigation, type);
[email protected]ce3fa3c2009-04-20 19:55:57812}
813
toyoshim6142d96f2016-12-19 09:07:25814void NavigationControllerImpl::Reload(ReloadType reload_type,
815 bool check_for_repost) {
Rakina Zata Amnid605d462022-06-01 10:17:03816 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "Reload_type",
817 (int)reload_type);
818 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "Reload_check",
819 check_for_repost);
liaoyuke9168fba2017-03-10 19:20:28820 DCHECK_NE(ReloadType::NONE, reload_type);
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28821 NavigationEntryImpl* entry = nullptr;
[email protected]59167c22013-06-03 18:07:32822 int current_index = -1;
823
Carlos IL42b416592019-10-07 23:10:36824 if (entry_replaced_by_post_commit_error_) {
825 // If there is an entry that was replaced by a currently active post-commit
826 // error navigation, this can't be the initial navigation.
827 DCHECK(!IsInitialNavigation());
828 // If the current entry is a post commit error, we reload the entry it
829 // replaced instead. We leave the error entry in place until a commit
830 // replaces it, but the pending entry points to the original entry in the
831 // meantime. Note that NavigateToExistingPendingEntry is able to handle the
832 // case that pending_entry_ != entries_[pending_entry_index_].
833 entry = entry_replaced_by_post_commit_error_.get();
834 current_index = GetCurrentEntryIndex();
835 } else if (IsInitialNavigation() && pending_entry_) {
836 // If we are reloading the initial navigation, just use the current
837 // pending entry. Otherwise look up the current entry.
[email protected]59167c22013-06-03 18:07:32838 entry = pending_entry_;
839 // The pending entry might be in entries_ (e.g., after a Clone), so we
840 // should also update the current_index.
841 current_index = pending_entry_index_;
842 } else {
arthursonzogni69a6a1b2019-09-17 09:23:00843 DiscardNonCommittedEntries();
[email protected]59167c22013-06-03 18:07:32844 current_index = GetCurrentEntryIndex();
845 if (current_index != -1) {
creis3da03872015-02-20 21:12:32846 entry = GetEntryAtIndex(current_index);
[email protected]59167c22013-06-03 18:07:32847 }
[email protected]979a4bc2013-04-24 01:27:15848 }
[email protected]241db352013-04-22 18:04:05849
[email protected]59167c22013-06-03 18:07:32850 // If we are no where, then we can't reload. TODO(darin): We should add a
851 // CanReload method.
852 if (!entry)
853 return;
854
Rakina Zata Amnif297a802022-01-18 03:53:43855 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
856 // We should never navigate to an existing initial NavigationEntry that is
857 // the initial NavigationEntry for the initial empty document that hasn't
858 // been overridden by the synchronous about:blank commit, to preserve
859 // legacy behavior where trying to reload when the main frame is on the
860 // initial empty document won't result in a navigation. See also
861 // https://crbug.com/1277414.
862 return;
863 }
864
Aran Gilman37d11632019-10-08 23:07:15865 if (g_check_for_repost && check_for_repost && entry->GetHasPostData()) {
[email protected]a3a1d142008-12-19 00:42:30866 // The user is asking to reload a page with POST data. Prompt to make sure
[email protected]b5bb35f2009-02-05 20:17:07867 // they really want to do this. If they do, the dialog will call us back
868 // with check_for_repost = false.
[email protected]ec6c05f2013-10-23 18:41:57869 delegate_->NotifyBeforeFormRepostWarningShow();
[email protected]965bb092010-04-09 11:59:02870
[email protected]106a0812010-03-18 00:15:12871 pending_reload_ = reload_type;
[email protected]ec6c05f2013-10-23 18:41:57872 delegate_->ActivateAndShowRepostFormWarningDialog();
Lei Zhang96031532019-10-10 19:05:47873 return;
initial.commit09911bf2008-07-26 23:55:29874 }
Lei Zhang96031532019-10-10 19:05:47875
Wang Huia25efabc2022-09-24 17:27:22876 // Set ReloadType for |entry|.
877 entry->set_reload_type(reload_type);
878
Lei Zhang96031532019-10-10 19:05:47879 if (!IsInitialNavigation())
880 DiscardNonCommittedEntries();
881
882 pending_entry_ = entry;
883 pending_entry_index_ = current_index;
884 pending_entry_->SetTransitionType(ui::PAGE_TRANSITION_RELOAD);
885
Nate Chapin45f620582021-09-30 17:45:43886 // location.reload() goes through BeginNavigation, so all reloads triggered
887 // via this codepath are browser initiated.
Yoav Weiss8c573952022-11-17 17:35:13888 NavigateToExistingPendingEntry(
889 reload_type,
890 /*initiator_rfh=*/nullptr,
891 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
892 /*navigation_api_key=*/nullptr);
initial.commit09911bf2008-07-26 23:55:29893}
894
[email protected]d202a7c2012-01-04 07:53:47895void NavigationControllerImpl::CancelPendingReload() {
toyoshim0df1d3a2016-09-09 09:52:48896 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12897}
898
[email protected]d202a7c2012-01-04 07:53:47899void NavigationControllerImpl::ContinuePendingReload() {
Wang Hui96ab1012022-10-11 02:05:49900 // If the pending reload type has been cleared by another navigation
901 // committing, then do not proceed to reload after a form repost dialog.
toyoshim0df1d3a2016-09-09 09:52:48902 if (pending_reload_ == ReloadType::NONE) {
Wang Hui96ab1012022-10-11 02:05:49903 return;
[email protected]106a0812010-03-18 00:15:12904 }
Wang Hui96ab1012022-10-11 02:05:49905 Reload(pending_reload_, false);
906 pending_reload_ = ReloadType::NONE;
[email protected]106a0812010-03-18 00:15:12907}
908
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57909bool NavigationControllerImpl::IsInitialNavigation() {
[email protected]27ba81c2012-08-21 17:04:09910 return is_initial_navigation_;
[email protected]c70f9b82010-04-21 07:31:11911}
912
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57913bool NavigationControllerImpl::IsInitialBlankNavigation() {
Rakina Zata Amni46087a12022-11-11 08:28:38914 // Check that we're on the initial NavigationEntry and that this is not a
915 // cloned tab.
916 return IsInitialNavigation() && GetEntryCount() == 1 &&
917 GetLastCommittedEntry()->IsInitialEntry() &&
918 GetLastCommittedEntry()->restore_type() == RestoreType::kNotRestored;
creis10a4ab72015-10-13 17:22:40919}
920
Aran Gilman37d11632019-10-08 23:07:15921NavigationEntryImpl* NavigationControllerImpl::GetEntryWithUniqueID(
922 int nav_entry_id) const {
avi254eff02015-07-01 08:27:58923 int index = GetEntryIndexWithUniqueID(nav_entry_id);
avif16f85a72015-11-13 18:25:03924 return (index != -1) ? entries_[index].get() : nullptr;
avi254eff02015-07-01 08:27:58925}
926
Adithya Srinivasan9b0c99c2021-08-10 15:19:45927NavigationEntryImpl*
928NavigationControllerImpl::GetEntryWithUniqueIDIncludingPending(
929 int nav_entry_id) const {
930 NavigationEntryImpl* entry = GetEntryWithUniqueID(nav_entry_id);
931 if (entry)
932 return entry;
933 return pending_entry_ && pending_entry_->GetUniqueID() == nav_entry_id
Keishi Hattori0e45c022021-11-27 09:25:52934 ? pending_entry_.get()
Adithya Srinivasan9b0c99c2021-08-10 15:19:45935 : nullptr;
936}
937
W. James MacLeanc07dc41b2022-07-25 18:52:16938void NavigationControllerImpl::RegisterExistingOriginAsHavingDefaultIsolation(
W. James MacLean1c40862c2020-04-27 21:05:57939 const url::Origin& origin) {
940 for (int i = 0; i < GetEntryCount(); i++) {
941 auto* entry = GetEntryAtIndex(i);
W. James MacLeanc07dc41b2022-07-25 18:52:16942 entry->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57943 }
944 if (entry_replaced_by_post_commit_error_) {
945 // It's possible we could come back to this entry if the error
946 // page/interstitial goes away.
947 entry_replaced_by_post_commit_error_
W. James MacLeanc07dc41b2022-07-25 18:52:16948 ->RegisterExistingOriginAsHavingDefaultIsolation(origin);
W. James MacLean1c40862c2020-04-27 21:05:57949 }
W. James MacLean1c40862c2020-04-27 21:05:57950}
951
avi25764702015-06-23 15:43:37952void NavigationControllerImpl::SetPendingEntry(
dcheng9bfa5162016-04-09 01:00:57953 std::unique_ptr<NavigationEntryImpl> entry) {
arthursonzogni69a6a1b2019-09-17 09:23:00954 DiscardNonCommittedEntries();
avi25764702015-06-23 15:43:37955 pending_entry_ = entry.release();
arthursonzogni5c4c202d2017-04-25 23:41:27956 DCHECK_EQ(-1, pending_entry_index_);
[email protected]765b35502008-08-21 00:51:20957}
958
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57959NavigationEntryImpl* NavigationControllerImpl::GetActiveEntry() {
[email protected]cbab76d2008-10-13 22:42:47960 if (pending_entry_)
961 return pending_entry_;
962 return GetLastCommittedEntry();
[email protected]765b35502008-08-21 00:51:20963}
964
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57965NavigationEntryImpl* NavigationControllerImpl::GetVisibleEntry() {
[email protected]59167c22013-06-03 18:07:32966 // The pending entry is safe to return for new (non-history), browser-
967 // initiated navigations. Most renderer-initiated navigations should not
968 // show the pending entry, to prevent URL spoof attacks.
969 //
970 // We make an exception for renderer-initiated navigations in new tabs, as
971 // long as no other page has tried to access the initial empty document in
972 // the new tab. If another page modifies this blank page, a URL spoof is
973 // possible, so we must stop showing the pending entry.
[email protected]59167c22013-06-03 18:07:32974 bool safe_to_show_pending =
975 pending_entry_ &&
976 // Require a new navigation.
avi0dca04d2015-01-26 20:21:09977 pending_entry_index_ == -1 &&
[email protected]59167c22013-06-03 18:07:32978 // Require either browser-initiated or an unmodified new tab.
[email protected]aa62afd2014-04-22 19:22:46979 (!pending_entry_->is_renderer_initiated() || IsUnmodifiedBlankTab());
[email protected]59167c22013-06-03 18:07:32980
981 // Also allow showing the pending entry for history navigations in a new tab,
982 // such as Ctrl+Back. In this case, no existing page is visible and no one
983 // can script the new tab before it commits.
Aran Gilman37d11632019-10-08 23:07:15984 if (!safe_to_show_pending && pending_entry_ && pending_entry_index_ != -1 &&
985 IsInitialNavigation() && !pending_entry_->is_renderer_initiated())
[email protected]59167c22013-06-03 18:07:32986 safe_to_show_pending = true;
987
988 if (safe_to_show_pending)
[email protected]867e1f92011-08-30 19:01:19989 return pending_entry_;
990 return GetLastCommittedEntry();
991}
992
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57993int NavigationControllerImpl::GetCurrentEntryIndex() {
[email protected]765b35502008-08-21 00:51:20994 if (pending_entry_index_ != -1)
995 return pending_entry_index_;
996 return last_committed_entry_index_;
997}
998
Lucas Furukawa Gadani5553a1582019-01-08 18:55:57999NavigationEntryImpl* NavigationControllerImpl::GetLastCommittedEntry() {
Rakina Zata Amni46087a12022-11-11 08:28:381000 CHECK_NE(last_committed_entry_index_, -1);
avif16f85a72015-11-13 18:25:031001 return entries_[last_committed_entry_index_].get();
[email protected]765b35502008-08-21 00:51:201002}
1003
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571004bool NavigationControllerImpl::CanViewSource() {
Jeremy Roman2d8dfe132021-07-06 20:51:261005 const std::string& mime_type =
Ali Hijazid87307d2022-11-07 20:15:031006 frame_tree_->root()->current_frame_host()->GetPage().contents_mime_type();
Kinuko Yasuda74702f92017-07-31 03:27:531007 bool is_viewable_mime_type = blink::IsSupportedNonImageMimeType(mime_type) &&
1008 !media::IsSupportedMediaMimeType(mime_type);
[email protected]6286a3792013-10-09 04:03:271009 NavigationEntry* visible_entry = GetVisibleEntry();
1010 return visible_entry && !visible_entry->IsViewSourceMode() &&
Carlos ILd51e7702020-05-07 18:51:391011 is_viewable_mime_type;
[email protected]31682282010-01-15 18:05:161012}
1013
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571014int NavigationControllerImpl::GetLastCommittedEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:271015 // The last committed entry index must always be less than the number of
Rakina Zata Amnie2d31312022-11-18 03:38:451016 // entries.
arthursonzogni5c4c202d2017-04-25 23:41:271017 DCHECK_LT(last_committed_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:551018 return last_committed_entry_index_;
1019}
1020
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571021int NavigationControllerImpl::GetEntryCount() {
Rakina Zata Amnie2d31312022-11-18 03:38:451022 DCHECK_GE(entries_.size(), 1u);
Carlos IL4dea8902020-05-26 15:14:291023 DCHECK_LE(entries_.size(), max_entry_count());
[email protected]a26023822011-12-29 00:23:551024 return static_cast<int>(entries_.size());
1025}
1026
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571027NavigationEntryImpl* NavigationControllerImpl::GetEntryAtIndex(int index) {
avi25764702015-06-23 15:43:371028 if (index < 0 || index >= GetEntryCount())
1029 return nullptr;
1030
avif16f85a72015-11-13 18:25:031031 return entries_[index].get();
[email protected]022af742011-12-28 18:37:251032}
1033
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571034NavigationEntryImpl* NavigationControllerImpl::GetEntryAtOffset(int offset) {
avi057ce1492015-06-29 15:59:471035 return GetEntryAtIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201036}
1037
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571038int NavigationControllerImpl::GetIndexForOffset(int offset) {
[email protected]7bc2b032012-12-19 22:45:461039 return GetCurrentEntryIndex() + offset;
[email protected]9ba14052012-06-22 23:50:031040}
1041
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571042bool NavigationControllerImpl::CanGoBack() {
Shivani Sharma298d12852019-01-22 20:04:031043 for (int index = GetIndexForOffset(-1); index >= 0; index--) {
1044 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1045 return true;
1046 }
1047 return false;
[email protected]765b35502008-08-21 00:51:201048}
1049
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571050bool NavigationControllerImpl::CanGoForward() {
WangHui74286d52021-03-31 16:17:151051 for (int index = GetIndexForOffset(1); index < GetEntryCount(); index++) {
1052 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1053 return true;
1054 }
1055 return false;
[email protected]765b35502008-08-21 00:51:201056}
1057
Lucas Furukawa Gadani5553a1582019-01-08 18:55:571058bool NavigationControllerImpl::CanGoToOffset(int offset) {
[email protected]9ba14052012-06-22 23:50:031059 int index = GetIndexForOffset(offset);
1060 return index >= 0 && index < GetEntryCount();
1061}
1062
Xiaohan Wang7f8052e02022-01-14 18:44:281063#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151064bool NavigationControllerImpl::CanGoToOffsetWithSkipping(int offset) {
WangHui74286d52021-03-31 16:17:151065 if (offset == 0)
1066 return true;
1067 int increment = offset > 0 ? 1 : -1;
1068 int non_skippable_entries = 0;
1069 for (int index = GetIndexForOffset(increment);
1070 index >= 0 && index < GetEntryCount(); index += increment) {
1071 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1072 non_skippable_entries++;
1073
1074 if (non_skippable_entries == std::abs(offset))
1075 return true;
1076 }
1077 return false;
1078}
1079#endif
1080
[email protected]d202a7c2012-01-04 07:53:471081void NavigationControllerImpl::GoBack() {
shivanisha55201872018-12-13 04:29:061082 int target_index = GetIndexForOffset(-1);
1083
Elly Fong-Jones40ee8112021-06-23 19:10:521084 // Move the target index past the skippable entries.
Shivani Sharma298d12852019-01-22 20:04:031085 bool all_skippable_entries = true;
Elly Fong-Jones40ee8112021-06-23 19:10:521086 while (target_index >= 0) {
1087 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui()) {
Shivani Sharma298d12852019-01-22 20:04:031088 all_skippable_entries = false;
shivanisha55201872018-12-13 04:29:061089 break;
Shivani Sharma2d5b4b6b2019-01-08 16:07:161090 }
Elly Fong-Jones40ee8112021-06-23 19:10:521091 target_index--;
shivanisha55201872018-12-13 04:29:061092 }
Miyoung Shin1c565c912021-03-17 12:11:211093
Shivani Sharma298d12852019-01-22 20:04:031094 // Do nothing if all entries are skippable. Normally this path would not
1095 // happen as consumers would have already checked it in CanGoBack but a lot of
1096 // tests do not do that.
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421097 if (all_skippable_entries)
Shivani Sharma298d12852019-01-22 20:04:031098 return;
shivanisha55201872018-12-13 04:29:061099
shivanisha55201872018-12-13 04:29:061100 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201101}
1102
[email protected]d202a7c2012-01-04 07:53:471103void NavigationControllerImpl::GoForward() {
shivanisha55201872018-12-13 04:29:061104 int target_index = GetIndexForOffset(1);
1105
Shivani Sharma2d5b4b6b2019-01-08 16:07:161106 // Note that at least one entry (the last one) will be non-skippable since
1107 // entries are marked skippable only when they add another entry because of
1108 // redirect or pushState.
Elly Fong-Jones40ee8112021-06-23 19:10:521109 while (target_index < static_cast<int>(entries_.size())) {
1110 if (!GetEntryAtIndex(target_index)->should_skip_on_back_forward_ui())
shivanisha55201872018-12-13 04:29:061111 break;
Elly Fong-Jones40ee8112021-06-23 19:10:521112 target_index++;
shivanisha55201872018-12-13 04:29:061113 }
shivanisha55201872018-12-13 04:29:061114 GoToIndex(target_index);
[email protected]765b35502008-08-21 00:51:201115}
1116
[email protected]d202a7c2012-01-04 07:53:471117void NavigationControllerImpl::GoToIndex(int index) {
Yoav Weiss8c573952022-11-17 17:35:131118 GoToIndex(index, /*initiator_rfh=*/nullptr,
1119 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
1120 /*navigation_api_key=*/nullptr);
Dave Tapuska8bfd84c2019-03-26 20:47:161121}
1122
Nate Chapinbf682fa32022-09-26 22:41:201123void NavigationControllerImpl::GoToIndex(
1124 int index,
1125 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131126 absl::optional<blink::scheduler::TaskAttributionId>
1127 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201128 const std::string* navigation_api_key) {
Rakina Zata Amnid605d462022-06-01 10:17:031129 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy_caller1", "GoToIndex_index", index);
sunjian30574a62017-03-21 21:39:441130 TRACE_EVENT0("browser,navigation,benchmark",
1131 "NavigationControllerImpl::GoToIndex");
[email protected]765b35502008-08-21 00:51:201132 if (index < 0 || index >= static_cast<int>(entries_.size())) {
1133 NOTREACHED();
1134 return;
1135 }
1136
Rakina Zata Amnif297a802022-01-18 03:53:431137 if (entries_[index]->IsInitialEntryNotForSynchronousAboutBlank()) {
1138 // We should never navigate to an existing initial NavigationEntry that is
1139 // the initial NavigationEntry for the initial empty document that hasn't
1140 // been overridden by the synchronous about:blank commit, to preserve
1141 // legacy behavior where trying to reload when the main frame is on the
1142 // initial empty document won't result in a navigation. See also
1143 // https://crbug.com/1277414.
1144 return;
1145 }
1146
[email protected]cbab76d2008-10-13 22:42:471147 DiscardNonCommittedEntries();
[email protected]765b35502008-08-21 00:51:201148
arthursonzogni5c4c202d2017-04-25 23:41:271149 DCHECK_EQ(nullptr, pending_entry_);
1150 DCHECK_EQ(-1, pending_entry_index_);
Rakina Zata Amnif297a802022-01-18 03:53:431151
arthursonzogni5c4c202d2017-04-25 23:41:271152 pending_entry_ = entries_[index].get();
[email protected]765b35502008-08-21 00:51:201153 pending_entry_index_ = index;
arthursonzogni5c4c202d2017-04-25 23:41:271154 pending_entry_->SetTransitionType(ui::PageTransitionFromInt(
1155 pending_entry_->GetTransitionType() | ui::PAGE_TRANSITION_FORWARD_BACK));
Nate Chapinbf682fa32022-09-26 22:41:201156 NavigateToExistingPendingEntry(ReloadType::NONE, initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131157 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:201158 navigation_api_key);
[email protected]765b35502008-08-21 00:51:201159}
1160
[email protected]d202a7c2012-01-04 07:53:471161void NavigationControllerImpl::GoToOffset(int offset) {
toyoshim3af4d502016-03-30 12:38:121162 // Note: This is actually reached in unit tests.
[email protected]9ba14052012-06-22 23:50:031163 if (!CanGoToOffset(offset))
[email protected]765b35502008-08-21 00:51:201164 return;
1165
[email protected]9ba14052012-06-22 23:50:031166 GoToIndex(GetIndexForOffset(offset));
[email protected]765b35502008-08-21 00:51:201167}
1168
Nate Chapinbf682fa32022-09-26 22:41:201169void NavigationControllerImpl::GoToOffsetFromRenderer(
1170 int offset,
Yoav Weiss8c573952022-11-17 17:35:131171 RenderFrameHostImpl* initiator_rfh,
1172 absl::optional<blink::scheduler::TaskAttributionId>
1173 soft_navigation_heuristics_task_id) {
Nate Chapin45f620582021-09-30 17:45:431174 // Note: This is actually reached in unit tests.
1175 if (!CanGoToOffset(offset))
1176 return;
1177
Nate Chapinbf682fa32022-09-26 22:41:201178 GoToIndex(GetIndexForOffset(offset), initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:131179 soft_navigation_heuristics_task_id,
1180 /*navigation_api_key=*/nullptr);
Nate Chapin45f620582021-09-30 17:45:431181}
1182
Xiaohan Wang7f8052e02022-01-14 18:44:281183#if BUILDFLAG(IS_ANDROID)
WangHui74286d52021-03-31 16:17:151184void NavigationControllerImpl::GoToOffsetWithSkipping(int offset) {
1185 // Note: This is actually reached in unit tests.
1186 if (!CanGoToOffsetWithSkipping(offset))
1187 return;
1188
Elly Fong-Jonesccc6d1f2021-06-14 18:32:421189 if (offset == 0) {
WangHui74286d52021-03-31 16:17:151190 GoToIndex(GetIndexForOffset(offset));
1191 return;
1192 }
1193 int increment = offset > 0 ? 1 : -1;
1194 // Find the offset without counting skippable entries.
1195 int target_index = GetIndexForOffset(increment);
1196 int non_skippable_entries = 0;
1197 for (int index = target_index; index >= 0 && index < GetEntryCount();
1198 index += increment) {
1199 if (!GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
1200 non_skippable_entries++;
1201
1202 if (non_skippable_entries == std::abs(offset)) {
1203 target_index = index;
1204 break;
1205 }
1206 }
1207
1208 GoToIndex(target_index);
1209}
1210#endif
1211
[email protected]41374f12013-07-24 02:49:281212bool NavigationControllerImpl::RemoveEntryAtIndex(int index) {
Aran Gilman37d11632019-10-08 23:07:151213 if (index == last_committed_entry_index_ || index == pending_entry_index_)
[email protected]41374f12013-07-24 02:49:281214 return false;
[email protected]6a13a6c2011-12-20 21:47:121215
[email protected]43032342011-03-21 14:10:311216 RemoveEntryAtIndexInternal(index);
[email protected]41374f12013-07-24 02:49:281217 return true;
[email protected]cbab76d2008-10-13 22:42:471218}
1219
Michael Thiessen9b14d512019-09-23 21:19:471220void NavigationControllerImpl::PruneForwardEntries() {
1221 DiscardNonCommittedEntries();
1222 int remove_start_index = last_committed_entry_index_ + 1;
Lei Zhang96031532019-10-10 19:05:471223 int num_removed = static_cast<int>(entries_.size()) - remove_start_index;
Michael Thiessen9b14d512019-09-23 21:19:471224 if (num_removed <= 0)
1225 return;
Nate Chapin9eb16be72022-09-23 22:54:311226 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
Michael Thiessen9b14d512019-09-23 21:19:471227 entries_.erase(entries_.begin() + remove_start_index, entries_.end());
1228 NotifyPrunedEntries(this, remove_start_index /* start index */,
1229 num_removed /* count */);
1230}
1231
Aran Gilman37d11632019-10-08 23:07:151232void NavigationControllerImpl::UpdateVirtualURLToURL(NavigationEntryImpl* entry,
1233 const GURL& new_url) {
[email protected]38178a42009-12-17 18:58:321234 GURL new_virtual_url(new_url);
[email protected]825b1662012-03-12 19:07:311235 if (BrowserURLHandlerImpl::GetInstance()->ReverseURLRewrite(
[email protected]36fc0392011-12-25 03:59:511236 &new_virtual_url, entry->GetVirtualURL(), browser_context_)) {
1237 entry->SetVirtualURL(new_virtual_url);
[email protected]38178a42009-12-17 18:58:321238 }
1239}
1240
Harkiran Bolariaba823e42021-05-21 18:30:361241base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURL(
1242 const GURL& url,
1243 const Referrer& referrer,
1244 ui::PageTransition transition,
1245 const std::string& extra_headers) {
[email protected]cf002332012-08-14 19:17:471246 LoadURLParams params(url);
1247 params.referrer = referrer;
1248 params.transition_type = transition;
1249 params.extra_headers = extra_headers;
Harkiran Bolariaba823e42021-05-21 18:30:361250 return LoadURLWithParams(params);
[email protected]cf002332012-08-14 19:17:471251}
1252
Harkiran Bolariaba823e42021-05-21 18:30:361253base::WeakPtr<NavigationHandle> NavigationControllerImpl::LoadURLWithParams(
1254 const LoadURLParams& params) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061255 if (params.is_renderer_initiated)
1256 DCHECK(params.initiator_origin.has_value());
1257
naskob8744d22014-08-28 17:07:431258 TRACE_EVENT1("browser,navigation",
Aran Gilman37d11632019-10-08 23:07:151259 "NavigationControllerImpl::LoadURLWithParams", "url",
1260 params.url.possibly_invalid_spec());
Ian Vollick9dda0522019-09-11 02:24:291261 bool is_explicit_navigation =
1262 GetContentClient()->browser()->IsExplicitNavigation(
1263 params.transition_type);
1264 if (HandleDebugURL(params.url, params.transition_type,
1265 is_explicit_navigation)) {
[email protected]47752982014-07-29 08:01:431266 // If Telemetry is running, allow the URL load to proceed as if it's
1267 // unhandled, otherwise Telemetry can't tell if Navigation completed.
avi83883c82014-12-23 00:08:491268 if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
[email protected]47752982014-07-29 08:01:431269 cc::switches::kEnableGpuBenchmarking))
Harkiran Bolariaba823e42021-05-21 18:30:361270 return nullptr;
[email protected]47752982014-07-29 08:01:431271 }
[email protected]8bf1048012012-02-08 01:22:181272
[email protected]cf002332012-08-14 19:17:471273 // Checks based on params.load_type.
1274 switch (params.load_type) {
1275 case LOAD_TYPE_DEFAULT:
lukasza477a5a22016-06-16 18:28:431276 case LOAD_TYPE_HTTP_POST:
[email protected]cf002332012-08-14 19:17:471277 break;
1278 case LOAD_TYPE_DATA:
[email protected]cca6f392014-05-28 21:32:261279 if (!params.url.SchemeIs(url::kDataScheme)) {
[email protected]cf002332012-08-14 19:17:471280 NOTREACHED() << "Data load must use data scheme.";
Harkiran Bolariaba823e42021-05-21 18:30:361281 return nullptr;
[email protected]cf002332012-08-14 19:17:471282 }
1283 break;
Lukasz Anforowiczbb0cfd5e2017-12-14 22:39:461284 }
[email protected]e47ae9472011-10-13 19:48:341285
[email protected]e47ae9472011-10-13 19:48:341286 // The user initiated a load, we don't need to reload anymore.
1287 needs_reload_ = false;
1288
Harkiran Bolariaba823e42021-05-21 18:30:361289 return NavigateWithoutEntry(params);
[email protected]132e281a2012-07-31 18:32:441290}
1291
Mohamed Abdelhalim833de902019-09-16 17:41:451292bool NavigationControllerImpl::PendingEntryMatchesRequest(
1293 NavigationRequest* request) const {
creisb4dc9332016-03-14 21:39:191294 return pending_entry_ &&
Mohamed Abdelhalim833de902019-09-16 17:41:451295 pending_entry_->GetUniqueID() == request->nav_entry_id();
creisb4dc9332016-03-14 21:39:191296}
1297
[email protected]d202a7c2012-01-04 07:53:471298bool NavigationControllerImpl::RendererDidNavigate(
creis3da03872015-02-20 21:12:321299 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071300 const mojom::DidCommitProvisionalLoadParams& params,
peary21b0f797b2016-09-28 17:28:331301 LoadCommittedDetails* details,
Eugene But712f03d2018-05-22 16:03:441302 bool is_same_document_navigation,
Nate Chapinc7019dd7d2021-06-25 18:29:251303 bool was_on_initial_empty_document,
Shivani Sharmaffb32b82019-04-09 16:58:471304 bool previous_document_was_activated,
Camille Lamy10aafcd32018-12-05 15:48:131305 NavigationRequest* navigation_request) {
1306 DCHECK(navigation_request);
Chris Bookholt27faf8d2022-01-20 01:03:331307
1308 // Note: validation checks and renderer kills due to invalid commit messages
1309 // must happen before getting here, in
1310 // RenderFrameHostImpl::ValidateDidCommitParams. By the time we get here, some
1311 // effects of the navigation have already occurred.
1312
[email protected]cd2e15742013-03-08 04:08:311313 is_initial_navigation_ = false;
1314
Wang Hui96ab1012022-10-11 02:05:491315 // Any pending request to repost a form submission is no longer valid, since a
1316 // different NavigationEntry is committing.
1317 pending_reload_ = ReloadType::NONE;
1318
[email protected]0e8db942008-09-24 21:21:481319 // Save the previous state before we clobber it.
aelias100c9192017-01-13 00:01:431320 bool overriding_user_agent_changed = false;
Rakina Zata Amnie2d31312022-11-18 03:38:451321 if (entry_replaced_by_post_commit_error_) {
1322 // Same document navigation events with a post-commit error should already
1323 // be blocked by RenderFrameHostImpl::ValidateDidCommitParams() before
1324 // reaching here.
1325 CHECK(!is_same_document_navigation);
Chris Bookholt27faf8d2022-01-20 01:03:331326
Rakina Zata Amnie2d31312022-11-18 03:38:451327 // Any commit while a post-commit error page is showing should put the
1328 // original entry back, replacing the error page's entry. This includes
1329 // reloads, where the original entry was used as the pending entry and
1330 // should now be at the correct index at commit time.
1331 entries_[last_committed_entry_index_] =
1332 std::move(entry_replaced_by_post_commit_error_);
[email protected]0e8db942008-09-24 21:21:481333 }
Rakina Zata Amnie2d31312022-11-18 03:38:451334 details->previous_main_frame_url = GetLastCommittedEntry()->GetURL();
1335 details->previous_entry_index = GetLastCommittedEntryIndex();
1336 if (PendingEntryMatchesRequest(navigation_request) &&
1337 pending_entry_->GetIsOverridingUserAgent() !=
1338 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1339 overriding_user_agent_changed = true;
1340 }
1341#if BUILDFLAG(IS_ANDROID)
1342 // TODO(crbug.com/1266277): Clean up the logic of setting
1343 // |overriding_user_agent_changed| post-launch.
1344 if (base::FeatureList::IsEnabled(features::kRequestDesktopSiteExceptions) ||
1345 base::FeatureList::IsEnabled(features::kRequestDesktopSiteAdditions)) {
1346 // Must honor user agent overrides in the |navigation_request|, such as
1347 // from things like RequestDesktopSiteWebContentsObserverAndroid. As a
1348 // result, besides comparing |pending_entry_|'s user agent against
1349 // LastCommittedEntry's, also need to compare |navigation_request|'s user
1350 // agent against LastCommittedEntry's.
1351 if (navigation_request->is_overriding_user_agent() !=
1352 GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
1353 overriding_user_agent_changed = true;
1354 }
1355 }
1356#endif // BUILDFLAG(IS_ANDROID)
[email protected]ecd9d8702008-08-28 22:10:171357
Dave Tapuskaa2ab4f252021-07-08 21:31:281358 bool is_main_frame_navigation = !rfh->GetParent();
1359
Alexander Timind2f2e4f22019-04-02 20:04:531360 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1361 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281362 // For primary frame tree navigations, choose an appropriate
Rakina Zata Amni63b5e8092022-05-20 11:25:141363 // BackForwardCacheMetrics to be associated with the new navigation's
1364 // NavigationEntry, by either creating a new object or reusing the previous
1365 // entry's one.
Dave Tapuskaa2ab4f252021-07-08 21:31:281366 scoped_refptr<BackForwardCacheMetrics> back_forward_cache_metrics;
1367 if (navigation_request->frame_tree_node()->frame_tree()->type() ==
1368 FrameTree::Type::kPrimary) {
Rakina Zata Amni63b5e8092022-05-20 11:25:141369 back_forward_cache_metrics = BackForwardCacheMetrics::
1370 CreateOrReuseBackForwardCacheMetricsForNavigation(
Dave Tapuskaa2ab4f252021-07-08 21:31:281371 GetLastCommittedEntry(), is_main_frame_navigation,
1372 params.document_sequence_number);
1373 }
Alexander Timind2f2e4f22019-04-02 20:04:531374 // Notify the last active entry that we have navigated away.
Dave Tapuskaa2ab4f252021-07-08 21:31:281375 if (is_main_frame_navigation && !is_same_document_navigation) {
Rakina Zata Amnie2d31312022-11-18 03:38:451376 if (auto* metrics = GetLastCommittedEntry()->back_forward_cache_metrics()) {
1377 metrics->MainFrameDidNavigateAwayFromDocument();
Alexander Timind2f2e4f22019-04-02 20:04:531378 }
1379 }
1380
Rakina Zata Amnifd8370b2022-11-14 13:32:251381 // Use CommonNavigationParam's `should_replace_current_entry` to determine
1382 // whether the current NavigationEntry should be replaced.
Charlie Reisf8cde712022-10-20 16:25:091383 // (See below for a case where we might override that.)
Rakina Zata Amnifd8370b2022-11-14 13:32:251384 details->did_replace_entry =
1385 navigation_request->common_params().should_replace_current_entry;
Charlie Reisf8cde712022-10-20 16:25:091386
fdegans9caf66a2015-07-30 21:10:421387 // If there is a pending entry at this point, it should have a SiteInstance,
Charlie Reisc4155af2022-10-19 15:33:111388 // except for restored entries. This should be true even if the current commit
1389 // is not related to the pending entry.
jam48cea9082017-02-15 06:13:291390 bool was_restored = false;
toyoshim0df1d3a2016-09-09 09:52:481391 DCHECK(pending_entry_index_ == -1 || pending_entry_->site_instance() ||
Lukasz Anforowicz6b75c0d2020-12-01 22:56:081392 pending_entry_->IsRestored());
Charlie Reisc4155af2022-10-19 15:33:111393
1394 // Only make changes based on the pending entry if the NavigationRequest
1395 // matches it. Otherwise, the pending entry may be for a different request
1396 // (e.g., if a slow history navigation is pending while an auto-subframe
1397 // commit occurs).
1398 if (PendingEntryMatchesRequest(navigation_request)) {
1399 // It is no longer necessary to consider the pending entry as restored.
1400 if (pending_entry_->IsRestored()) {
1401 pending_entry_->set_restore_type(RestoreType::kNotRestored);
1402 was_restored = true;
1403 }
[email protected]e9ba4472008-09-14 15:42:431404
Charlie Reisf8cde712022-10-20 16:25:091405 // If the SiteInstance has changed from the matching pending entry, this
1406 // must be treated as a new navigation with replacement. Set the replacement
1407 // bit here and ClassifyNavigation will identify this case and return
1408 // NEW_ENTRY.
1409 if (!rfh->GetParent() && pending_entry_->site_instance() &&
1410 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
1411 DCHECK_NE(-1, pending_entry_index_);
Rakina Zata Amnifd8370b2022-11-14 13:32:251412 // TODO(nasko,creis,rakina): Move this to happen before committing the
1413 // navigation. This is a bit complicated because we don't currently
1414 // set `should_replace_current_entry` for reload/history navigations.
Charlie Reisf8cde712022-10-20 16:25:091415 details->did_replace_entry = true;
1416 }
Nasko Oskovaee2f862018-06-15 00:05:521417 }
[email protected]bcd904482012-02-01 01:54:221418
[email protected]e9ba4472008-09-14 15:42:431419 // Do navigation-type specific actions. These will make and commit an entry.
Miyoung Shin3299cbf2022-11-22 01:41:101420 NavigationType navigation_type =
1421 ClassifyNavigation(rfh, params, navigation_request);
1422 navigation_request->set_navigation_type(navigation_type);
shivanigithub189833f2022-04-27 18:08:451423
Rakina Zata Amnie2d31312022-11-18 03:38:451424 if (ShouldMaintainTrivialSessionHistory(rfh->frame_tree_node())) {
shivanigithub189833f2022-04-27 18:08:451425 // Ensure that this navigation does not add a navigation entry, since
1426 // ShouldMaintainTrivialSessionHistory() means we should not add an entry
1427 // beyond the last committed one. Therefore, `should_replace_current_entry`
1428 // should be set, which replaces the current entry, or this should be a
1429 // reload, which does not create a new entry.
1430 // In shadowDOM fenced frames, on a history/tab-restore navigation, any
1431 // navigation that is restored will not be creating a new entry anyways, so
1432 // exclude that case by checking NAVIGATION_TYPE_AUTO_SUBFRAME.
1433 // TODO(crbug.com/1319919): Consider adjusting the dcheck for more cases as
1434 // pointed out in the issue.
Rakina Zata Amnifd8370b2022-11-14 13:32:251435 DCHECK(navigation_request->common_params().should_replace_current_entry ||
shivanigithub189833f2022-04-27 18:08:451436 navigation_request->GetReloadType() != ReloadType::NONE ||
Miyoung Shin3299cbf2022-11-22 01:41:101437 navigation_type == NAVIGATION_TYPE_AUTO_SUBFRAME);
shivanigithub189833f2022-04-27 18:08:451438 }
1439
Rakina Zata Amnie2d31312022-11-18 03:38:451440 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniddf10502022-01-15 02:56:551441 if (rfh->GetParent()) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241442 // This is a subframe navigation on the initial empty document, which used
1443 // to not have a NavigationEntry to attach to. Now it can attach to the
1444 // initial NavigationEntry, and we must ensure that its NavigationEntry
1445 // will keep the "initial NavigationEntry" status and won't append a new
1446 // NavigationEntry (it should always do replacement instead).
1447 // See also https://crbug.com/1277414.
1448 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551449 // Subframe navigation on initial NavigationEntry must not append a new
1450 // NavigationEntry (i.e. should not be classified as NEW_SUBFRAME). This
1451 // means every subframe navigation that happens while we're on the initial
1452 // NavigationEntry will always reuse the existing NavigationEntry and
1453 // just update the corresponding FrameNavigationEntry.
Miyoung Shin3299cbf2022-11-22 01:41:101454 DCHECK_EQ(navigation_type, NAVIGATION_TYPE_AUTO_SUBFRAME);
1455 } else if (navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY) {
Rakina Zata Amniddf10502022-01-15 02:56:551456 // This is a navigation that modifies the initial NavigationEntry, either
1457 // for a replacement or a reload. The initial NavigationEntry should
1458 // retain its "initial NavigationEntry" status in this case.
1459 details->should_stay_as_initial_entry = true;
Rakina Zata Amni2322f4f82022-01-24 13:24:241460 } else if (navigation_request->is_synchronous_renderer_commit() &&
Rakina Zata Amnifd8370b2022-11-14 13:32:251461 !navigation_request->IsSameDocument() && !rfh->GetParent()) {
1462 DCHECK(navigation_request->common_params().should_replace_current_entry);
Rakina Zata Amni2322f4f82022-01-24 13:24:241463 // This is a synchronous about:blank navigation on the main frame, which
1464 // used to not create a NavigationEntry when we have no NavigationEntry on
1465 // FrameTree creation. We now have the initial NavigationEntry and are on
1466 // the initial NavigationEntry. To preserve old behavior, we should still
1467 // keep the "initial" status for the new NavigationEntry that we will
1468 // create for this navigation, so that subframe navigations under the
1469 // synchronously committed about:blank document will never append new
1470 // NavigationEntry, and instead will just reuse the initial
1471 // NavigationEntry and modify the corresponding FrameNavigationEntries.
1472 // See also https://crbug.com/1277414.
1473 details->should_stay_as_initial_entry = true;
Rakina Zata Amniddf10502022-01-15 02:56:551474 }
1475 }
1476 DCHECK(!details->should_stay_as_initial_entry ||
1477 GetLastCommittedEntry()->IsInitialEntry());
[email protected]4bf3522c2010-08-19 21:00:201478
eugenebutee08663a2017-04-27 17:43:121479 // is_same_document must be computed before the entry gets committed.
Eugene But712f03d2018-05-22 16:03:441480 details->is_same_document = is_same_document_navigation;
[email protected]b9d4dfdc2013-08-08 00:25:121481
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071482 details->is_prerender_activation =
1483 navigation_request->IsPrerenderedPageActivation();
Robert Lin540dbd12022-04-28 22:07:241484 details->is_in_active_page = navigation_request->GetRenderFrameHost()
1485 ->GetOutermostMainFrame()
1486 ->IsInPrimaryMainFrame();
Lucas Furukawa Gadanie3f7e792021-04-22 17:56:071487
Peter Boströmd7592132019-01-30 04:50:311488 // Make sure we do not discard the pending entry for a different ongoing
1489 // navigation when a same document commit comes in unexpectedly from the
1490 // renderer. Limit this to a very narrow set of conditions to avoid risks to
1491 // other navigation types. See https://crbug.com/900036.
1492 // TODO(crbug.com/926009): Handle history.pushState() as well.
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061493 bool keep_pending_entry =
1494 is_same_document_navigation &&
Miyoung Shin3299cbf2022-11-22 01:41:101495 navigation_type == NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY &&
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061496 pending_entry_ && !PendingEntryMatchesRequest(navigation_request);
Peter Boströmd7592132019-01-30 04:50:311497
Miyoung Shin3299cbf2022-11-22 01:41:101498 switch (navigation_type) {
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061499 case NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491500 RendererDidNavigateToNewEntry(
shivanisha41f04c52018-12-12 15:52:051501 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001502 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431503 break;
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061504 case NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY:
Charlie Reisc0f17d2d2021-01-12 18:52:491505 RendererDidNavigateToExistingEntry(rfh, params, details->is_same_document,
1506 was_restored, navigation_request,
Rakina Zata Amnia4e27222021-12-22 01:05:001507 keep_pending_entry, details);
[email protected]e9ba4472008-09-14 15:42:431508 break;
[email protected]8ff00d72012-10-23 19:12:211509 case NAVIGATION_TYPE_NEW_SUBFRAME:
Shivani Sharmaffb32b82019-04-09 16:58:471510 RendererDidNavigateNewSubframe(
1511 rfh, params, details->is_same_document, details->did_replace_entry,
Rakina Zata Amnia4e27222021-12-22 01:05:001512 previous_document_was_activated, navigation_request, details);
[email protected]e9ba4472008-09-14 15:42:431513 break;
[email protected]8ff00d72012-10-23 19:12:211514 case NAVIGATION_TYPE_AUTO_SUBFRAME:
Antonio Sartori78a749f2020-11-30 12:03:391515 if (!RendererDidNavigateAutoSubframe(
Nate Chapinc7019dd7d2021-06-25 18:29:251516 rfh, params, details->is_same_document,
Rakina Zata Amnia4e27222021-12-22 01:05:001517 was_on_initial_empty_document, navigation_request, details)) {
creisce0ef3572017-01-26 17:53:081518 // We don't send a notification about auto-subframe PageState during
1519 // UpdateStateForFrame, since it looks like nothing has changed. Send
1520 // it here at commit time instead.
1521 NotifyEntryChanged(GetLastCommittedEntry());
[email protected]e9ba4472008-09-14 15:42:431522 return false;
creis59d5a47cb2016-08-24 23:57:191523 }
[email protected]e9ba4472008-09-14 15:42:431524 break;
Aran Gilman37d11632019-10-08 23:07:151525 case NAVIGATION_TYPE_UNKNOWN:
[email protected]e9ba4472008-09-14 15:42:431526 NOTREACHED();
Aran Gilman37d11632019-10-08 23:07:151527 break;
[email protected]765b35502008-08-21 00:51:201528 }
1529
[email protected]688aa65c62012-09-28 04:32:221530 // At this point, we know that the navigation has just completed, so
1531 // record the time.
1532 //
1533 // TODO(akalin): Use "sane time" as described in
Adam Langley4463fb832018-01-28 22:42:261534 // https://www.chromium.org/developers/design-documents/sane-time .
[email protected]c5b88d82012-10-06 17:03:331535 base::Time timestamp =
1536 time_smoother_.GetSmoothedTime(get_timestamp_callback_.Run());
1537 DVLOG(1) << "Navigation finished at (smoothed) timestamp "
danakjf26536bf2020-09-10 00:46:131538 << timestamp.ToDeltaSinceWindowsEpoch().InMicroseconds();
[email protected]688aa65c62012-09-28 04:32:221539
Peter Boströmd7592132019-01-30 04:50:311540 // If we aren't keeping the pending entry, there shouldn't be one at this
1541 // point. Clear it again in case any error cases above forgot to do so.
1542 // TODO(pbos): Consider a CHECK here that verifies that the pending entry has
1543 // been cleared instead of protecting against it.
1544 if (!keep_pending_entry)
Rakina Zata Amniddf10502022-01-15 02:56:551545 DiscardNonCommittedEntriesWithCommitDetails(details);
[email protected]f233e4232013-02-23 00:55:141546
[email protected]e9ba4472008-09-14 15:42:431547 // All committed entries should have nonempty content state so WebKit doesn't
1548 // get confused when we go back to them (see the function for details).
creis0cade2e2017-02-28 06:37:471549 DCHECK(params.page_state.IsValid()) << "Shouldn't see an empty PageState.";
creis3da03872015-02-20 21:12:321550 NavigationEntryImpl* active_entry = GetLastCommittedEntry();
[email protected]688aa65c62012-09-28 04:32:221551 active_entry->SetTimestamp(timestamp);
[email protected]f49737b32013-08-28 07:51:441552 active_entry->SetHttpStatusCode(params.http_status_code);
Fergal Daly0686c0e2022-06-28 02:08:141553
Alexander Timind2f2e4f22019-04-02 20:04:531554 // TODO(altimin, crbug.com/933147): Remove this logic after we are done with
1555 // implementing back-forward cache.
Dave Tapuskaa2ab4f252021-07-08 21:31:281556 if (back_forward_cache_metrics &&
1557 !active_entry->back_forward_cache_metrics()) {
Alexander Timind2f2e4f22019-04-02 20:04:531558 active_entry->set_back_forward_cache_metrics(
1559 std::move(back_forward_cache_metrics));
1560 }
Dave Tapuskaa2ab4f252021-07-08 21:31:281561
1562 // `back_forward_cache_metrics()` may return null as we do not record
1563 // back-forward cache metrics for navigations in non-primary frame trees.
1564 if (active_entry->back_forward_cache_metrics()) {
Fergal Daly0686c0e2022-06-28 02:08:141565 // TODO(https://crbug.com/1338089): Remove this.
1566 // These are both only available from details at this point, so we capture
1567 // them here.
1568 SCOPED_CRASH_KEY_NUMBER("BFCacheMismatch", "navigation_type",
Miyoung Shin3299cbf2022-11-22 01:41:101569 navigation_type);
Fergal Daly0686c0e2022-06-28 02:08:141570 SCOPED_CRASH_KEY_BOOL("BFCacheMismatch", "did_replace",
1571 details->did_replace_entry);
Dave Tapuskaa2ab4f252021-07-08 21:31:281572 active_entry->back_forward_cache_metrics()->DidCommitNavigation(
1573 navigation_request,
1574 back_forward_cache_.IsAllowed(navigation_request->GetURL()));
1575 }
naskoc7533512016-05-06 17:01:121576
Charles Reisc0507202017-09-21 00:40:021577 // Grab the corresponding FrameNavigationEntry for a few updates, but only if
1578 // the SiteInstance matches (to avoid updating the wrong entry by mistake).
1579 // A mismatch can occur if the renderer lies or due to a unique name collision
1580 // after a race with an OOPIF (see https://crbug.com/616820).
naskoc7533512016-05-06 17:01:121581 FrameNavigationEntry* frame_entry =
1582 active_entry->GetFrameEntry(rfh->frame_tree_node());
Charles Reisc0507202017-09-21 00:40:021583 if (frame_entry && frame_entry->site_instance() != rfh->GetSiteInstance())
1584 frame_entry = nullptr;
Charles Reisf44482022017-10-13 21:15:031585 // Make sure we've updated the PageState in one of the helper methods.
creisce0ef3572017-01-26 17:53:081586 // TODO(creis): Remove the "if" once https://crbug.com/522193 is fixed.
1587 if (frame_entry) {
Charles Reisf44482022017-10-13 21:15:031588 DCHECK(params.page_state == frame_entry->page_state());
Nasko Oskovbbcfc0002019-11-20 20:03:201589
1590 // Remember the bindings the renderer process has at this point, so that
1591 // we do not grant this entry additional bindings if we come back to it.
1592 frame_entry->SetBindings(rfh->GetEnabledBindings());
creis4e2ecb72015-06-20 00:46:301593 }
[email protected]132e281a2012-07-31 18:32:441594
[email protected]97d8f0d2013-10-29 16:49:211595 // Once it is committed, we no longer need to track several pieces of state on
1596 // the entry.
naskoc7533512016-05-06 17:01:121597 active_entry->ResetForCommit(frame_entry);
[email protected]60d6cca2013-04-30 08:47:131598
[email protected]49bd30e62011-03-22 20:12:591599 // The active entry's SiteInstance should match our SiteInstance.
[email protected]a1b99262013-12-27 21:56:221600 // TODO(creis): This check won't pass for subframes until we create entries
1601 // for subframe navigations.
avi39c1edd32015-06-04 20:06:001602 if (!rfh->GetParent())
creis77c9aa32015-09-25 19:59:421603 CHECK_EQ(active_entry->site_instance(), rfh->GetSiteInstance());
[email protected]49bd30e62011-03-22 20:12:591604
[email protected]e9ba4472008-09-14 15:42:431605 // Now prep the rest of the details for the notification and broadcast.
[email protected]0f38dc4552011-02-25 11:24:001606 details->entry = active_entry;
avi39c1edd32015-06-04 20:06:001607 details->is_main_frame = !rfh->GetParent();
[email protected]2e39d2e2009-02-19 18:41:311608 details->http_status_code = params.http_status_code;
estarka5635c42015-07-14 00:06:531609
arthursonzogni7ddc6542021-04-09 09:16:501610 active_entry->SetIsOverridingUserAgent(
1611 navigation_request->is_overriding_user_agent());
Scott Violetc36f7462020-05-06 23:13:031612
[email protected]93f230e02011-06-01 14:40:001613 NotifyNavigationEntryCommitted(details);
initial.commit09911bf2008-07-26 23:55:291614
aelias100c9192017-01-13 00:01:431615 if (overriding_user_agent_changed)
1616 delegate_->UpdateOverridingUserAgent();
1617
creis03b48002015-11-04 00:54:561618 // Update the nav_entry_id for each RenderFrameHost in the tree, so that each
1619 // one knows the latest NavigationEntry it is showing (whether it has
1620 // committed anything in this navigation or not). This allows things like
1621 // state and title updates from RenderFrames to apply to the latest relevant
1622 // NavigationEntry.
dcheng57e39e22016-01-21 00:25:381623 int nav_entry_id = active_entry->GetUniqueID();
Ali Hijazid87307d2022-11-07 20:15:031624 for (FrameTreeNode* node : frame_tree_->Nodes())
dcheng57e39e22016-01-21 00:25:381625 node->current_frame_host()->set_nav_entry_id(nav_entry_id);
Hayato Ito2c8c08d02021-06-23 03:38:431626
1627 if (navigation_request->IsPrerenderedPageActivation()) {
1628 BroadcastHistoryOffsetAndLength();
1629 // TODO(crbug.com/1222893): Broadcasting happens after the prerendered page
1630 // is activated. As a result, a "prerenderingchange" event listener sees the
1631 // history.length which is not updated yet. We should guarantee that
1632 // history's length and offset should be updated before a
1633 // "prerenderingchange" event listener runs. One possible approach is to use
1634 // the same IPC which "prerenderingchange" uses, and propagate history's
1635 // length and offset together with that.
1636 }
1637
[email protected]e9ba4472008-09-14 15:42:431638 return true;
initial.commit09911bf2008-07-26 23:55:291639}
1640
[email protected]8ff00d72012-10-23 19:12:211641NavigationType NavigationControllerImpl::ClassifyNavigation(
creis3da03872015-02-20 21:12:321642 RenderFrameHostImpl* rfh,
Rakina Zata Amnif6950d552020-11-24 03:26:101643 const mojom::DidCommitProvisionalLoadParams& params,
Rakina Zata Amni2322f4f82022-01-24 13:24:241644 NavigationRequest* navigation_request) {
Piotr Tworekbad51282020-09-30 19:17:591645 TraceReturnReason<tracing_category::kNavigation> trace_return(
Nasko Oskovae49e292020-08-13 02:08:511646 "ClassifyNavigation");
1647
avi7c6f35e2015-05-08 17:52:381648 if (params.did_create_new_entry) {
Rakina Zata Amni2322f4f82022-01-24 13:24:241649 // A new entry. We may or may not have a corresponding pending entry, and
1650 // this may or may not be the main frame.
avi39c1edd32015-06-04 20:06:001651 if (!rfh->GetParent()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491652 trace_return.set_return_reason("new entry, no parent, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061653 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381654 }
Rakina Zata Amni2322f4f82022-01-24 13:24:241655 // Valid subframe navigation.
Nasko Oskovae49e292020-08-13 02:08:511656 trace_return.set_return_reason("new entry, new subframe");
avi7c6f35e2015-05-08 17:52:381657 return NAVIGATION_TYPE_NEW_SUBFRAME;
1658 }
1659
Charlie Reisc0f17d2d2021-01-12 18:52:491660 // We only clear the session history in tests when navigating to a new entry.
avi7c6f35e2015-05-08 17:52:381661 DCHECK(!params.history_list_was_cleared);
1662
avi39c1edd32015-06-04 20:06:001663 if (rfh->GetParent()) {
avi7c6f35e2015-05-08 17:52:381664 // All manual subframes would be did_create_new_entry and handled above, so
1665 // we know this is auto.
Rakina Zata Amniacd4df662022-11-15 06:49:081666 trace_return.set_return_reason("subframe, last commmited, auto subframe");
1667 return NAVIGATION_TYPE_AUTO_SUBFRAME;
avi7c6f35e2015-05-08 17:52:381668 }
1669
Rakina Zata Amnif6950d552020-11-24 03:26:101670 const int nav_entry_id = navigation_request->commit_params().nav_entry_id;
1671 if (nav_entry_id == 0) {
avi7c6f35e2015-05-08 17:52:381672 // This is a renderer-initiated navigation (nav_entry_id == 0), but didn't
1673 // create a new page.
1674
Hayato Ito2ae49442021-07-02 02:59:251675 // This main frame navigation is not a history navigation (since
1676 // nav_entry_id is 0), but didn't create a new entry. So this must be a
1677 // reload or a replacement navigation, which will modify the existing entry.
1678 //
Nasko Oskov332593c2018-08-16 17:21:341679 // TODO(nasko): With error page isolation, reloading an existing session
1680 // history entry can result in change of SiteInstance. Check for such a case
Charlie Reisc0f17d2d2021-01-12 18:52:491681 // here and classify it as NEW_ENTRY, as such navigations should be treated
Nasko Oskov332593c2018-08-16 17:21:341682 // as new with replacement.
Nasko Oskovae49e292020-08-13 02:08:511683 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491684 "nav entry 0, last committed, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061685 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381686 }
1687
Charlie Reisf8cde712022-10-20 16:25:091688 if (PendingEntryMatchesRequest(navigation_request)) {
Nasko Oskovaee2f862018-06-15 00:05:521689 // If the SiteInstance of the |pending_entry_| does not match the
1690 // SiteInstance that got committed, treat this as a new navigation with
1691 // replacement. This can happen if back/forward/reload encounters a server
1692 // redirect to a different site or an isolated error page gets successfully
1693 // reloaded into a different SiteInstance.
1694 if (pending_entry_->site_instance() &&
1695 pending_entry_->site_instance() != rfh->GetSiteInstance()) {
Charlie Reisc0f17d2d2021-01-12 18:52:491696 trace_return.set_return_reason("pending matching nav entry, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061697 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521698 }
creis77c9aa32015-09-25 19:59:421699
Nasko Oskovaee2f862018-06-15 00:05:521700 if (pending_entry_index_ == -1) {
1701 // In this case, we have a pending entry for a load of a new URL but Blink
1702 // didn't do a new navigation (params.did_create_new_entry). First check
1703 // to make sure Blink didn't treat a new cross-process navigation as
1704 // inert, and thus set params.did_create_new_entry to false. In that case,
Charlie Reis7e2cb6d2021-01-26 01:27:161705 // we must treat it as NEW rather than the converted reload case below,
1706 // since the new SiteInstance doesn't match the last committed entry.
Rakina Zata Amnie2d31312022-11-18 03:38:451707 if (GetLastCommittedEntry()->site_instance() != rfh->GetSiteInstance()) {
Charlie Reis7e2cb6d2021-01-26 01:27:161708 trace_return.set_return_reason("new pending, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061709 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521710 }
1711
1712 // Otherwise, this happens when you press enter in the URL bar to reload.
Charlie Reis7e2cb6d2021-01-26 01:27:161713 // We will create a pending entry, but NavigateWithoutEntry will convert
1714 // it to a reload since it's the same page and not create a new entry for
1715 // it. (The user doesn't want to have a new back/forward entry when they
1716 // do this.) Therefore we want to just ignore the pending entry and go
1717 // back to where we were (the "existing entry").
1718 trace_return.set_return_reason("new pending, existing (same) entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061719 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
Nasko Oskovaee2f862018-06-15 00:05:521720 }
avi7c6f35e2015-05-08 17:52:381721 }
1722
Rakina Zata Amni153d5702021-09-13 22:48:001723 if (navigation_request->commit_params().intended_as_new_entry) {
avi7c6f35e2015-05-08 17:52:381724 // This was intended to be a navigation to a new entry but the pending entry
Charlie Reisc0f17d2d2021-01-12 18:52:491725 // got cleared in the meanwhile. Classify as EXISTING_ENTRY because we may
1726 // or may not have a pending entry.
Charlie Reis7e2cb6d2021-01-26 01:27:161727 trace_return.set_return_reason("intended as new entry, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061728 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381729 }
1730
Rakina Zata Amni3a1c0ec2021-04-15 03:35:121731 if (navigation_request->DidEncounterError() &&
1732 failed_pending_entry_id_ != 0 &&
Rakina Zata Amnif6950d552020-11-24 03:26:101733 nav_entry_id == failed_pending_entry_id_) {
avi7c6f35e2015-05-08 17:52:381734 // If the renderer was going to a new pending entry that got cleared because
1735 // of an error, this is the case of the user trying to retry a failed load
Charlie Reisc0f17d2d2021-01-12 18:52:491736 // by pressing return. Classify as EXISTING_ENTRY because we probably don't
avi7c6f35e2015-05-08 17:52:381737 // have a pending entry.
Nasko Oskovae49e292020-08-13 02:08:511738 trace_return.set_return_reason(
Charlie Reisc0f17d2d2021-01-12 18:52:491739 "unreachable, matching pending, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061740 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381741 }
1742
Charlie Reisc0f17d2d2021-01-12 18:52:491743 // Now we know that the notification is for an existing entry; find it.
Rakina Zata Amnif6950d552020-11-24 03:26:101744 int existing_entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
Nasko Oskovae49e292020-08-13 02:08:511745 trace_return.traced_value()->SetInteger("existing_entry_index",
1746 existing_entry_index);
avi7c6f35e2015-05-08 17:52:381747 if (existing_entry_index == -1) {
avi5cad4912015-06-19 05:25:441748 // The renderer has committed a navigation to an entry that no longer
1749 // exists. Because the renderer is showing that page, resurrect that entry.
Charlie Reisc0f17d2d2021-01-12 18:52:491750 trace_return.set_return_reason("existing entry -1, new entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061751 return NAVIGATION_TYPE_MAIN_FRAME_NEW_ENTRY;
avi7c6f35e2015-05-08 17:52:381752 }
1753
avi7c6f35e2015-05-08 17:52:381754 // Since we weeded out "new" navigations above, we know this is an existing
1755 // (back/forward) navigation.
Charlie Reisc0f17d2d2021-01-12 18:52:491756 trace_return.set_return_reason("default return, existing entry");
Yoshisato Yanagisawa2ccba602021-11-17 08:24:061757 return NAVIGATION_TYPE_MAIN_FRAME_EXISTING_ENTRY;
avi7c6f35e2015-05-08 17:52:381758}
1759
Rakina Zata Amni3460d382021-10-29 00:43:371760void NavigationControllerImpl::UpdateNavigationEntryDetails(
1761 NavigationEntryImpl* entry,
1762 RenderFrameHostImpl* rfh,
1763 const mojom::DidCommitProvisionalLoadParams& params,
1764 NavigationRequest* request,
1765 NavigationEntryImpl::UpdatePolicy update_policy,
Rakina Zata Amnia4e27222021-12-22 01:05:001766 bool is_new_entry,
1767 LoadCommittedDetails* commit_details) {
Rakina Zata Amni3460d382021-10-29 00:43:371768 // Update the FrameNavigationEntry.
Rakina Zata Amniafd3c6582021-11-30 06:19:171769 std::vector<GURL> redirects;
Rakina Zata Amni3460d382021-10-29 00:43:371770 entry->AddOrUpdateFrameEntry(
1771 rfh->frame_tree_node(), update_policy, params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571772 params.document_sequence_number, params.navigation_api_key,
Rakina Zata Amni3460d382021-10-29 00:43:371773 rfh->GetSiteInstance(), nullptr, params.url,
1774 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amniafd3c6582021-11-30 06:19:171775 Referrer(*params.referrer),
1776 request ? request->common_params().initiator_origin : params.origin,
1777 request ? request->GetRedirectChain() : redirects, params.page_state,
1778 params.method, params.post_id, nullptr /* blob_url_loader_factory */,
1779 (request && request->web_bundle_navigation_info())
Rakina Zata Amni3460d382021-10-29 00:43:371780 ? request->web_bundle_navigation_info()->Clone()
1781 : nullptr,
Rakina Zata Amniafd3c6582021-11-30 06:19:171782 (request ? request->GetSubresourceWebBundleNavigationInfo() : nullptr),
Rakina Zata Amni3460d382021-10-29 00:43:371783 ComputePolicyContainerPoliciesForFrameEntry(
Rakina Zata Amniafd3c6582021-11-30 06:19:171784 rfh, request && request->IsSameDocument(),
1785 request ? request->common_params().url : params.url));
Rakina Zata Amni3460d382021-10-29 00:43:371786
1787 if (rfh->GetParent()) {
1788 // Only modify the NavigationEntry for main frame navigations.
1789 return;
1790 }
1791 if (entry->update_virtual_url_with_url())
1792 UpdateVirtualURLToURL(entry, params.url);
1793 // Don't use the page type from the pending entry. Some interstitial page
1794 // may have set the type to interstitial. Once we commit, however, the page
1795 // type must always be normal or error.
Rakina Zata Amniafd3c6582021-11-30 06:19:171796 entry->set_page_type((request && request->DidEncounterError())
1797 ? PAGE_TYPE_ERROR
1798 : PAGE_TYPE_NORMAL);
Rakina Zata Amnif297a802022-01-18 03:53:431799 if (commit_details && commit_details->should_stay_as_initial_entry) {
1800 // Retain the "initial NavigationEntry" status.
1801 if (request->IsSameDocument()) {
1802 // If this is for a same-document navigation, the NavigationEntry must be
1803 // reused and should already be marked as the initial NavigationEntry.
1804 DCHECK(entry->IsInitialEntry());
1805 } else {
1806 // If this is for a cross-document navigation, it can be caused by a
1807 // renderer-initiated reload, or the synchronous about:blank commit. Mark
1808 // "for synchronous about:blank" in the latter case, and also when it is
1809 // reloading a "for synchronous about:blank" entry. Otherwise, the entry
1810 // is not for a synchronous about:blank commit.
1811 NavigationEntryImpl::InitialNavigationEntryState new_state =
1812 NavigationEntryImpl::InitialNavigationEntryState::
1813 kInitialNotForSynchronousAboutBlank;
1814 if (entry->IsInitialEntryForSynchronousAboutBlank() ||
1815 request->is_synchronous_renderer_commit()) {
1816 new_state = NavigationEntryImpl::InitialNavigationEntryState::
1817 kInitialForSynchronousAboutBlank;
1818 }
1819 entry->set_initial_navigation_entry_state(new_state);
1820 }
1821 } else if (commit_details && !commit_details->should_stay_as_initial_entry) {
1822 // Remove the "initial NavigationEntry" status.
1823 entry->set_initial_navigation_entry_state(
1824 NavigationEntryImpl::InitialNavigationEntryState::kNonInitial);
Rakina Zata Amnia4e27222021-12-22 01:05:001825 }
Rakina Zata Amniddf10502022-01-15 02:56:551826
Rakina Zata Amni3460d382021-10-29 00:43:371827 if (is_new_entry) {
1828 // Some properties of the NavigationEntry are only set when the entry is
1829 // new (we aren't reusing it).
1830 entry->SetTransitionType(params.transition);
Rakina Zata Amniafd3c6582021-11-30 06:19:171831 entry->SetOriginalRequestURL(request ? request->GetOriginalRequestURL()
1832 : GURL::EmptyGURL());
Rakina Zata Amni3460d382021-10-29 00:43:371833 DCHECK_EQ(rfh->is_overriding_user_agent(), params.is_overriding_user_agent);
1834 entry->SetIsOverridingUserAgent(params.is_overriding_user_agent);
1835 } else {
1836 // We are reusing the NavigationEntry. The site instance will normally be
1837 // the same except for a few cases:
1838 // 1) session restore, when no site instance will be assigned or
1839 // 2) redirect, when the site instance is reset.
1840 DCHECK(!entry->site_instance() || !entry->GetRedirectChain().empty() ||
1841 entry->site_instance() == rfh->GetSiteInstance());
1842 }
1843}
1844
Rakina Zata Amniafd3c6582021-11-30 06:19:171845void NavigationControllerImpl::CreateInitialEntry() {
1846 DCHECK_EQ(entries_.size(), 0u);
Ali Hijazid87307d2022-11-07 20:15:031847 RenderFrameHostImpl* rfh = frame_tree_->root()->current_frame_host();
Rakina Zata Amniafd3c6582021-11-30 06:19:171848 auto params = mojom::DidCommitProvisionalLoadParams::New();
1849 // The initial NavigationEntry's URL is the empty URL. This preserves the old
1850 // behavior of WebContent's GetLastCommittedURL() and GetVisibleURL() from
1851 // before we have initial NavigationEntries.
1852 params->url = GURL::EmptyGURL();
1853 params->http_status_code = 0;
1854 params->url_is_unreachable = false;
1855 params->method = "GET";
Rakina Zata Amniafd3c6582021-11-30 06:19:171856 params->post_id = -1;
1857 params->embedding_token = base::UnguessableToken::Create();
1858 params->navigation_token = base::UnguessableToken::Create();
1859 params->did_create_new_entry = true;
1860 params->origin = rfh->GetLastCommittedOrigin();
1861 params->should_update_history = true;
1862 params->item_sequence_number = 0;
1863 params->document_sequence_number = 0;
Abhijeet Kandalkare26014a92022-10-13 04:21:151864 bool is_in_fenced_frame_tree = rfh->IsNestedWithinFencedFrame();
Rakina Zata Amniafd3c6582021-11-30 06:19:171865 params->transition = is_in_fenced_frame_tree
1866 ? ui::PAGE_TRANSITION_AUTO_SUBFRAME
1867 : ui::PAGE_TRANSITION_LINK;
1868 params->referrer = blink::mojom::Referrer::New();
1869
1870 // Create and insert the initial NavigationEntry.
1871 auto new_entry = std::make_unique<NavigationEntryImpl>(
1872 rfh->GetSiteInstance(), params->url, Referrer(*params->referrer),
1873 rfh->GetLastCommittedOrigin(), std::u16string() /* title */,
1874 ui::PAGE_TRANSITION_TYPED, false /* renderer_initiated */,
1875 nullptr /* blob_url_loader_factory */, true /* is_initial_entry */);
1876 UpdateNavigationEntryDetails(
1877 new_entry.get(), rfh, *params, nullptr /* request */,
Rakina Zata Amnia4e27222021-12-22 01:05:001878 NavigationEntryImpl::UpdatePolicy::kUpdate, true /* is_new_entry */,
1879 nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171880
1881 InsertOrReplaceEntry(std::move(new_entry), false /* replace_entry */,
1882 false /* was_post_commit_error */,
Rakina Zata Amnia4e27222021-12-22 01:05:001883 is_in_fenced_frame_tree, nullptr /* commit_details */);
Rakina Zata Amniafd3c6582021-11-30 06:19:171884}
1885
Charlie Reisc0f17d2d2021-01-12 18:52:491886void NavigationControllerImpl::RendererDidNavigateToNewEntry(
creis3da03872015-02-20 21:12:321887 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:071888 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:361889 bool is_same_document,
clamy3bf35e3c2016-11-10 15:59:441890 bool replace_entry,
Shivani Sharmaffb32b82019-04-09 16:58:471891 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:001892 NavigationRequest* request,
1893 LoadCommittedDetails* commit_details) {
dcheng9bfa5162016-04-09 01:00:571894 std::unique_ptr<NavigationEntryImpl> new_entry;
Anton Bikineevf62d1bf2021-05-15 17:56:071895 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:451896 request->common_params().initiator_origin;
Lukasz Anforowicz435bcb582019-07-12 20:50:061897
creisf49dfc92016-07-26 17:05:181898 // First check if this is an in-page navigation. If so, clone the current
1899 // entry instead of looking at the pending entry, because the pending entry
1900 // does not have any subframe history items.
Rakina Zata Amnie2d31312022-11-18 03:38:451901 if (is_same_document) {
Nate Chapin63db0d12022-01-20 22:03:301902 FrameNavigationEntry* previous_frame_entry =
1903 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Patrick Monette50e8bd82019-06-13 22:40:451904 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:481905 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:571906 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:081907 rfh->GetSiteInstance(), nullptr, params.url,
1908 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amni82fafba2021-03-11 07:07:091909 Referrer(*params.referrer), initiator_origin,
1910 request->GetRedirectChain(), params.page_state, params.method,
1911 params.post_id, nullptr /* blob_url_loader_factory */,
Antonio Sartori78a749f2020-11-30 12:03:391912 nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:481913 request->GetSubresourceWebBundleNavigationInfo(),
Antonio Sartori78a749f2020-11-30 12:03:391914 // We will set the document policies later in this function.
Nate Chapin63db0d12022-01-20 22:03:301915 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:571916 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:301917 // FrameNavigationEntry.
1918 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:571919 previous_frame_entry->protect_url_in_navigation_api());
Charles Reisf44482022017-10-13 21:15:031920
creisf49dfc92016-07-26 17:05:181921 new_entry = GetLastCommittedEntry()->CloneAndReplace(
Ali Hijazid87307d2022-11-07 20:15:031922 frame_entry, true, request->frame_tree_node(), frame_tree_->root());
Mike West800532c2021-10-14 09:26:521923 if (new_entry->GetURL().DeprecatedGetOriginAsURL() !=
1924 params.url.DeprecatedGetOriginAsURL()) {
jama78746e2017-02-22 17:21:571925 // TODO(jam): we had one report of this with a URL that was redirecting to
1926 // only tildes. Until we understand that better, don't copy the cert in
1927 // this case.
1928 new_entry->GetSSL() = SSLStatus();
jama78746e2017-02-22 17:21:571929 }
creisf49dfc92016-07-26 17:05:181930
Patrick Monette50e8bd82019-06-13 22:40:451931 // It is expected that |frame_entry| is now owned by |new_entry|. This means
1932 // that |frame_entry| should now have a reference count of exactly 2: one
1933 // due to the local variable |frame_entry|, and another due to |new_entry|
1934 // also retaining one. This should never fail, because it's the main frame.
1935 CHECK(!frame_entry->HasOneRef() && frame_entry->HasAtLeastOneRef());
creisf49dfc92016-07-26 17:05:181936 }
1937
Harkiran Bolaria59290d62021-03-17 01:53:011938 // If this is an activation navigation from a prerendered page, transfer the
1939 // new entry from an entry already created and stored in the
1940 // NavigationRequest. |new_entry| will not have been set prior to this as
1941 // |is_same_document| is mutually exclusive with
1942 // |IsPrerenderedPageActivation|.
1943 if (request->IsPrerenderedPageActivation()) {
1944 DCHECK(!is_same_document);
1945 DCHECK(!new_entry);
1946 new_entry = request->TakePrerenderNavigationEntry();
1947 DCHECK(new_entry);
1948 }
1949
Charlie Reisc0f17d2d2021-01-12 18:52:491950 // Only make a copy of the pending entry if it is appropriate for the new
1951 // document that just loaded. Verify this by checking if the entry corresponds
Mohamed Abdelhalim833de902019-09-16 17:41:451952 // to the given NavigationRequest. Additionally, coarsely check that:
csharrison9a9142bc42016-03-01 17:24:041953 // 1. The SiteInstance hasn't been assigned to something else.
1954 // 2. The pending entry was intended as a new entry, rather than being a
1955 // history navigation that was interrupted by an unrelated,
1956 // renderer-initiated navigation.
1957 // TODO(csharrison): Investigate whether we can remove some of the coarser
1958 // checks.
Mohamed Abdelhalim833de902019-09-16 17:41:451959 if (!new_entry && PendingEntryMatchesRequest(request) &&
1960 pending_entry_index_ == -1 &&
[email protected]6dd86ab2013-02-27 00:30:341961 (!pending_entry_->site_instance() ||
[email protected]27dd82fd2014-03-03 22:11:431962 pending_entry_->site_instance() == rfh->GetSiteInstance())) {
creisef4a0cb2015-03-12 19:14:351963 new_entry = pending_entry_->Clone();
[email protected]e9ba4472008-09-14 15:42:431964
Camille Lamy62b826012019-02-26 09:15:471965 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451966 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
creisf49dfc92016-07-26 17:05:181967 }
1968
Charlie Reisc0f17d2d2021-01-12 18:52:491969 // For cross-document commits with no matching pending entry, create a new
1970 // entry.
creisf49dfc92016-07-26 17:05:181971 if (!new_entry) {
Lukasz Anforowicz435bcb582019-07-12 20:50:061972 new_entry = std::make_unique<NavigationEntryImpl>(
arthursonzogni73fe3212020-11-17 13:24:071973 rfh->GetSiteInstance(), params.url, Referrer(*params.referrer),
1974 initiator_origin,
Jan Wilken Dörrieaace0cfef2021-03-11 22:01:581975 std::u16string(), // title
Mohamed Abdelhalim833de902019-09-16 17:41:451976 params.transition, request->IsRendererInitiated(),
Rakina Zata Amniafd3c6582021-11-30 06:19:171977 nullptr, // blob_url_loader_factory
1978 false); // is_initial_entry
[email protected]f8f93eb2012-09-25 03:06:241979
1980 // Find out whether the new entry needs to update its virtual URL on URL
1981 // change and set up the entry accordingly. This is needed to correctly
1982 // update the virtual URL when replaceState is called after a pushState.
1983 GURL url = params.url;
1984 bool needs_update = false;
Charlie Reisc0f17d2d2021-01-12 18:52:491985 // When navigating to a new entry, give the browser URL handler a chance to
[email protected]f1eb87a2011-05-06 17:49:411986 // update the virtual URL based on the new URL. For example, this is needed
1987 // to show chrome://bookmarks/#1 when the bookmarks webui extension changes
1988 // the URL.
Rakina Zata Amni3460d382021-10-29 00:43:371989 BrowserURLHandlerImpl::GetInstance()->RewriteURLIfNecessary(
1990 &url, browser_context_, &needs_update);
1991 new_entry->set_update_virtual_url_with_url(needs_update);
1992
Camille Lamy62b826012019-02-26 09:15:471993 new_entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:451994 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
[email protected]e9ba4472008-09-14 15:42:431995 }
1996
Harkiran Bolaria59290d62021-03-17 01:53:011997 // TODO(crbug.com/1179428) - determine which parts of the entry need to be set
1998 // for prerendered contents, if any. This is because prerendering/activation
1999 // technically won't be creating a new document. Unlike BFCache, prerendering
2000 // creates a new NavigationEntry rather than using an existing one.
2001 if (!request->IsPrerenderedPageActivation()) {
Rakina Zata Amni3460d382021-10-29 00:43:372002 UpdateNavigationEntryDetails(new_entry.get(), rfh, params, request,
2003 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002004 true /* is_new_entry */, commit_details);
creis8b5cd4c2015-06-19 00:11:082005
Harkiran Bolaria59290d62021-03-17 01:53:012006 // history.pushState() is classified as a navigation to a new page, but sets
2007 // is_same_document to true. In this case, we already have the title and
2008 // favicon available, so set them immediately.
Rakina Zata Amnie2d31312022-11-18 03:38:452009 if (is_same_document) {
Harkiran Bolaria59290d62021-03-17 01:53:012010 new_entry->SetTitle(GetLastCommittedEntry()->GetTitle());
2011 new_entry->GetFavicon() = GetLastCommittedEntry()->GetFavicon();
2012 }
[email protected]3a868f212014-08-09 10:41:192013 }
[email protected]ff64b3e2014-05-31 04:07:332014
[email protected]60d6cca2013-04-30 08:47:132015 DCHECK(!params.history_list_was_cleared || !replace_entry);
2016 // The browser requested to clear the session history when it initiated the
2017 // navigation. Now we know that the renderer has updated its state accordingly
2018 // and it is safe to also clear the browser side history.
2019 if (params.history_list_was_cleared) {
Rakina Zata Amniddf10502022-01-15 02:56:552020 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]60d6cca2013-04-30 08:47:132021 entries_.clear();
2022 last_committed_entry_index_ = -1;
2023 }
2024
Nasko Oskovaee2f862018-06-15 00:05:522025 // If this is a new navigation with replacement and there is a
2026 // pending_entry_ which matches the navigation reported by the renderer
2027 // process, then it should be the one replaced, so update the
2028 // last_committed_entry_index_ to use it.
2029 if (replace_entry && pending_entry_index_ != -1 &&
Charlie Reisf8cde712022-10-20 16:25:092030 PendingEntryMatchesRequest(request)) {
Nasko Oskovaee2f862018-06-15 00:05:522031 last_committed_entry_index_ = pending_entry_index_;
2032 }
2033
Alexander Timine3ec4192020-04-20 16:39:402034 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412035 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402036 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
shivanisha41f04c52018-12-12 15:52:052037
Yuzu Saijoa725585f2022-11-28 04:14:032038 // If this is a history navigation and the old entry has an existing
2039 // back/forward cache metrics object, keep using the old one so that the
2040 // reasons logged from the last time the page navigated gets preserved.
2041 if (BackForwardCacheMetrics::IsCrossDocumentMainFrameHistoryNavigation(
2042 request)) {
2043 // Use |request->GetNavigationEntry()| instead of |pending_entry_| here
2044 // because some tests do not have a pending entry.
2045 NavigationEntryImpl* entry =
2046 static_cast<NavigationEntryImpl*>(request->GetNavigationEntry());
2047 if (entry && entry->back_forward_cache_metrics()) {
2048 scoped_refptr<BackForwardCacheMetrics> metrics =
2049 entry->TakeBackForwardCacheMetrics();
2050 new_entry->set_back_forward_cache_metrics(std::move(metrics));
2051 }
2052 }
2053
Carlos IL42b416592019-10-07 23:10:362054 InsertOrReplaceEntry(std::move(new_entry), replace_entry,
Dave Tapuska87696ae2021-11-18 18:48:312055 !request->post_commit_error_page_html().empty(),
Abhijeet Kandalkare26014a92022-10-13 04:21:152056 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432057}
2058
Charlie Reisc0f17d2d2021-01-12 18:52:492059void NavigationControllerImpl::RendererDidNavigateToExistingEntry(
creis3da03872015-02-20 21:12:322060 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072061 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362062 bool is_same_document,
jam48cea9082017-02-15 06:13:292063 bool was_restored,
Mohamed Abdelhalim833de902019-09-16 17:41:452064 NavigationRequest* request,
Rakina Zata Amnia4e27222021-12-22 01:05:002065 bool keep_pending_entry,
2066 LoadCommittedDetails* commit_details) {
creis26d22632017-04-21 20:23:562067 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2068 << "that a last committed entry exists.";
2069
[email protected]e9ba4472008-09-14 15:42:432070 // We should only get here for main frame navigations.
avi39c1edd32015-06-04 20:06:002071 DCHECK(!rfh->GetParent());
[email protected]e9ba4472008-09-14 15:42:432072
Charlie Reis7e2cb6d2021-01-26 01:27:162073 NavigationEntryImpl* entry = nullptr;
Rakina Zata Amni153d5702021-09-13 22:48:002074 if (request->commit_params().intended_as_new_entry) {
Charlie Reis7e2cb6d2021-01-26 01:27:162075 // We're guaranteed to have a last committed entry if intended_as_new_entry
2076 // is true.
avicbdc4c12015-07-01 16:07:112077 entry = GetLastCommittedEntry();
Charlie Reis7e2cb6d2021-01-26 01:27:162078
2079 // If the NavigationRequest matches a new pending entry and is classified as
2080 // EXISTING_ENTRY, then it is a navigation to the same URL that was
2081 // converted to a reload, such as a user pressing enter in the omnibox.
Charlie Reisf8cde712022-10-20 16:25:092082 if (pending_entry_index_ == -1 && PendingEntryMatchesRequest(request)) {
Charlie Reis7e2cb6d2021-01-26 01:27:162083 // Note: The pending entry will usually have a real ReloadType here, but
2084 // it can still be ReloadType::NONE in cases that
2085 // ShouldTreatNavigationAsReload returns false (e.g., POST, view-source).
2086
2087 // If we classified this correctly, the SiteInstance should not have
2088 // changed.
2089 CHECK_EQ(entry->site_instance(), rfh->GetSiteInstance());
2090
2091 // For converted reloads, we assign the entry's unique ID to be that of
2092 // the new one. Since this is always the result of a user action, we want
2093 // to dismiss infobars, etc. like a regular user-initiated navigation.
2094 entry->set_unique_id(pending_entry_->GetUniqueID());
2095
2096 // The extra headers may have changed due to reloading with different
2097 // headers.
2098 entry->set_extra_headers(pending_entry_->extra_headers());
2099 }
2100 // Otherwise, this was intended as a new entry but the pending entry was
2101 // lost in the meantime and no new entry was created. We are stuck at the
2102 // last committed entry.
2103
2104 // Even if this is a converted reload from pressing enter in the omnibox,
2105 // the server could redirect, requiring an update to the SSL status. If this
2106 // is a same document navigation, though, there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452107 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
Charlie Reis7e2cb6d2021-01-26 01:27:162108 if (!is_same_document) {
Camille Lamy62b826012019-02-26 09:15:472109 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452110 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
Charlie Reis7e2cb6d2021-01-26 01:27:162111 }
Rakina Zata Amnif6950d552020-11-24 03:26:102112 } else if (const int nav_entry_id = request->commit_params().nav_entry_id) {
avicbdc4c12015-07-01 16:07:112113 // This is a browser-initiated navigation (back/forward/reload).
Rakina Zata Amnif6950d552020-11-24 03:26:102114 entry = GetEntryWithUniqueID(nav_entry_id);
jamd208b902016-09-01 16:58:162115
eugenebut604866f2017-05-10 21:35:362116 if (is_same_document) {
Mohamed Abdelhalim833de902019-09-16 17:41:452117 // There's no SSLStatus in the NavigationRequest for same document
eugenebut604866f2017-05-10 21:35:362118 // navigations, so normally we leave |entry|'s SSLStatus as is. However if
2119 // this was a restored same document navigation entry, then it won't have
2120 // an SSLStatus. So we need to copy over the SSLStatus from the entry that
2121 // navigated it.
jam48cea9082017-02-15 06:13:292122 NavigationEntryImpl* last_entry = GetLastCommittedEntry();
Mike West800532c2021-10-14 09:26:522123 if (entry->GetURL().DeprecatedGetOriginAsURL() ==
2124 last_entry->GetURL().DeprecatedGetOriginAsURL() &&
jam48cea9082017-02-15 06:13:292125 last_entry->GetSSL().initialized && !entry->GetSSL().initialized &&
2126 was_restored) {
2127 entry->GetSSL() = last_entry->GetSSL();
2128 }
2129 } else {
Mohamed Abdelhalim833de902019-09-16 17:41:452130 // In rapid back/forward navigations |request| sometimes won't have a cert
2131 // (http://crbug.com/727892). So we use the request's cert if it exists,
John Abd-El-Malek3f247082017-12-07 19:02:192132 // otherwise we only reuse the existing cert if the origins match.
Mohamed Abdelhalim833de902019-09-16 17:41:452133 if (request->GetSSLInfo().has_value() &&
2134 request->GetSSLInfo()->is_valid()) {
2135 entry->GetSSL() = SSLStatus(*(request->GetSSLInfo()));
Mike West800532c2021-10-14 09:26:522136 } else if (entry->GetURL().DeprecatedGetOriginAsURL() !=
2137 request->GetURL().DeprecatedGetOriginAsURL()) {
John Abd-El-Malek3f247082017-12-07 19:02:192138 entry->GetSSL() = SSLStatus();
2139 }
jam48cea9082017-02-15 06:13:292140 }
avicbdc4c12015-07-01 16:07:112141 } else {
Feifei Wang2ab8ba6c2022-04-13 22:19:272142 // This is renderer-initiated. The only kinds of renderer-initiated
Rakina Zata Amni557afb92021-07-17 04:39:572143 // navigations that are EXISTING_ENTRY are same-document navigations that
2144 // result in replacement (e.g. history.replaceState(), location.replace(),
2145 // forced replacements for trivial session history contexts). For these
2146 // cases, we reuse the last committed entry.
avicbdc4c12015-07-01 16:07:112147 entry = GetLastCommittedEntry();
jam0576b132016-09-07 05:13:102148
Mikel Astizba9cf2fd2017-12-17 10:38:102149 // TODO(crbug.com/751023): Set page transition type to PAGE_TRANSITION_LINK
2150 // to avoid misleading interpretations (e.g. URLs paired with
2151 // PAGE_TRANSITION_TYPED that haven't actually been typed) as well as to fix
2152 // the inconsistency with what we report to observers (PAGE_TRANSITION_LINK
2153 // | PAGE_TRANSITION_CLIENT_REDIRECT).
2154
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572155 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(entry, entry);
Mikel Astizba9cf2fd2017-12-17 10:38:102156
eugenebut604866f2017-05-10 21:35:362157 // If this is a same document navigation, then there's no SSLStatus in the
Mohamed Abdelhalim833de902019-09-16 17:41:452158 // NavigationRequest so don't overwrite the existing entry's SSLStatus.
eugenebut604866f2017-05-10 21:35:362159 if (!is_same_document)
Camille Lamy62b826012019-02-26 09:15:472160 entry->GetSSL() =
Mohamed Abdelhalim833de902019-09-16 17:41:452161 SSLStatus(request->GetSSLInfo().value_or(net::SSLInfo()));
avicbdc4c12015-07-01 16:07:112162 }
2163 DCHECK(entry);
[email protected]e9ba4472008-09-14 15:42:432164
Rakina Zata Amni3460d382021-10-29 00:43:372165 UpdateNavigationEntryDetails(entry, rfh, params, request,
2166 NavigationEntryImpl::UpdatePolicy::kUpdate,
Rakina Zata Amnia4e27222021-12-22 01:05:002167 false /* is_new_entry */, commit_details);
creis22a7b4c2016-04-28 07:20:302168
[email protected]5ccd4dc2012-10-24 02:28:142169 // The redirected to page should not inherit the favicon from the previous
2170 // page.
eugenebut604866f2017-05-10 21:35:362171 if (ui::PageTransitionIsRedirect(params.transition) && !is_same_document)
[email protected]91a4ff82012-10-29 20:29:482172 entry->GetFavicon() = FaviconStatus();
[email protected]5ccd4dc2012-10-24 02:28:142173
Peter Boströmd7592132019-01-30 04:50:312174 // We should also usually discard the pending entry if it corresponds to a
2175 // different navigation, since that one is now likely canceled. In rare
2176 // cases, we leave the pending entry for another navigation in place when we
2177 // know it is still ongoing, to avoid a flicker in the omnibox (see
2178 // https://crbug.com/900036).
[email protected]e9ba4472008-09-14 15:42:432179 //
2180 // Note that we need to use the "internal" version since we don't want to
2181 // actually change any other state, just kill the pointer.
Peter Boströmd7592132019-01-30 04:50:312182 if (!keep_pending_entry)
Rakina Zata Amnia4e27222021-12-22 01:05:002183 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]40bcc302009-03-02 20:50:392184
Carlos IL4dea8902020-05-26 15:14:292185 // Update the last committed index to reflect the committed entry.
avicbdc4c12015-07-01 16:07:112186 last_committed_entry_index_ = GetIndexOfEntry(entry);
[email protected]e9ba4472008-09-14 15:42:432187}
2188
[email protected]d202a7c2012-01-04 07:53:472189void NavigationControllerImpl::RendererDidNavigateNewSubframe(
creis3da03872015-02-20 21:12:322190 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072191 const mojom::DidCommitProvisionalLoadParams& params,
eugenebut604866f2017-05-10 21:35:362192 bool is_same_document,
Shivani Sharmaffb32b82019-04-09 16:58:472193 bool replace_entry,
2194 bool previous_document_was_activated,
Rakina Zata Amnia4e27222021-12-22 01:05:002195 NavigationRequest* request,
2196 LoadCommittedDetails* commit_details) {
avi25f5f9e2015-07-17 20:08:262197 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2198 ui::PAGE_TRANSITION_MANUAL_SUBFRAME));
Rakina Zata Amniddf10502022-01-15 02:56:552199 // The NEW_SUBFRAME path should never result in an initial NavigationEntry.
2200 DCHECK(!commit_details->should_stay_as_initial_entry);
[email protected]09b8f82f2009-06-16 20:22:112201
[email protected]e9ba4472008-09-14 15:42:432202 // Manual subframe navigations just get the current entry cloned so the user
2203 // can go back or forward to it. The actual subframe information will be
2204 // stored in the page state for each of those entries. This happens out of
2205 // band with the actual navigations.
[email protected]4c27ba82008-09-24 16:49:092206 DCHECK(GetLastCommittedEntry()) << "ClassifyNavigation should guarantee "
2207 << "that a last committed entry exists.";
creis96fc55082015-06-13 06:42:382208
Mikel Astizba9cf2fd2017-12-17 10:38:102209 // The DCHECK below documents the fact that we don't know of any situation
2210 // where |replace_entry| is true for subframe navigations. This simplifies
2211 // reasoning about the replacement struct for subframes (see
2212 // CopyReplacedNavigationEntryDataIfPreviouslyEmpty()).
2213 DCHECK(!replace_entry);
2214
Patrick Monette50e8bd82019-06-13 22:40:452215 // This FrameNavigationEntry might not end up being used in the
2216 // CloneAndReplace() call below, if a spot can't be found for it in the tree.
Anton Bikineevf62d1bf2021-05-15 17:56:072217 const absl::optional<url::Origin>& initiator_origin =
Mohamed Abdelhalim833de902019-09-16 17:41:452218 request->common_params().initiator_origin;
Nate Chapin63db0d12022-01-20 22:03:302219 std::unique_ptr<PolicyContainerPolicies> policy_container_policies =
2220 ComputePolicyContainerPoliciesForFrameEntry(rfh, is_same_document,
2221 request->GetURL());
Domenic Denicolacc094fb2022-03-16 23:40:572222 bool protect_url_in_navigation_api = false;
Nate Chapin63db0d12022-01-20 22:03:302223 if (is_same_document) {
2224 FrameNavigationEntry* previous_frame_entry =
2225 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
Domenic Denicolacc094fb2022-03-16 23:40:572226 // Try to preserve protect_url_in_navigation_api from the previous
Nate Chapin63db0d12022-01-20 22:03:302227 // FrameNavigationEntry.
Domenic Denicolacc094fb2022-03-16 23:40:572228 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302229 previous_frame_entry &&
Domenic Denicolacc094fb2022-03-16 23:40:572230 previous_frame_entry->protect_url_in_navigation_api();
Nate Chapin63db0d12022-01-20 22:03:302231 } else {
Domenic Denicolacc094fb2022-03-16 23:40:572232 protect_url_in_navigation_api =
Nate Chapin63db0d12022-01-20 22:03:302233 policy_container_policies &&
Domenic Denicolacc094fb2022-03-16 23:40:572234 ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:302235 policy_container_policies->referrer_policy);
2236 }
2237
Patrick Monette50e8bd82019-06-13 22:40:452238 auto frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Charles Reisd2a509f2017-09-27 23:47:482239 rfh->frame_tree_node()->unique_name(), params.item_sequence_number,
Domenic Denicolacc094fb2022-03-16 23:40:572240 params.document_sequence_number, params.navigation_api_key,
Nate Chapinfbfe5af2021-06-10 17:22:082241 rfh->GetSiteInstance(), nullptr, params.url,
2242 GetCommittedOriginForFrameEntry(params, request),
Rakina Zata Amni82fafba2021-03-11 07:07:092243 Referrer(*params.referrer), initiator_origin, request->GetRedirectChain(),
arthursonzogni73fe3212020-11-17 13:24:072244 params.page_state, params.method, params.post_id,
2245 nullptr /* blob_url_loader_factory */,
Tsuyoshi Horo0c605782020-05-27 00:21:032246 request->web_bundle_navigation_info()
2247 ? request->web_bundle_navigation_info()->Clone()
Antonio Sartori78a749f2020-11-30 12:03:392248 : nullptr,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482249 request->GetSubresourceWebBundleNavigationInfo(),
Domenic Denicolacc094fb2022-03-16 23:40:572250 std::move(policy_container_policies), protect_url_in_navigation_api);
Charles Reisf44482022017-10-13 21:15:032251
creisce0ef3572017-01-26 17:53:082252 std::unique_ptr<NavigationEntryImpl> new_entry =
2253 GetLastCommittedEntry()->CloneAndReplace(
Patrick Monette50e8bd82019-06-13 22:40:452254 std::move(frame_entry), is_same_document, rfh->frame_tree_node(),
Ali Hijazid87307d2022-11-07 20:15:032255 frame_tree_->root());
creise062d542015-08-25 02:01:552256
Alexander Timine3ec4192020-04-20 16:39:402257 SetShouldSkipOnBackForwardUIIfNeeded(
shivanigithube92c33da2020-09-14 13:01:412258 replace_entry, previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:402259 request->IsRendererInitiated(), request->GetPreviousPageUkmSourceId());
Shivani Sharmaffb32b82019-04-09 16:58:472260
creisce0ef3572017-01-26 17:53:082261 // TODO(creis): Update this to add the frame_entry if we can't find the one
Patrick Monette50e8bd82019-06-13 22:40:452262 // to replace, which can happen due to a unique name change. See
2263 // https://crbug.com/607205. For now, the call to CloneAndReplace() will
2264 // delete the |frame_entry| when the function exits if it doesn't get used.
creis96fc55082015-06-13 06:42:382265
Dave Tapuska87696ae2021-11-18 18:48:312266 InsertOrReplaceEntry(std::move(new_entry), replace_entry, false,
Abhijeet Kandalkare26014a92022-10-13 04:21:152267 rfh->IsNestedWithinFencedFrame(), commit_details);
[email protected]e9ba4472008-09-14 15:42:432268}
2269
[email protected]d202a7c2012-01-04 07:53:472270bool NavigationControllerImpl::RendererDidNavigateAutoSubframe(
creis3da03872015-02-20 21:12:322271 RenderFrameHostImpl* rfh,
arthursonzogni73fe3212020-11-17 13:24:072272 const mojom::DidCommitProvisionalLoadParams& params,
Antonio Sartori78a749f2020-11-30 12:03:392273 bool is_same_document,
Nate Chapinc7019dd7d2021-06-25 18:29:252274 bool was_on_initial_empty_document,
Rakina Zata Amnia4e27222021-12-22 01:05:002275 NavigationRequest* request,
2276 LoadCommittedDetails* commit_details) {
avi9f07a0c2015-02-18 22:51:292277 DCHECK(ui::PageTransitionCoreTypeIs(params.transition,
2278 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
2279
[email protected]e9ba4472008-09-14 15:42:432280 // We're guaranteed to have a previously committed entry, and we now need to
2281 // handle navigation inside of a subframe in it without creating a new entry.
2282 DCHECK(GetLastCommittedEntry());
2283
creis913c63ce2016-07-16 19:52:522284 // For newly created subframes, we don't need to send a commit notification.
2285 // This is only necessary for history navigations in subframes.
2286 bool send_commit_notification = false;
2287
Rakina Zata Amnif6950d552020-11-24 03:26:102288 // If |nav_entry_id| is non-zero and matches an existing entry, this
2289 // is a history navigation. Update the last committed index accordingly. If
2290 // we don't recognize the |nav_entry_id|, it might be a recently
2291 // pruned entry. We'll handle it below.
2292 if (const int nav_entry_id = request->commit_params().nav_entry_id) {
2293 int entry_index = GetEntryIndexWithUniqueID(nav_entry_id);
creis3cdc3b02015-05-29 23:00:472294 if (entry_index != -1 && entry_index != last_committed_entry_index_) {
avi98405c22015-05-21 20:47:062295 // Make sure that a subframe commit isn't changing the main frame's
2296 // origin. Otherwise the renderer process may be confused, leading to a
2297 // URL spoof. We can't check the path since that may change
2298 // (https://crbug.com/373041).
creis37988b92016-06-10 18:03:572299 // TODO(creis): For now, restrict this check to HTTP(S) origins, because
2300 // about:blank, file, and unique origins are more subtle to get right.
Charlie Reis95fbca442021-05-21 21:38:242301 // We should use checks similar to RenderFrameHostImpl's
2302 // CanCommitUrlAndOrigin on the main frame during subframe commits.
2303 // See https://crbug.com/1209092.
creis37988b92016-06-10 18:03:572304 const GURL& dest_top_url = GetEntryAtIndex(entry_index)->GetURL();
2305 const GURL& current_top_url = GetLastCommittedEntry()->GetURL();
2306 if (current_top_url.SchemeIsHTTPOrHTTPS() &&
2307 dest_top_url.SchemeIsHTTPOrHTTPS() &&
Mike West800532c2021-10-14 09:26:522308 current_top_url.DeprecatedGetOriginAsURL() !=
2309 dest_top_url.DeprecatedGetOriginAsURL()) {
Chris Bookholt10f4b7332022-02-14 18:25:442310 bad_message::ReceivedBadMessage(rfh->GetMainFrame()->GetProcess(),
creisfb6eeb62016-05-10 19:01:512311 bad_message::NC_AUTO_SUBFRAME);
avi98405c22015-05-21 20:47:062312 }
creis3cdc3b02015-05-29 23:00:472313
creis913c63ce2016-07-16 19:52:522314 // We only need to discard the pending entry in this history navigation
2315 // case. For newly created subframes, there was no pending entry.
avi98405c22015-05-21 20:47:062316 last_committed_entry_index_ = entry_index;
Rakina Zata Amnia4e27222021-12-22 01:05:002317 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
creis913c63ce2016-07-16 19:52:522318
2319 // History navigations should send a commit notification.
2320 send_commit_notification = true;
avi98405c22015-05-21 20:47:062321 }
[email protected]e9ba4472008-09-14 15:42:432322 }
[email protected]f233e4232013-02-23 00:55:142323
creisce0ef3572017-01-26 17:53:082324 // This may be a "new auto" case where we add a new FrameNavigationEntry, or
2325 // it may be a "history auto" case where we update an existing one.
Nate Chapin9f169072021-06-09 19:32:372326 // We may want to update |last_committed|'s FrameNavigationEntry (if one
2327 // exists), or we may want to clobber it and create a new one. We update in
2328 // cases where the corresponding FrameNavigationEntry is conceptually similar
2329 // to the document described by the commit params: same-document
2330 // navigations, history traversal to an existing entry, and reloads (including
2331 // a "soft reload" where we navigate to the same url without flagging it as a
2332 // reload). But in the case of a different document that is not logically
2333 // related to the committed FrameNavigationEntry's document (cross-document,
2334 // not same url, not a reload, not a history traversal), we replace rather
2335 // than update.
Nate Chapinc7019dd7d2021-06-25 18:29:252336 //
Nate Chapin9f169072021-06-09 19:32:372337 // In the case where we update, the FrameNavigationEntry will potentially be
2338 // shared across multiple NavigationEntries, and any updates will be reflected
2339 // in all of those NavigationEntries. In the replace case, any existing
2340 // sharing with other NavigationEntries will stop.
Nate Chapinc7019dd7d2021-06-25 18:29:252341 //
2342 // When navigating away from the initial empty document, we also update rather
2343 // than replace. Either update or replace will overwrite the initial empty
2344 // document state for |last_committed|, but if the FrameNavigationEntry for
2345 // the initial empty document is shared across multiple NavigationEntries (due
2346 // to a navigation in another frame), we want to make sure we overwrite the
2347 // initial empty document state everywhere this FrameNavigationEntry is used,
2348 // which is accompished by updating the existing FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452349 NavigationEntryImpl* last_committed = GetLastCommittedEntry();
Nate Chapin9f169072021-06-09 19:32:372350 FrameNavigationEntry* last_committed_frame_entry =
2351 last_committed->GetFrameEntry(rfh->frame_tree_node());
2352 NavigationEntryImpl::UpdatePolicy update_policy =
2353 NavigationEntryImpl::UpdatePolicy::kUpdate;
2354 if (request->common_params().navigation_type ==
Minggang Wangb9f3fa92021-07-01 15:30:312355 blink::mojom::NavigationType::DIFFERENT_DOCUMENT &&
Nate Chapin9f169072021-06-09 19:32:372356 last_committed_frame_entry &&
Nate Chapinc7019dd7d2021-06-25 18:29:252357 last_committed_frame_entry->url() != params.url &&
2358 !was_on_initial_empty_document) {
Nate Chapin9f169072021-06-09 19:32:372359 update_policy = NavigationEntryImpl::UpdatePolicy::kReplace;
2360 }
2361
Rakina Zata Amni3460d382021-10-29 00:43:372362 UpdateNavigationEntryDetails(last_committed, rfh, params, request,
Rakina Zata Amnia4e27222021-12-22 01:05:002363 update_policy, false /* is_new_entry */,
2364 commit_details);
creis625a0c7d2015-03-24 23:17:122365
creis913c63ce2016-07-16 19:52:522366 return send_commit_notification;
[email protected]e9ba4472008-09-14 15:42:432367}
2368
[email protected]d202a7c2012-01-04 07:53:472369int NavigationControllerImpl::GetIndexOfEntry(
[email protected]10f417c52011-12-28 21:04:232370 const NavigationEntryImpl* entry) const {
avif16f85a72015-11-13 18:25:032371 for (size_t i = 0; i < entries_.size(); ++i) {
2372 if (entries_[i].get() == entry)
2373 return i;
2374 }
2375 return -1;
[email protected]765b35502008-08-21 00:51:202376}
2377
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572378void NavigationControllerImpl::CopyStateFrom(NavigationController* temp,
Francois Dorayeaace782017-06-21 16:37:242379 bool needs_reload) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572380 NavigationControllerImpl* source =
2381 static_cast<NavigationControllerImpl*>(temp);
[email protected]ce3fa3c2009-04-20 19:55:572382 // Verify that we look new.
Rakina Zata Amni46087a12022-11-11 08:28:382383 DCHECK_EQ(1, GetEntryCount());
2384 DCHECK(GetLastCommittedEntry()->IsInitialEntry());
Lei Zhang96031532019-10-10 19:05:472385 DCHECK(!GetPendingEntry());
Rakina Zata Amniafd3c6582021-11-30 06:19:172386 entries_.clear();
[email protected]ce3fa3c2009-04-20 19:55:572387
Francois Dorayeaace782017-06-21 16:37:242388 needs_reload_ = needs_reload;
Bo Liucdfa4b12018-11-06 00:21:442389 needs_reload_type_ = NeedsReloadType::kCopyStateFrom;
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572390 InsertEntriesFrom(source, source->GetEntryCount());
[email protected]ce3fa3c2009-04-20 19:55:572391
Fergal Dalya1d569972021-03-16 03:24:532392 for (auto& it : source->session_storage_namespace_map_) {
[email protected]fdac6ade2013-07-20 01:06:302393 SessionStorageNamespaceImpl* source_namespace =
Fergal Dalya1d569972021-03-16 03:24:532394 static_cast<SessionStorageNamespaceImpl*>(it.second.get());
2395 session_storage_namespace_map_[it.first] = source_namespace->Clone();
[email protected]fdac6ade2013-07-20 01:06:302396 }
[email protected]4e6419c2010-01-15 04:50:342397
Lukasz Anforowicz0de0f452020-12-02 19:57:152398 FinishRestore(source->last_committed_entry_index_, RestoreType::kRestored);
[email protected]ce3fa3c2009-04-20 19:55:572399}
2400
Aran Gilman37d11632019-10-08 23:07:152401void NavigationControllerImpl::CopyStateFromAndPrune(NavigationController* temp,
2402 bool replace_entry) {
[email protected]474f8512013-05-31 22:31:162403 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012404 CHECK(CanPruneAllButLastCommitted());
[email protected]474f8512013-05-31 22:31:162405
[email protected]d202a7c2012-01-04 07:53:472406 NavigationControllerImpl* source =
2407 static_cast<NavigationControllerImpl*>(temp);
[email protected]e1cd5452010-08-26 18:03:252408
avi2b177592014-12-10 02:08:022409 // Remove all the entries leaving the last committed entry.
[email protected]79368982013-11-13 01:11:012410 PruneAllButLastCommittedInternal();
[email protected]e1cd5452010-08-26 18:03:252411
[email protected]474f8512013-05-31 22:31:162412 // We now have one entry, possibly with a new pending entry. Ensure that
2413 // adding the entries from source won't put us over the limit.
2414 DCHECK_EQ(1, GetEntryCount());
[email protected]e78a6852013-12-13 08:08:572415 if (!replace_entry)
Shivani Sharmad8c8d652019-02-13 17:27:572416 source->PruneOldestSkippableEntryIfFull();
[email protected]944822b2012-03-02 20:57:252417
Carlos IL4dea8902020-05-26 15:14:292418 // Insert the entries from source. Ignore any pending entry, since it has not
2419 // committed in source.
[email protected]474f8512013-05-31 22:31:162420 int max_source_index = source->last_committed_entry_index_;
Rakina Zata Amniafd3c6582021-11-30 06:19:172421 DCHECK_NE(max_source_index, -1);
2422 max_source_index++;
[email protected]e78a6852013-12-13 08:08:572423
2424 // Ignore the source's current entry if merging with replacement.
2425 // TODO(davidben): This should preserve entries forward of the current
2426 // too. http://crbug.com/317872
2427 if (replace_entry && max_source_index > 0)
2428 max_source_index--;
2429
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572430 InsertEntriesFrom(source, max_source_index);
[email protected]e1cd5452010-08-26 18:03:252431
2432 // Adjust indices such that the last entry and pending are at the end now.
[email protected]a26023822011-12-29 00:23:552433 last_committed_entry_index_ = GetEntryCount() - 1;
[email protected]796931a92011-08-10 01:32:142434
Hayato Ito2c8c08d02021-06-23 03:38:432435 BroadcastHistoryOffsetAndLength();
[email protected]e1cd5452010-08-26 18:03:252436}
2437
[email protected]79368982013-11-13 01:11:012438bool NavigationControllerImpl::CanPruneAllButLastCommitted() {
[email protected]474f8512013-05-31 22:31:162439 // If there is no last committed entry, we cannot prune. Even if there is a
2440 // pending entry, it may not commit, leaving this WebContents blank, despite
2441 // possibly giving it new entries via CopyStateFromAndPrune.
2442 if (last_committed_entry_index_ == -1)
2443 return false;
[email protected]9350602e2013-02-26 23:27:442444
[email protected]474f8512013-05-31 22:31:162445 // We cannot prune if there is a pending entry at an existing entry index.
2446 // It may not commit, so we have to keep the last committed entry, and thus
2447 // there is no sensible place to keep the pending entry. It is ok to have
2448 // a new pending entry, which can optionally commit as a new navigation.
2449 if (pending_entry_index_ != -1)
2450 return false;
2451
[email protected]474f8512013-05-31 22:31:162452 return true;
2453}
2454
[email protected]79368982013-11-13 01:11:012455void NavigationControllerImpl::PruneAllButLastCommitted() {
2456 PruneAllButLastCommittedInternal();
[email protected]474f8512013-05-31 22:31:162457
avi2b177592014-12-10 02:08:022458 DCHECK_EQ(0, last_committed_entry_index_);
2459 DCHECK_EQ(1, GetEntryCount());
[email protected]9350602e2013-02-26 23:27:442460
Hayato Ito2c8c08d02021-06-23 03:38:432461 BroadcastHistoryOffsetAndLength();
[email protected]9350602e2013-02-26 23:27:442462}
2463
[email protected]79368982013-11-13 01:11:012464void NavigationControllerImpl::PruneAllButLastCommittedInternal() {
[email protected]474f8512013-05-31 22:31:162465 // It is up to callers to check the invariants before calling this.
[email protected]79368982013-11-13 01:11:012466 CHECK(CanPruneAllButLastCommitted());
[email protected]97b6c4f2010-09-27 19:31:262467
Nate Chapin9eb16be72022-09-23 22:54:312468 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
2469
[email protected]474f8512013-05-31 22:31:162470 // Erase all entries but the last committed entry. There may still be a
2471 // new pending entry after this.
2472 entries_.erase(entries_.begin(),
2473 entries_.begin() + last_committed_entry_index_);
2474 entries_.erase(entries_.begin() + 1, entries_.end());
2475 last_committed_entry_index_ = 0;
[email protected]97b6c4f2010-09-27 19:31:262476}
2477
Christian Dullweber1af31e62018-02-22 11:49:482478void NavigationControllerImpl::DeleteNavigationEntries(
2479 const DeletionPredicate& deletionPredicate) {
2480 // It is up to callers to check the invariants before calling this.
2481 CHECK(CanPruneAllButLastCommitted());
2482 std::vector<int> delete_indices;
2483 for (size_t i = 0; i < entries_.size(); i++) {
2484 if (i != static_cast<size_t>(last_committed_entry_index_) &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572485 deletionPredicate.Run(entries_[i].get())) {
Christian Dullweber1af31e62018-02-22 11:49:482486 delete_indices.push_back(i);
2487 }
2488 }
2489 if (delete_indices.empty())
2490 return;
2491
2492 if (delete_indices.size() == GetEntryCount() - 1U) {
2493 PruneAllButLastCommitted();
2494 } else {
2495 // Do the deletion in reverse to preserve indices.
Ayu Ishii2f825852022-03-08 19:47:382496 for (const auto& index : base::Reversed(delete_indices)) {
2497 RemoveEntryAtIndex(index);
Christian Dullweber1af31e62018-02-22 11:49:482498 }
Hayato Ito2c8c08d02021-06-23 03:38:432499 BroadcastHistoryOffsetAndLength();
Christian Dullweber1af31e62018-02-22 11:49:482500 }
2501 delegate()->NotifyNavigationEntriesDeleted();
2502}
2503
Shivani Sharma883f5f32019-02-12 18:20:012504bool NavigationControllerImpl::IsEntryMarkedToBeSkipped(int index) {
2505 auto* entry = GetEntryAtIndex(index);
2506 return entry && entry->should_skip_on_back_forward_ui();
2507}
2508
Carlos Caballero35ce710c2019-09-19 10:59:452509BackForwardCacheImpl& NavigationControllerImpl::GetBackForwardCache() {
2510 return back_forward_cache_;
2511}
2512
clamy987a3752018-05-03 17:36:262513void NavigationControllerImpl::DiscardPendingEntry(bool was_failure) {
2514 // It is not safe to call DiscardPendingEntry while NavigateToEntry is in
2515 // progress, since this will cause a use-after-free. (We only allow this
2516 // when the tab is being destroyed for shutdown, since it won't return to
2517 // NavigateToEntry in that case.) http://crbug.com/347742.
Ali Hijazid87307d2022-11-07 20:15:032518 CHECK(!in_navigate_to_pending_entry_ || frame_tree_->IsBeingDestroyed());
clamy987a3752018-05-03 17:36:262519
2520 if (was_failure && pending_entry_) {
2521 failed_pending_entry_id_ = pending_entry_->GetUniqueID();
2522 } else {
2523 failed_pending_entry_id_ = 0;
2524 }
2525
2526 if (pending_entry_) {
2527 if (pending_entry_index_ == -1)
Paul Semel7e51469e2022-07-12 12:16:332528 pending_entry_.ClearAndDelete();
clamy987a3752018-05-03 17:36:262529 pending_entry_index_ = -1;
2530 pending_entry_ = nullptr;
2531 }
arthursonzogni66f711c2019-10-08 14:40:362532
2533 // Ensure any refs to the current pending entry are ignored if they get
2534 // deleted, by clearing the set of known refs. All future pending entries will
2535 // only be affected by new refs.
2536 pending_entry_refs_.clear();
clamy987a3752018-05-03 17:36:262537}
2538
2539void NavigationControllerImpl::SetPendingNavigationSSLError(bool error) {
2540 if (pending_entry_)
2541 pending_entry_->set_ssl_error(error);
2542}
2543
Xiaohan Wang7f8052e02022-01-14 18:44:282544#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:422545// static
2546bool NavigationControllerImpl::ValidateDataURLAsString(
2547 const scoped_refptr<const base::RefCountedString>& data_url_as_string) {
2548 if (!data_url_as_string)
2549 return false;
2550
2551 if (data_url_as_string->size() > kMaxLengthOfDataURLString)
2552 return false;
2553
2554 // The number of characters that is enough for validating a data: URI.
2555 // From the GURL's POV, the only important part here is scheme, it doesn't
2556 // check the actual content. Thus we can take only the prefix of the url, to
2557 // avoid unneeded copying of a potentially long string.
2558 const size_t kDataUriPrefixMaxLen = 64;
2559 GURL data_url(
2560 std::string(data_url_as_string->front_as<char>(),
2561 std::min(data_url_as_string->size(), kDataUriPrefixMaxLen)));
2562 if (!data_url.is_valid() || !data_url.SchemeIs(url::kDataScheme))
2563 return false;
2564
2565 return true;
2566}
2567#endif
2568
Shivani Sharma194877032019-03-07 17:52:472569void NavigationControllerImpl::NotifyUserActivation() {
2570 // When a user activation occurs, ensure that all adjacent entries for the
2571 // same document clear their skippable bit, so that the history manipulation
2572 // intervention does not apply to them.
shivanigithub99368382021-06-16 18:33:372573 if (base::FeatureList::IsEnabled(
2574 features::kDebugHistoryInterventionNoUserActivation)) {
2575 return;
2576 }
2577
Shivani Sharmac4cc8922019-04-18 03:11:172578 SetSkippableForSameDocumentEntries(GetLastCommittedEntryIndex(), false);
Shivani Sharma194877032019-03-07 17:52:472579}
2580
clamy987a3752018-05-03 17:36:262581bool NavigationControllerImpl::StartHistoryNavigationInNewSubframe(
2582 RenderFrameHostImpl* render_frame_host,
Julie Jeongeun Kimed2e5ba72019-09-12 10:14:172583 mojo::PendingAssociatedRemote<mojom::NavigationClient>* navigation_client) {
clamy987a3752018-05-03 17:36:262584 NavigationEntryImpl* entry =
2585 GetEntryWithUniqueID(render_frame_host->nav_entry_id());
2586 if (!entry)
2587 return false;
2588
2589 FrameNavigationEntry* frame_entry =
2590 entry->GetFrameEntry(render_frame_host->frame_tree_node());
2591 if (!frame_entry)
2592 return false;
2593
Nate Chapin45f620582021-09-30 17:45:432594 // |is_browser_initiated| is false here because a navigation in a new subframe
2595 // always begins with renderer action (i.e., an HTML element being inserted
2596 // into the DOM), so it is always renderer-initiated.
Camille Lamy5193caa2018-10-12 11:59:422597 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572598 render_frame_host->frame_tree_node(), entry, frame_entry,
clamyea99ea12018-05-28 13:54:232599 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432600 true /* is_history_navigation_in_new_child */,
2601 false /* is_browser_initiated */);
clamyea99ea12018-05-28 13:54:232602
2603 if (!request)
2604 return false;
2605
arthursonzognif046d4a2019-12-12 19:08:102606 request->SetNavigationClient(std::move(*navigation_client));
Arthur Hemery06173ce2019-05-29 12:11:412607
Lukasz Anforowicz9ee83c272020-12-01 20:14:052608 render_frame_host->frame_tree_node()->navigator().Navigate(std::move(request),
2609 ReloadType::NONE);
clamyea99ea12018-05-28 13:54:232610
2611 return true;
clamy987a3752018-05-03 17:36:262612}
2613
Tsuyoshi Horo52fd08e2020-07-07 07:03:452614bool NavigationControllerImpl::ReloadFrame(FrameTreeNode* frame_tree_node) {
2615 NavigationEntryImpl* entry = GetEntryAtIndex(GetCurrentEntryIndex());
2616 if (!entry)
2617 return false;
Rakina Zata Amnif297a802022-01-18 03:53:432618
2619 if (entry->IsInitialEntryNotForSynchronousAboutBlank()) {
2620 // We should never navigate to an existing initial NavigationEntry that is
2621 // the initial NavigationEntry for the initial empty document that hasn't
2622 // been overridden by the synchronous about:blank commit, to preserve
2623 // legacy behavior where trying to reload when the main frame is on the
2624 // initial empty document won't result in a navigation. See also
2625 // https://crbug.com/1277414.
2626 return false;
2627 }
Tsuyoshi Horo52fd08e2020-07-07 07:03:452628 FrameNavigationEntry* frame_entry = entry->GetFrameEntry(frame_tree_node);
2629 if (!frame_entry)
2630 return false;
John Abd-El-Malek5b669132020-07-14 01:04:142631 ReloadType reload_type = ReloadType::NORMAL;
2632 entry->set_reload_type(reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452633 std::unique_ptr<NavigationRequest> request = CreateNavigationRequestFromEntry(
John Abd-El-Malek5b669132020-07-14 01:04:142634 frame_tree_node, entry, frame_entry, reload_type,
Tsuyoshi Horo52fd08e2020-07-07 07:03:452635 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:432636 false /* is_history_navigation_in_new_child */,
2637 true /* is_browser_initiated */);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452638 if (!request)
2639 return false;
Lukasz Anforowicz9ee83c272020-12-01 20:14:052640 frame_tree_node->navigator().Navigate(std::move(request), reload_type);
Tsuyoshi Horo52fd08e2020-07-07 07:03:452641 return true;
2642}
2643
clamy987a3752018-05-03 17:36:262644void NavigationControllerImpl::NavigateFromFrameProxy(
2645 RenderFrameHostImpl* render_frame_host,
2646 const GURL& url,
Chris Hamilton83272dc2021-02-23 00:24:022647 const blink::LocalFrameToken* initiator_frame_token,
Antonio Sartori9a82f6f32020-12-14 09:22:452648 int initiator_process_id,
Anton Bikineevf62d1bf2021-05-15 17:56:072649 const absl::optional<url::Origin>& initiator_origin,
clamy987a3752018-05-03 17:36:262650 bool is_renderer_initiated,
2651 SiteInstance* source_site_instance,
2652 const Referrer& referrer,
2653 ui::PageTransition page_transition,
2654 bool should_replace_current_entry,
Yeunjoo Choi3df791a2021-02-17 07:07:252655 blink::NavigationDownloadPolicy download_policy,
clamy987a3752018-05-03 17:36:262656 const std::string& method,
2657 scoped_refptr<network::ResourceRequestBody> post_body,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:092658 const std::string& extra_headers,
Antonio Sartori2f763d9d2021-04-21 10:04:142659 network::mojom::SourceLocationPtr source_location,
John Delaney50425f82020-04-07 16:26:212660 scoped_refptr<network::SharedURLLoaderFactory> blob_url_loader_factory,
jongdeok.kim5de823b32022-06-14 04:37:502661 bool is_form_submission,
Tsuyoshi Horo167ca6432022-03-09 05:16:392662 const absl::optional<blink::Impression>& impression,
Nan Lin944e9b4e2022-04-12 13:51:222663 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:492664 bool is_embedder_initiated_fenced_frame_navigation,
Garrett Tanzerbb8db412022-09-27 21:59:462665 bool is_unfenced_top_navigation,
2666 bool force_new_browsing_instance) {
Lukasz Anforowicz63f3b9432019-05-30 05:42:582667 if (is_renderer_initiated)
2668 DCHECK(initiator_origin.has_value());
2669
clamy987a3752018-05-03 17:36:262670 FrameTreeNode* node = render_frame_host->frame_tree_node();
Nasko Oskov18006bc2018-12-06 02:53:582671
Rakina Zata Amni2322f4f82022-01-24 13:24:242672 // Don't allow an entry replacement if there is no entry to replace.
2673 // http://crbug.com/457149
2674 if (GetEntryCount() == 0)
2675 should_replace_current_entry = false;
2676
clamy987a3752018-05-03 17:36:262677 // Create a NavigationEntry for the transfer, without making it the pending
2678 // entry. Subframe transfers should have a clone of the last committed entry
2679 // with a FrameNavigationEntry for the target frame. Main frame transfers
2680 // should have a new NavigationEntry.
2681 // TODO(creis): Make this unnecessary by creating (and validating) the params
2682 // directly, passing them to the destination RenderFrameHost. See
2683 // https://crbug.com/536906.
2684 std::unique_ptr<NavigationEntryImpl> entry;
Harkiran Bolariae1b5158b2021-09-16 19:03:262685 if (!render_frame_host->is_main_frame()) {
clamy987a3752018-05-03 17:36:262686 // Subframe case: create FrameNavigationEntry.
Rakina Zata Amnie2d31312022-11-18 03:38:452687 DCHECK(GetLastCommittedEntry());
2688 entry = GetLastCommittedEntry()->Clone();
2689 entry->set_extra_headers(extra_headers);
Rakina Zata Amniafd3c6582021-11-30 06:19:172690 // TODO(arthursonzogni): What about |is_renderer_initiated|?
2691 // Renderer-initiated navigation that target a remote frame are currently
2692 // classified as browser-initiated when this one has already navigated.
2693 // See https://crbug.com/722251.
Nate Chapin9f169072021-06-09 19:32:372694 // The UpdatePolicy doesn't matter here. |entry| is only used as a parameter
2695 // to CreateNavigationRequestFromLoadParams(), so while kReplace might
2696 // remove child FrameNavigationEntries (e.g., if this is a cross-process
2697 // same-document navigation), they will still be present in the
2698 // committed NavigationEntry that will be referenced to construct the new
2699 // FrameNavigationEntry tree when this navigation commits.
clamy987a3752018-05-03 17:36:262700 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:082701 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582702 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072703 absl::nullopt /* commit_origin */, referrer, initiator_origin,
Miyoung Shin5d77f72072020-10-09 15:14:202704 std::vector<GURL>(), blink::PageState(), method, -1,
Antonio Sartori78a749f2020-11-30 12:03:392705 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482706 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori79d549d2021-02-18 12:59:542707 nullptr /* policy_container_policies */);
clamy987a3752018-05-03 17:36:262708 } else {
2709 // Main frame case.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172710 // If `node` is the outermost main frame, it rewrites a virtual url in order
2711 // to adjust the original input url if needed. For inner frames such as
2712 // fenced frames or subframes, they don't rewrite urls as the urls are not
2713 // input urls by users.
2714 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy987a3752018-05-03 17:36:262715 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz641234d52019-11-07 21:07:102716 url, referrer, initiator_origin, source_site_instance, page_transition,
2717 is_renderer_initiated, extra_headers, browser_context_,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:172718 blob_url_loader_factory, rewrite_virtual_urls));
clamy987a3752018-05-03 17:36:262719 entry->root_node()->frame_entry->set_source_site_instance(
2720 static_cast<SiteInstanceImpl*>(source_site_instance));
2721 entry->root_node()->frame_entry->set_method(method);
2722 }
clamy987a3752018-05-03 17:36:262723
Camille Lamy5193caa2018-10-12 11:59:422724 bool override_user_agent = false;
Rakina Zata Amnie2d31312022-11-18 03:38:452725 if (GetLastCommittedEntry()->GetIsOverridingUserAgent()) {
clamy987a3752018-05-03 17:36:262726 entry->SetIsOverridingUserAgent(true);
Camille Lamy5193caa2018-10-12 11:59:422727 override_user_agent = true;
clamy987a3752018-05-03 17:36:262728 }
2729 // TODO(creis): Set user gesture and intent received timestamp on Android.
2730
2731 // We may not have successfully added the FrameNavigationEntry to |entry|
2732 // above (per https://crbug.com/608402), in which case we create it from
2733 // scratch. This works because we do not depend on |frame_entry| being inside
2734 // |entry| during NavigateToEntry. This will go away when we shortcut this
2735 // further in https://crbug.com/536906.
2736 scoped_refptr<FrameNavigationEntry> frame_entry(entry->GetFrameEntry(node));
2737 if (!frame_entry) {
Patrick Monette50e8bd82019-06-13 22:40:452738 frame_entry = base::MakeRefCounted<FrameNavigationEntry>(
Nate Chapinfbfe5af2021-06-10 17:22:082739 node->unique_name(), -1, -1, "", nullptr,
Nasko Oskov18006bc2018-12-06 02:53:582740 static_cast<SiteInstanceImpl*>(source_site_instance), url,
Anton Bikineevf62d1bf2021-05-15 17:56:072741 absl::nullopt /* origin */, referrer, initiator_origin,
Rakina Zata Amni3a1c0ec2021-04-15 03:35:122742 std::vector<GURL>(), blink::PageState(), method, -1,
2743 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:482744 nullptr /* subresource_web_bundle_navigation_info */,
Nate Chapin63db0d12022-01-20 22:03:302745 nullptr /* policy_container_policies */,
Domenic Denicolacc094fb2022-03-16 23:40:572746 false /* protect_url_in_navigation_api */);
clamy987a3752018-05-03 17:36:262747 }
2748
Camille Lamy5193caa2018-10-12 11:59:422749 LoadURLParams params(url);
Chris Hamilton83272dc2021-02-23 00:24:022750 params.initiator_frame_token = base::OptionalFromPtr(initiator_frame_token);
Antonio Sartori9a82f6f32020-12-14 09:22:452751 params.initiator_process_id = initiator_process_id;
Nasko Oskov93e7c55c2018-12-19 01:59:292752 params.initiator_origin = initiator_origin;
Camille Lamy5193caa2018-10-12 11:59:422753 params.source_site_instance = source_site_instance;
2754 params.load_type = method == "POST" ? LOAD_TYPE_HTTP_POST : LOAD_TYPE_DEFAULT;
2755 params.transition_type = page_transition;
Dominic Farolino226226af2019-06-25 00:58:032756 params.frame_tree_node_id = node->frame_tree_node_id();
Camille Lamy5193caa2018-10-12 11:59:422757 params.referrer = referrer;
2758 /* params.redirect_chain: skip */
2759 params.extra_headers = extra_headers;
2760 params.is_renderer_initiated = is_renderer_initiated;
2761 params.override_user_agent = UA_OVERRIDE_INHERIT;
2762 /* params.base_url_for_data_url: skip */
2763 /* params.virtual_url_for_data_url: skip */
2764 /* params.data_url_as_string: skip */
2765 params.post_data = post_body;
2766 params.can_load_local_resources = false;
Kevin McNeee60e76b2019-11-27 20:01:582767 /* params.should_replace_current_entry: skip */
Camille Lamy5193caa2018-10-12 11:59:422768 /* params.frame_name: skip */
2769 // TODO(clamy): See if user gesture should be propagated to this function.
2770 params.has_user_gesture = false;
2771 params.should_clear_history_list = false;
2772 params.started_from_context_menu = false;
2773 /* params.navigation_ui_data: skip */
2774 /* params.input_start: skip */
Minggang Wangf59db47b2021-06-16 01:56:222775 params.was_activated = blink::mojom::WasActivatedOption::kUnknown;
Robert Ogden011a8082019-01-23 19:04:542776 /* params.reload_type: skip */
John Delaney50425f82020-04-07 16:26:212777 params.impression = impression;
Antonio Sartori6984c742021-08-26 08:03:412778 params.download_policy = std::move(download_policy);
jongdeok.kim5de823b32022-06-14 04:37:502779 params.is_form_submission = is_form_submission;
Camille Lamy5193caa2018-10-12 11:59:422780
2781 std::unique_ptr<NavigationRequest> request =
2782 CreateNavigationRequestFromLoadParams(
Dominic Farolino226226af2019-06-25 00:58:032783 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:142784 false /* has_user_gesture */, std::move(source_location),
Tsuyoshi Horo167ca6432022-03-09 05:16:392785 ReloadType::NONE, entry.get(), frame_entry.get(),
Garrett Tanzer405f3402022-07-21 20:12:492786 navigation_start_time, is_embedder_initiated_fenced_frame_navigation,
2787 is_unfenced_top_navigation);
clamyea99ea12018-05-28 13:54:232788
2789 if (!request)
2790 return;
2791
Garrett Tanzerbb8db412022-09-27 21:59:462792 // Force the navigation to take place in a new browsing instance.
2793 // This is used by _unfencedTop in fenced frames to ensure that navigations
2794 // leaving the fenced context create a new browsing instance.
2795 if (force_new_browsing_instance) {
2796 request->coop_status().ForceBrowsingInstanceSwap();
2797 }
2798
Arthur Hemery948742762019-09-18 10:06:242799 // At this stage we are proceeding with this navigation. If this was renderer
2800 // initiated with user gesture, we need to make sure we clear up potential
2801 // remains of a cancelled browser initiated navigation to avoid URL spoofs.
2802 DiscardNonCommittedEntries();
2803
Lukasz Anforowicz9ee83c272020-12-01 20:14:052804 node->navigator().Navigate(std::move(request), ReloadType::NONE);
clamy987a3752018-05-03 17:36:262805}
2806
[email protected]d1198fd2012-08-13 22:50:192807void NavigationControllerImpl::SetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252808 const StoragePartitionConfig& partition_config,
[email protected]8ff00d72012-10-23 19:12:212809 SessionStorageNamespace* session_storage_namespace) {
[email protected]d1198fd2012-08-13 22:50:192810 if (!session_storage_namespace)
2811 return;
2812
2813 // We can't overwrite an existing SessionStorage without violating spec.
2814 // Attempts to do so may give a tab access to another tab's session storage
2815 // so die hard on an error.
Aran Gilman37d11632019-10-08 23:07:152816 bool successful_insert =
2817 session_storage_namespace_map_
Alex Moshchuk8015afcf2022-01-31 22:59:252818 .insert(std::make_pair(partition_config,
Aaron Colwellf3b316e2021-03-11 20:17:052819 static_cast<SessionStorageNamespaceImpl*>(
2820 session_storage_namespace)))
[email protected]fdac6ade2013-07-20 01:06:302821 .second;
2822 CHECK(successful_insert) << "Cannot replace existing SessionStorageNamespace";
[email protected]d1198fd2012-08-13 22:50:192823}
2824
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572825bool NavigationControllerImpl::IsUnmodifiedBlankTab() {
Rakina Zata Amnie2d31312022-11-18 03:38:452826 return IsInitialNavigation() && GetLastCommittedEntry()->IsInitialEntry() &&
Ali Hijazid87307d2022-11-07 20:15:032827 !frame_tree_->has_accessed_initial_main_document();
[email protected]aa62afd2014-04-22 19:22:462828}
2829
Aran Gilman37d11632019-10-08 23:07:152830SessionStorageNamespace* NavigationControllerImpl::GetSessionStorageNamespace(
Alex Moshchuk8015afcf2022-01-31 22:59:252831 const StoragePartitionConfig& partition_config) {
[email protected]fdac6ade2013-07-20 01:06:302832 StoragePartition* partition =
Lukasz Anforowiczb9a969a2021-04-29 15:26:252833 browser_context_->GetStoragePartition(partition_config);
michaelnbacbcbd2016-02-09 00:32:032834 DOMStorageContextWrapper* context_wrapper =
2835 static_cast<DOMStorageContextWrapper*>(partition->GetDOMStorageContext());
2836
2837 SessionStorageNamespaceMap::const_iterator it =
Alex Moshchuk8015afcf2022-01-31 22:59:252838 session_storage_namespace_map_.find(partition_config);
michaelnbacbcbd2016-02-09 00:32:032839 if (it != session_storage_namespace_map_.end()) {
2840 // Ensure that this namespace actually belongs to this partition.
Aran Gilman37d11632019-10-08 23:07:152841 DCHECK(static_cast<SessionStorageNamespaceImpl*>(it->second.get())
2842 ->IsFromContext(context_wrapper));
Aaron Colwellb731a0ae2021-03-19 19:14:472843
michaelnbacbcbd2016-02-09 00:32:032844 return it->second.get();
2845 }
2846
2847 // Create one if no one has accessed session storage for this partition yet.
Daniel Murphy31bbb8b12018-02-07 21:44:102848 scoped_refptr<SessionStorageNamespaceImpl> session_storage_namespace =
2849 SessionStorageNamespaceImpl::Create(context_wrapper);
2850 SessionStorageNamespaceImpl* session_storage_namespace_ptr =
2851 session_storage_namespace.get();
Alex Moshchuk8015afcf2022-01-31 22:59:252852 session_storage_namespace_map_[partition_config] =
Daniel Murphy31bbb8b12018-02-07 21:44:102853 std::move(session_storage_namespace);
[email protected]fdac6ade2013-07-20 01:06:302854
Daniel Murphy31bbb8b12018-02-07 21:44:102855 return session_storage_namespace_ptr;
[email protected]fdac6ade2013-07-20 01:06:302856}
2857
2858SessionStorageNamespace*
2859NavigationControllerImpl::GetDefaultSessionStorageNamespace() {
Alex Moshchuk8015afcf2022-01-31 22:59:252860 return GetSessionStorageNamespace(
2861 StoragePartitionConfig::CreateDefault(GetBrowserContext()));
[email protected]fdac6ade2013-07-20 01:06:302862}
2863
2864const SessionStorageNamespaceMap&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572865NavigationControllerImpl::GetSessionStorageNamespaceMap() {
[email protected]fdac6ade2013-07-20 01:06:302866 return session_storage_namespace_map_;
[email protected]a26023822011-12-29 00:23:552867}
[email protected]d202a7c2012-01-04 07:53:472868
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572869bool NavigationControllerImpl::NeedsReload() {
[email protected]71fde352011-12-29 03:29:562870 return needs_reload_;
2871}
[email protected]a26023822011-12-29 00:23:552872
[email protected]46bb5e9c2013-10-03 22:16:472873void NavigationControllerImpl::SetNeedsReload() {
Alex Moshchuk7b4f0652019-05-30 18:54:412874 SetNeedsReload(NeedsReloadType::kRequestedByClient);
2875}
2876
2877void NavigationControllerImpl::SetNeedsReload(NeedsReloadType type) {
[email protected]46bb5e9c2013-10-03 22:16:472878 needs_reload_ = true;
Alex Moshchuk7b4f0652019-05-30 18:54:412879 needs_reload_type_ = type;
jaekyunc8cefa82015-01-09 20:14:542880
2881 if (last_committed_entry_index_ != -1) {
2882 entries_[last_committed_entry_index_]->SetTransitionType(
2883 ui::PAGE_TRANSITION_RELOAD);
2884 }
[email protected]46bb5e9c2013-10-03 22:16:472885}
2886
[email protected]d202a7c2012-01-04 07:53:472887void NavigationControllerImpl::RemoveEntryAtIndexInternal(int index) {
Kevin McNee05164772019-09-03 17:24:572888 DCHECK_LT(index, GetEntryCount());
2889 DCHECK_NE(index, last_committed_entry_index_);
[email protected]43032342011-03-21 14:10:312890 DiscardNonCommittedEntries();
2891
Nate Chapin9eb16be72022-09-23 22:54:312892 RemovedEntriesTracker tracker(weak_factory_.GetSafeRef());
[email protected]43032342011-03-21 14:10:312893 entries_.erase(entries_.begin() + index);
[email protected]6a13a6c2011-12-20 21:47:122894 if (last_committed_entry_index_ > index)
[email protected]43032342011-03-21 14:10:312895 last_committed_entry_index_--;
2896}
2897
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572898NavigationEntryImpl* NavigationControllerImpl::GetPendingEntry() {
arthursonzogni5c4c202d2017-04-25 23:41:272899 // If there is no pending_entry_, there should be no pending_entry_index_.
2900 DCHECK(pending_entry_ || pending_entry_index_ == -1);
2901
2902 // If there is a pending_entry_index_, then pending_entry_ must be the entry
Carlos IL42b416592019-10-07 23:10:362903 // at that index. An exception is while a reload of a post commit error page
2904 // is ongoing; in that case pending entry will point to the entry replaced
2905 // by the error.
arthursonzogni5c4c202d2017-04-25 23:41:272906 DCHECK(pending_entry_index_ == -1 ||
Carlos IL42b416592019-10-07 23:10:362907 pending_entry_ == GetEntryAtIndex(pending_entry_index_) ||
2908 pending_entry_ == entry_replaced_by_post_commit_error_.get());
arthursonzogni5c4c202d2017-04-25 23:41:272909
[email protected]022af742011-12-28 18:37:252910 return pending_entry_;
2911}
2912
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572913int NavigationControllerImpl::GetPendingEntryIndex() {
arthursonzogni5c4c202d2017-04-25 23:41:272914 // The pending entry index must always be less than the number of entries.
arthursonzogni5c4c202d2017-04-25 23:41:272915 DCHECK_LT(pending_entry_index_, GetEntryCount());
[email protected]a26023822011-12-29 00:23:552916 return pending_entry_index_;
2917}
2918
avi25764702015-06-23 15:43:372919void NavigationControllerImpl::InsertOrReplaceEntry(
dcheng9bfa5162016-04-09 01:00:572920 std::unique_ptr<NavigationEntryImpl> entry,
Carlos IL42b416592019-10-07 23:10:362921 bool replace,
Dave Tapuska87696ae2021-11-18 18:48:312922 bool was_post_commit_error,
Rakina Zata Amnia4e27222021-12-22 01:05:002923 bool in_fenced_frame_tree,
2924 LoadCommittedDetails* commit_details) {
Dave Tapuska87696ae2021-11-18 18:48:312925 // Fenced frame trees should always have `ui::PAGE_TRANSITION_AUTO_SUBFRAME`
2926 // set because:
2927 // 1) They don't influence the history of the outer page.
2928 // 2) They are always replace only navigation (there is always only one entry
2929 // in their history stack).
2930 // 3) Are not top level navigations and appear similar to iframes.
2931 // Navigations of the fenced frame might create a new NavigationEntry, which
2932 // will call this function. Non fenced frame navigations will never have
2933 // `ui::PAGE_TRANSITION_AUTO_SUBFRAME` because they won't call
2934 // InsertOrReplaceEntry.
2935 DCHECK_EQ(in_fenced_frame_tree,
2936 ui::PageTransitionCoreTypeIs(entry->GetTransitionType(),
2937 ui::PAGE_TRANSITION_AUTO_SUBFRAME));
[email protected]765b35502008-08-21 00:51:202938
avi5cad4912015-06-19 05:25:442939 // If the pending_entry_index_ is -1, the navigation was to a new page, and we
2940 // need to keep continuity with the pending entry, so copy the pending entry's
2941 // unique ID to the committed entry. If the pending_entry_index_ isn't -1,
2942 // then the renderer navigated on its own, independent of the pending entry,
2943 // so don't copy anything.
2944 if (pending_entry_ && pending_entry_index_ == -1)
2945 entry->set_unique_id(pending_entry_->GetUniqueID());
[email protected]765b35502008-08-21 00:51:202946
Rakina Zata Amnia4e27222021-12-22 01:05:002947 DiscardNonCommittedEntriesWithCommitDetails(commit_details);
[email protected]765b35502008-08-21 00:51:202948
creisee17e932015-07-17 17:56:222949 // When replacing, don't prune the forward history.
Rakina Zata Amnie2d31312022-11-18 03:38:452950 if (replace || was_post_commit_error) {
Mikel Astizba9cf2fd2017-12-17 10:38:102951 CopyReplacedNavigationEntryDataIfPreviouslyEmpty(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:572952 entries_[last_committed_entry_index_].get(), entry.get());
Carlos IL42b416592019-10-07 23:10:362953 // If the new entry is a post-commit error page, we store the current last
2954 // committed entry to the side so that we can put it back when navigating
2955 // away from the error.
2956 if (was_post_commit_error) {
2957 DCHECK(!entry_replaced_by_post_commit_error_);
2958 entry_replaced_by_post_commit_error_ =
2959 std::move(entries_[last_committed_entry_index_]);
2960 }
dcheng36b6aec92015-12-26 06:16:362961 entries_[last_committed_entry_index_] = std::move(entry);
creisee17e932015-07-17 17:56:222962 return;
2963 }
[email protected]765b35502008-08-21 00:51:202964
creis37979a62015-08-04 19:48:182965 // We shouldn't see replace == true when there's no committed entries.
2966 DCHECK(!replace);
2967
Michael Thiessen9b14d512019-09-23 21:19:472968 PruneForwardEntries();
[email protected]765b35502008-08-21 00:51:202969
Shivani Sharmad8c8d652019-02-13 17:27:572970 PruneOldestSkippableEntryIfFull();
[email protected]765b35502008-08-21 00:51:202971
dcheng36b6aec92015-12-26 06:16:362972 entries_.push_back(std::move(entry));
[email protected]765b35502008-08-21 00:51:202973 last_committed_entry_index_ = static_cast<int>(entries_.size()) - 1;
initial.commit09911bf2008-07-26 23:55:292974}
2975
Shivani Sharmad8c8d652019-02-13 17:27:572976void NavigationControllerImpl::PruneOldestSkippableEntryIfFull() {
Shivani Sharma2d5b4b6b2019-01-08 16:07:162977 if (entries_.size() < max_entry_count())
2978 return;
2979
2980 DCHECK_EQ(max_entry_count(), entries_.size());
2981 DCHECK_GT(last_committed_entry_index_, 0);
Shivani Sharmad8c8d652019-02-13 17:27:572982 CHECK_EQ(pending_entry_index_, -1);
2983
2984 int index = 0;
Elly Fong-Jonesccc6d1f2021-06-14 18:32:422985 // Retrieve the oldest skippable entry.
2986 for (; index < GetEntryCount(); index++) {
2987 if (GetEntryAtIndex(index)->should_skip_on_back_forward_ui())
2988 break;
Shivani Sharmad8c8d652019-02-13 17:27:572989 }
2990
2991 // If there is no skippable entry or if it is the last committed entry then
2992 // fall back to pruning the oldest entry. It is not safe to prune the last
2993 // committed entry.
2994 if (index == GetEntryCount() || index == last_committed_entry_index_)
2995 index = 0;
2996
2997 bool should_succeed = RemoveEntryAtIndex(index);
2998 DCHECK_EQ(true, should_succeed);
2999
3000 NotifyPrunedEntries(this, index, 1);
[email protected]944822b2012-03-02 20:57:253001}
3002
clamy3cb9bea92018-07-10 12:42:023003void NavigationControllerImpl::NavigateToExistingPendingEntry(
Dave Tapuska8bfd84c2019-03-26 20:47:163004 ReloadType reload_type,
Nate Chapinbf682fa32022-09-26 22:41:203005 RenderFrameHostImpl* initiator_rfh,
Yoav Weiss8c573952022-11-17 17:35:133006 absl::optional<blink::scheduler::TaskAttributionId>
3007 soft_navigation_heuristics_task_id,
Nate Chapinbf682fa32022-09-26 22:41:203008 const std::string* navigation_api_key) {
Alexander Timin3a92df72019-09-20 11:59:503009 TRACE_EVENT0("navigation",
3010 "NavigationControllerImpl::NavigateToExistingPendingEntry");
arthursonzogni5c4c202d2017-04-25 23:41:273011 DCHECK(pending_entry_);
clamy3cb9bea92018-07-10 12:42:023012 DCHECK(IsInitialNavigation() || pending_entry_index_ != -1);
Carlos IL42b416592019-10-07 23:10:363013 if (pending_entry_index_ != -1) {
3014 // The pending entry may not be in entries_ if a post-commit error page is
3015 // showing.
3016 DCHECK(pending_entry_ == entries_[pending_entry_index_].get() ||
3017 pending_entry_ == entry_replaced_by_post_commit_error_.get());
3018 }
Gyuyoung Kim107c2a02021-04-13 01:49:303019 DCHECK(!blink::IsRendererDebugURL(pending_entry_->GetURL()));
Alex Moshchuk3a4e77a2020-05-29 21:32:573020 bool is_forced_reload = needs_reload_;
[email protected]72097fd02010-01-21 23:36:013021 needs_reload_ = false;
Ali Hijazid87307d2022-11-07 20:15:033022 FrameTreeNode* root = frame_tree_->root();
Arthur Sonzogni620cec62018-12-13 13:08:573023 int nav_entry_id = pending_entry_->GetUniqueID();
Nate Chapinbf682fa32022-09-26 22:41:203024 bool is_browser_initiated = !initiator_rfh;
Yoav Weiss8c573952022-11-17 17:35:133025 // Only pass down the soft_navigation_heuristics_task_id when the initiator is
3026 // the same as the top level frame being navigated.
3027 if (root->current_frame_host() != initiator_rfh) {
3028 soft_navigation_heuristics_task_id = absl::nullopt;
3029 }
Arthur Sonzogni620cec62018-12-13 13:08:573030
[email protected]83c2e232011-10-07 21:36:463031 // If we were navigating to a slow-to-commit page, and the user performs
3032 // a session history navigation to the last committed page, RenderViewHost
3033 // will force the throbber to start, but WebKit will essentially ignore the
3034 // navigation, and won't send a message to stop the throbber. To prevent this
3035 // from happening, we drop the navigation here and stop the slow-to-commit
3036 // page from loading (which would normally happen during the navigation).
clamy3cb9bea92018-07-10 12:42:023037 if (pending_entry_index_ == last_committed_entry_index_ &&
Lukasz Anforowicz6b75c0d2020-12-01 22:56:083038 !pending_entry_->IsRestored() &&
arthursonzogni5c4c202d2017-04-25 23:41:273039 pending_entry_->GetTransitionType() & ui::PAGE_TRANSITION_FORWARD_BACK) {
Ali Hijazid87307d2022-11-07 20:15:033040 frame_tree_->StopLoading();
[email protected]6a13a6c2011-12-20 21:47:123041
[email protected]83c2e232011-10-07 21:36:463042 DiscardNonCommittedEntries();
3043 return;
3044 }
3045
creisce0ef3572017-01-26 17:53:083046 // Compare FrameNavigationEntries to see which frames in the tree need to be
3047 // navigated.
clamy3cb9bea92018-07-10 12:42:023048 std::vector<std::unique_ptr<NavigationRequest>> same_document_loads;
3049 std::vector<std::unique_ptr<NavigationRequest>> different_document_loads;
Nate Chapin45f620582021-09-30 17:45:433050 FindFramesToNavigate(root, reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133051 soft_navigation_heuristics_task_id, &same_document_loads,
3052 &different_document_loads);
creis4e2ecb72015-06-20 00:46:303053
3054 if (same_document_loads.empty() && different_document_loads.empty()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573055 // We were unable to match any frames to navigate. This can happen if a
3056 // history navigation targets a subframe that no longer exists
3057 // (https://crbug.com/705550). In this case, we need to update the current
3058 // history entry to the pending one but keep the main document loaded. We
3059 // also need to ensure that observers are informed about the updated
3060 // current history entry (e.g., for greying out back/forward buttons), and
3061 // that renderer processes update their history offsets. The easiest way
3062 // to do all that is to schedule a "redundant" same-document navigation in
3063 // the main frame.
3064 //
3065 // Note that we don't want to remove this history entry, as it might still
3066 // be valid later, since a frame that it's targeting may be recreated.
3067 //
3068 // TODO(alexmos, creis): This behavior isn't ideal, as the user would
3069 // need to repeat history navigations until finding the one that works.
3070 // Consider changing this behavior to keep looking for the first valid
3071 // history entry that finds frames to navigate.
clamy3cb9bea92018-07-10 12:42:023072 std::unique_ptr<NavigationRequest> navigation_request =
Camille Lamy5193caa2018-10-12 11:59:423073 CreateNavigationRequestFromEntry(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573074 root, pending_entry_, pending_entry_->GetFrameEntry(root),
Alex Moshchuk3a4e77a2020-05-29 21:32:573075 ReloadType::NONE /* reload_type */,
3076 true /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433077 false /* is_history_navigation_in_new_child */,
3078 is_browser_initiated);
clamy3cb9bea92018-07-10 12:42:023079 if (!navigation_request) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573080 // If this navigation cannot start, delete the pending NavigationEntry.
clamy3cb9bea92018-07-10 12:42:023081 DiscardPendingEntry(false);
3082 return;
3083 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573084 same_document_loads.push_back(std::move(navigation_request));
3085
3086 // Sanity check that we never take this branch for any kinds of reloads,
3087 // as those should've queued a different-document load in the main frame.
3088 DCHECK(!is_forced_reload);
3089 DCHECK_EQ(reload_type, ReloadType::NONE);
creis4e2ecb72015-06-20 00:46:303090 }
3091
Nate Chapinbf682fa32022-09-26 22:41:203092 // If the initiator is top-navigation sandboxed, then track whether this
Dave Tapuska8bfd84c2019-03-26 20:47:163093 // navigation affects any frame outside the frame's subtree.
Nate Chapinbf682fa32022-09-26 22:41:203094 if (initiator_rfh && initiator_rfh->IsSandboxed(
3095 network::mojom::WebSandboxFlags::kTopNavigation)) {
3096 bool navigates_inside_tree = DoesSandboxNavigationStayWithinSubtree(
3097 initiator_rfh, same_document_loads) &&
3098 DoesSandboxNavigationStayWithinSubtree(
3099 initiator_rfh, different_document_loads);
Dave Tapuska716ed3af2019-09-23 18:45:503100 // Count the navigations as web use counters so we can determine
Dave Tapuska8bfd84c2019-03-26 20:47:163101 // the number of pages that trigger this.
Nate Chapinbf682fa32022-09-26 22:41:203102 GetContentClient()->browser()->LogWebFeatureForCurrentPage(
3103 initiator_rfh,
3104 navigates_inside_tree
3105 ? blink::mojom::WebFeature::kSandboxBackForwardStaysWithinSubtree
3106 : blink::mojom::WebFeature::
3107 kSandboxBackForwardAffectsFramesOutsideSubtree);
Dave Tapuska855c1e12019-08-23 20:45:523108
3109 // If the navigation occurred outside the tree discard it because
3110 // the sandboxed frame didn't have permission to navigate outside
3111 // its tree. If it is possible that the navigation is both inside and
3112 // outside the frame tree and we discard it entirely because we don't
3113 // want to end up in a history state that didn't exist before.
Dominic Farolino057440042022-01-19 18:18:143114 if (!navigates_inside_tree) {
Nate Chapinbf682fa32022-09-26 22:41:203115 // If a |navigation_api_key| was provided, this navigation originated from
3116 // the navigation API. Notify the renderer that the navigation was
3117 // cancelled so the navigation API can fire an error event and reject the
3118 // relevant promise.
3119 if (navigation_api_key) {
3120 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
3121 *navigation_api_key,
3122 blink::mojom::TraverseCancelledReason::kSandboxViolation);
3123 }
Dave Tapuska855c1e12019-08-23 20:45:523124 DiscardPendingEntry(false);
3125 return;
3126 }
Dave Tapuska8bfd84c2019-03-26 20:47:163127 }
3128
Carlos Caballero539a421c2020-07-06 10:25:573129 // BackForwardCache:
3130 // Navigate immediately if the document is in the BackForwardCache.
3131 if (back_forward_cache_.GetEntry(nav_entry_id)) {
3132 TRACE_EVENT0("navigation", "BackForwardCache_CreateNavigationRequest");
3133 DCHECK_EQ(reload_type, ReloadType::NONE);
3134 auto navigation_request = CreateNavigationRequestFromEntry(
3135 root, pending_entry_, pending_entry_->GetFrameEntry(root),
3136 ReloadType::NONE, false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433137 false /* is_history_navigation_in_new_child */, is_browser_initiated);
Lukasz Anforowicz9ee83c272020-12-01 20:14:053138 root->navigator().Navigate(std::move(navigation_request), ReloadType::NONE);
Carlos Caballero539a421c2020-07-06 10:25:573139
3140 return;
3141 }
3142
3143 // History navigation might try to reuse a specific BrowsingInstance, already
3144 // used by a page in the cache. To avoid having two different main frames that
3145 // live in the same BrowsingInstance, evict the all pages with this
3146 // BrowsingInstance from the cache.
3147 //
3148 // For example, take the following scenario:
3149 //
3150 // A1 = Some page on a.com
3151 // A2 = Some other page on a.com
3152 // B3 = An uncacheable page on b.com
3153 //
3154 // Then the following navigations occur:
3155 // A1->A2->B3->A1
3156 // On the navigation from B3 to A1, A2 will remain in the cache (B3 doesn't
3157 // take its place) and A1 will be created in the same BrowsingInstance (and
3158 // SiteInstance), as A2.
3159 //
3160 // If we didn't do anything, both A1 and A2 would remain alive in the same
3161 // BrowsingInstance/SiteInstance, which is unsupported by
3162 // RenderFrameHostManager::CommitPending(). To avoid this conundrum, we evict
3163 // A2 from the cache.
3164 if (pending_entry_->site_instance()) {
3165 back_forward_cache_.EvictFramesInRelatedSiteInstances(
3166 pending_entry_->site_instance());
3167 }
3168
Rakina Zata Amnid605d462022-06-01 10:17:033169 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_restored",
3170 pending_entry_ && pending_entry_->IsRestored());
3171 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_id",
3172 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3173 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_entry_index",
3174 pending_entry_index_);
3175 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "last_committed_index",
3176 last_committed_entry_index_);
3177 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "entries_size", entries_.size());
3178 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "pending_entry_initial",
3179 pending_entry_ && pending_entry_->IsInitialEntry());
3180 SCOPED_CRASH_KEY_BOOL(
3181 "nav_reentrancy", "pending_entry_initial2",
3182 pending_entry_ &&
3183 pending_entry_->IsInitialEntryNotForSynchronousAboutBlank());
3184 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_nav",
3185 IsInitialNavigation());
3186 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_initial_blank_nav",
3187 IsInitialBlankNavigation());
3188 SCOPED_CRASH_KEY_BOOL("nav_reentrancy", "is_forced_reload", is_forced_reload);
3189 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "pending_reload_type",
3190 (int)pending_reload_);
3191
clamy3cb9bea92018-07-10 12:42:023192 // This call does not support re-entrancy. See http://crbug.com/347742.
3193 CHECK(!in_navigate_to_pending_entry_);
3194 in_navigate_to_pending_entry_ = true;
creis4e2ecb72015-06-20 00:46:303195
Rakina Zata Amnid605d462022-06-01 10:17:033196 // If the navigation-reentrancy is caused by calling
3197 // NavigateToExistingPendingEntry twice, this will note the previous call's
3198 // pending entry's ID.
3199 SCOPED_CRASH_KEY_NUMBER("nav_reentrancy", "prev_pending_entry_id",
3200 pending_entry_ ? pending_entry_->GetUniqueID() : -1);
3201
arthursonzogni66f711c2019-10-08 14:40:363202 // It is not possible to delete the pending NavigationEntry while navigating
3203 // to it. Grab a reference to delay potential deletion until the end of this
3204 // function.
3205 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3206
creis4e2ecb72015-06-20 00:46:303207 // Send all the same document frame loads before the different document loads.
clamy3cb9bea92018-07-10 12:42:023208 for (auto& item : same_document_loads) {
3209 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053210 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303211 }
clamy3cb9bea92018-07-10 12:42:023212 for (auto& item : different_document_loads) {
3213 FrameTreeNode* frame = item->frame_tree_node();
Lukasz Anforowicz9ee83c272020-12-01 20:14:053214 frame->navigator().Navigate(std::move(item), reload_type);
creis4e2ecb72015-06-20 00:46:303215 }
clamy3cb9bea92018-07-10 12:42:023216
3217 in_navigate_to_pending_entry_ = false;
creis4e2ecb72015-06-20 00:46:303218}
3219
Alex Moshchuk3a4e77a2020-05-29 21:32:573220NavigationControllerImpl::HistoryNavigationAction
3221NavigationControllerImpl::DetermineActionForHistoryNavigation(
creis4e2ecb72015-06-20 00:46:303222 FrameTreeNode* frame,
Alex Moshchuk3a4e77a2020-05-29 21:32:573223 ReloadType reload_type) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423224 RenderFrameHostImpl* render_frame_host = frame->current_frame_host();
Sreeja Kamishettydb8e2892021-03-10 09:30:583225 // Only active and prerendered documents are allowed to navigate in their
3226 // frame.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423227 if (render_frame_host->lifecycle_state() !=
Sreeja Kamishetty299329ad2021-03-25 14:06:013228 RenderFrameHostImpl::LifecycleStateImpl::kPrerendering) {
Sreeja Kamishettydb8e2892021-03-10 09:30:583229 // - If the document is in pending deletion, the browser already committed
3230 // to destroying this RenderFrameHost. See https://crbug.com/930278.
3231 // - If the document is in back-forward cache, it's not allowed to navigate
3232 // as it should remain frozen. Ignore the request and evict the document
3233 // from back-forward cache.
Sreeja Kamishetty8eacabb2021-03-09 11:45:423234 //
Sreeja Kamishettydb8e2892021-03-10 09:30:583235 // If the document is inactive, there's no need to recurse into subframes,
Sreeja Kamishetty8eacabb2021-03-09 11:45:423236 // which should all be inactive as well.
Fergal Daly1336ac642021-09-14 15:13:113237 if (frame->current_frame_host()->IsInactiveAndDisallowActivation(
3238 DisallowActivationReasonId::kDetermineActionForHistoryNavigation)) {
Sreeja Kamishetty8eacabb2021-03-09 11:45:423239 return HistoryNavigationAction::kStopLooking;
Fergal Daly1336ac642021-09-14 15:13:113240 }
Sreeja Kamishetty8eacabb2021-03-09 11:45:423241 }
arthursonzogni03f76152019-02-12 10:35:203242
Alex Moshchuk3a4e77a2020-05-29 21:32:573243 // Reloads should result in a different-document load. Note that reloads may
3244 // also happen via the |needs_reload_| mechanism where the reload_type is
3245 // NONE, so detect this by comparing whether we're going to the same
3246 // entry that we're currently on. Similarly to above, only main frames
3247 // should reach this. Note that subframes support reloads, but that's done
3248 // via a different path that doesn't involve FindFramesToNavigate (see
3249 // RenderFrameHost::Reload()).
3250 if (reload_type != ReloadType::NONE ||
3251 pending_entry_index_ == last_committed_entry_index_) {
3252 DCHECK(frame->IsMainFrame());
3253 return HistoryNavigationAction::kDifferentDocument;
3254 }
3255
Alex Moshchuk47d1a4bd2020-06-01 22:15:343256 // If there is no new FrameNavigationEntry for the frame, ignore the
3257 // load. For example, this may happen when going back to an entry before a
3258 // frame was created. Suppose we commit a same-document navigation that also
3259 // results in adding a new subframe somewhere in the tree. If we go back,
3260 // the new subframe will be missing a FrameNavigationEntry in the previous
3261 // NavigationEntry, but we shouldn't delete or change what's loaded in
3262 // it.
3263 //
Alex Moshchuke65c39272020-06-03 17:55:373264 // Note that in this case, there is no need to keep looking for navigations
3265 // in subframes, which would be missing FrameNavigationEntries as well.
3266 //
Alex Moshchuk47d1a4bd2020-06-01 22:15:343267 // It's important to check this before checking |old_item| below, since both
3268 // might be null, and in that case we still shouldn't change what's loaded in
3269 // this frame. Note that scheduling any loads assumes that |new_item| is
3270 // non-null. See https://crbug.com/1088354.
3271 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3272 if (!new_item)
Alex Moshchuke65c39272020-06-03 17:55:373273 return HistoryNavigationAction::kStopLooking;
Alex Moshchuk47d1a4bd2020-06-01 22:15:343274
Charlie Reisa474fb62022-03-17 02:31:363275 // Use the RenderFrameHost's last committed FrameNavigationEntry to identify
3276 // which history item it is currently on, since this may be different than the
3277 // FrameNavigationEntry for the frame in the last committed NavigationEntry
3278 // (e.g., if a history navigation is targeting multiple frames and only some
3279 // have committed so far).
creis4e2ecb72015-06-20 00:46:303280 FrameNavigationEntry* old_item =
Charlie Reisa474fb62022-03-17 02:31:363281 frame->current_frame_host()->last_committed_frame_entry();
3282 if (!old_item) {
3283 // In cases where the RenderFrameHost does not have a FrameNavigationEntry,
3284 // fall back to the last committed NavigationEntry's record for this frame.
3285 // This may happen in cases like the initial state of the RenderFrameHost.
3286 // TODO(https://crbug.com/1304466): Ensure the RenderFrameHost always has an
3287 // accurate FrameNavigationEntry and eliminate this case.
3288 old_item = GetLastCommittedEntry()->GetFrameEntry(frame);
3289 }
3290 // If neither approach finds a FrameNavigationEntry, schedule a
3291 // different-document load.
3292 // TODO(https://crbug.com/608402): Remove this case.
Alex Moshchuk3a4e77a2020-05-29 21:32:573293 if (!old_item)
3294 return HistoryNavigationAction::kDifferentDocument;
3295
Alex Moshchuk3a4e77a2020-05-29 21:32:573296 // If the new item is not in the same SiteInstance, schedule a
3297 // different-document load. Newly restored items may not have a SiteInstance
3298 // yet, in which case it will be assigned on first commit.
3299 if (new_item->site_instance() &&
3300 new_item->site_instance() != old_item->site_instance())
3301 return HistoryNavigationAction::kDifferentDocument;
3302
3303 // Schedule a different-document load if the current RenderFrameHost is not
danakj25c436d2021-04-01 16:35:313304 // live. This case can happen for Ctrl+Back or after a renderer crash. Note
3305 // that we do this even if the history navigation would not be modifying this
3306 // frame were it live.
3307 if (!frame->current_frame_host()->IsRenderFrameLive())
Alex Moshchuk3a4e77a2020-05-29 21:32:573308 return HistoryNavigationAction::kDifferentDocument;
3309
3310 if (new_item->item_sequence_number() != old_item->item_sequence_number()) {
danakj25c436d2021-04-01 16:35:313311 // Starting a navigation after a crash early-promotes the speculative
3312 // RenderFrameHost. Then we have a RenderFrameHost with no document in it
3313 // committed yet, so we can not possibly perform a same-document history
3314 // navigation. The frame would need to be reloaded with a cross-document
3315 // navigation.
3316 if (!frame->current_frame_host()->has_committed_any_navigation())
3317 return HistoryNavigationAction::kDifferentDocument;
3318
creis54131692016-08-12 18:32:253319 // Same document loads happen if the previous item has the same document
danakjb952ef12021-01-14 19:58:493320 // sequence number but different item sequence number.
3321 if (new_item->document_sequence_number() ==
3322 old_item->document_sequence_number()) {
Alex Moshchuk3a4e77a2020-05-29 21:32:573323 return HistoryNavigationAction::kSameDocument;
danakjb952ef12021-01-14 19:58:493324 }
avib48cb312016-05-05 21:35:003325
Alex Moshchuk3a4e77a2020-05-29 21:32:573326 // Otherwise, if both item and document sequence numbers differ, this
3327 // should be a different document load.
3328 return HistoryNavigationAction::kDifferentDocument;
3329 }
3330
3331 // If the item sequence numbers match, there is no need to navigate this
Alex Moshchuke65c39272020-06-03 17:55:373332 // frame. Keep looking for navigations in this frame's children.
Alex Moshchuk3a4e77a2020-05-29 21:32:573333 DCHECK_EQ(new_item->document_sequence_number(),
3334 old_item->document_sequence_number());
Alex Moshchuke65c39272020-06-03 17:55:373335 return HistoryNavigationAction::kKeepLooking;
Alex Moshchuk3a4e77a2020-05-29 21:32:573336}
3337
3338void NavigationControllerImpl::FindFramesToNavigate(
3339 FrameTreeNode* frame,
3340 ReloadType reload_type,
Nate Chapin45f620582021-09-30 17:45:433341 bool is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133342 absl::optional<blink::scheduler::TaskAttributionId>
3343 soft_navigation_heuristics_task_id,
Alex Moshchuk3a4e77a2020-05-29 21:32:573344 std::vector<std::unique_ptr<NavigationRequest>>* same_document_loads,
3345 std::vector<std::unique_ptr<NavigationRequest>>* different_document_loads) {
3346 DCHECK(pending_entry_);
3347 FrameNavigationEntry* new_item = pending_entry_->GetFrameEntry(frame);
3348
3349 auto action = DetermineActionForHistoryNavigation(frame, reload_type);
3350
3351 if (action == HistoryNavigationAction::kSameDocument) {
3352 std::unique_ptr<NavigationRequest> navigation_request =
3353 CreateNavigationRequestFromEntry(
3354 frame, pending_entry_, new_item, reload_type,
Yoav Weiss8c573952022-11-17 17:35:133355 /*is_same_document_history_load=*/true,
3356 /*is_history_navigation_in_new_child_frame=*/false,
3357 is_browser_initiated, soft_navigation_heuristics_task_id);
Alex Moshchuk3a4e77a2020-05-29 21:32:573358 if (navigation_request) {
3359 // Only add the request if was properly created. It's possible for the
3360 // creation to fail in certain cases, e.g. when the URL is invalid.
3361 same_document_loads->push_back(std::move(navigation_request));
creis4e2ecb72015-06-20 00:46:303362 }
Alex Moshchuk3a4e77a2020-05-29 21:32:573363 } else if (action == HistoryNavigationAction::kDifferentDocument) {
Lei Zhang96031532019-10-10 19:05:473364 std::unique_ptr<NavigationRequest> navigation_request =
3365 CreateNavigationRequestFromEntry(
3366 frame, pending_entry_, new_item, reload_type,
3367 false /* is_same_document_history_load */,
Nate Chapin45f620582021-09-30 17:45:433368 false /* is_history_navigation_in_new_child */,
3369 is_browser_initiated);
Lei Zhang96031532019-10-10 19:05:473370 if (navigation_request) {
3371 // Only add the request if was properly created. It's possible for the
3372 // creation to fail in certain cases, e.g. when the URL is invalid.
3373 different_document_loads->push_back(std::move(navigation_request));
3374 }
3375 // For a different document, the subframes will be destroyed, so there's
3376 // no need to consider them.
3377 return;
Alex Moshchuke65c39272020-06-03 17:55:373378 } else if (action == HistoryNavigationAction::kStopLooking) {
3379 return;
creis4e2ecb72015-06-20 00:46:303380 }
3381
Yoav Weiss8c573952022-11-17 17:35:133382 // Do not pass down the soft_navigation_heuristics_task_id to child frames, as
3383 // we currently only support soft navigation heuristics for the top level
3384 // frame.
creis4e2ecb72015-06-20 00:46:303385 for (size_t i = 0; i < frame->child_count(); i++) {
Nate Chapin45f620582021-09-30 17:45:433386 FindFramesToNavigate(frame->child_at(i), reload_type, is_browser_initiated,
Yoav Weiss8c573952022-11-17 17:35:133387 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
Nate Chapin45f620582021-09-30 17:45:433388 same_document_loads, different_document_loads);
creis4e2ecb72015-06-20 00:46:303389 }
3390}
3391
Harkiran Bolariaba823e42021-05-21 18:30:363392base::WeakPtr<NavigationHandle> NavigationControllerImpl::NavigateWithoutEntry(
clamy21718cc22018-06-13 13:34:243393 const LoadURLParams& params) {
3394 // Find the appropriate FrameTreeNode.
3395 FrameTreeNode* node = nullptr;
3396 if (params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId ||
3397 !params.frame_name.empty()) {
3398 node = params.frame_tree_node_id != RenderFrameHost::kNoFrameTreeNodeId
Ali Hijazid87307d2022-11-07 20:15:033399 ? frame_tree_->FindByID(params.frame_tree_node_id)
3400 : frame_tree_->FindByName(params.frame_name);
3401 DCHECK(!node || node->frame_tree() == &*frame_tree_);
clamy21718cc22018-06-13 13:34:243402 }
3403
3404 // If no FrameTreeNode was specified, navigate the main frame.
3405 if (!node)
Ali Hijazid87307d2022-11-07 20:15:033406 node = frame_tree_->root();
clamy21718cc22018-06-13 13:34:243407
Camille Lamy5193caa2018-10-12 11:59:423408 // Compute overrides to the LoadURLParams for |override_user_agent|,
3409 // |should_replace_current_entry| and |has_user_gesture| that will be used
3410 // both in the creation of the NavigationEntry and the NavigationRequest.
3411 // Ideally, the LoadURLParams themselves would be updated, but since they are
3412 // passed as a const reference, this is not possible.
3413 // TODO(clamy): When we only create a NavigationRequest, move this to
3414 // CreateNavigationRequestFromLoadURLParams.
3415 bool override_user_agent = ShouldOverrideUserAgent(params.override_user_agent,
3416 GetLastCommittedEntry());
3417
Rakina Zata Amnie2d31312022-11-18 03:38:453418 // An entry replacement must happen if the current browsing context should
3419 // maintain a trivial session history.
shivanigithubf405bf0d2021-11-05 17:58:333420 bool should_replace_current_entry =
3421 (params.should_replace_current_entry ||
Rakina Zata Amnie2d31312022-11-18 03:38:453422 ShouldMaintainTrivialSessionHistory(node));
Camille Lamy5193caa2018-10-12 11:59:423423
clamy21718cc22018-06-13 13:34:243424 // Javascript URLs should not create NavigationEntries. All other navigations
3425 // do, including navigations to chrome renderer debug URLs.
clamy21718cc22018-06-13 13:34:243426 if (!params.url.SchemeIs(url::kJavaScriptScheme)) {
Scott Violet5ae6c42e2020-10-28 02:47:373427 std::unique_ptr<NavigationEntryImpl> entry =
3428 CreateNavigationEntryFromLoadParams(node, params, override_user_agent,
3429 should_replace_current_entry,
3430 params.has_user_gesture);
clamy21718cc22018-06-13 13:34:243431 DiscardPendingEntry(false);
3432 SetPendingEntry(std::move(entry));
3433 }
3434
3435 // Renderer-debug URLs are sent to the renderer process immediately for
3436 // processing and don't need to create a NavigationRequest.
3437 // Note: this includes navigations to JavaScript URLs, which are considered
3438 // renderer-debug URLs.
3439 // Note: we intentionally leave the pending entry in place for renderer debug
3440 // URLs, unlike the cases below where we clear it if the navigation doesn't
3441 // proceed.
Gyuyoung Kim107c2a02021-04-13 01:49:303442 if (blink::IsRendererDebugURL(params.url)) {
Oleg Davydov2cc0167b2019-02-05 14:32:483443 // Renderer-debug URLs won't go through NavigationThrottlers so we have to
3444 // check them explicitly. See bug 913334.
Aaron Colwelle1908d982020-06-26 22:08:153445 if (GetContentClient()->browser()->ShouldBlockRendererDebugURL(
Oleg Davydov2cc0167b2019-02-05 14:32:483446 params.url, browser_context_)) {
3447 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363448 return nullptr;
Oleg Davydov2cc0167b2019-02-05 14:32:483449 }
3450
clamy21718cc22018-06-13 13:34:243451 HandleRendererDebugURL(node, params.url);
Harkiran Bolariaba823e42021-05-21 18:30:363452 return nullptr;
clamy21718cc22018-06-13 13:34:243453 }
3454
Antonio Sartori78a749f2020-11-30 12:03:393455 DCHECK(pending_entry_);
3456
clamy21718cc22018-06-13 13:34:243457 // Convert navigations to the current URL to a reload.
3458 // TODO(clamy): We should be using FrameTreeNode::IsMainFrame here instead of
3459 // relying on the frame tree node id from LoadURLParams. Unfortunately,
3460 // DevTools sometimes issues navigations to main frames that they do not
3461 // expect to see treated as reload, and it only works because they pass a
3462 // FrameTreeNode id in their LoadURLParams. Change this once they no longer do
3463 // that. See https://crbug.com/850926.
Robert Ogden011a8082019-01-23 19:04:543464 ReloadType reload_type = params.reload_type;
3465 if (reload_type == ReloadType::NONE &&
3466 ShouldTreatNavigationAsReload(
Fergal Daly766177d2020-07-07 07:54:043467 node, params.url, pending_entry_->GetVirtualURL(),
clamy21718cc22018-06-13 13:34:243468 params.base_url_for_data_url, params.transition_type,
clamy21718cc22018-06-13 13:34:243469 params.load_type ==
3470 NavigationController::LOAD_TYPE_HTTP_POST /* is_post */,
Hayato Ito7a80db42021-07-05 06:18:543471 should_replace_current_entry, GetLastCommittedEntry())) {
clamy21718cc22018-06-13 13:34:243472 reload_type = ReloadType::NORMAL;
Alexander Timinb70f67382020-12-10 00:03:473473 pending_entry_->set_reload_type(reload_type);
Antonio Sartori78a749f2020-11-30 12:03:393474
3475 // If this is a reload of an existing FrameNavigationEntry and we had a
3476 // policy container for it, then we should copy it into the pending entry,
3477 // so that it is copied to the navigation request in
3478 // CreateNavigationRequestFromLoadParams later.
Rakina Zata Amnie2d31312022-11-18 03:38:453479 FrameNavigationEntry* previous_frame_entry =
3480 GetLastCommittedEntry()->GetFrameEntry(node);
3481 if (previous_frame_entry &&
3482 previous_frame_entry->policy_container_policies()) {
3483 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
3484 previous_frame_entry->policy_container_policies()->ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393485 }
3486 }
3487
3488 // If this navigation is an "Enter-in-omnibox" with the initial about:blank
Rakina Zata Amniafd3c6582021-11-30 06:19:173489 // document, then we should copy the document polices from RenderFrameHost's
3490 // PolicyContainerHost. The NavigationRequest will create a new
3491 // PolicyContainerHost with the document policies from the |pending_entry_|,
3492 // and that PolicyContainerHost will be put in the final RenderFrameHost for
3493 // the navigation. This way, we ensure that we keep enforcing the right
3494 // policies on the initial empty document after the reload.
Rakina Zata Amnie2d31312022-11-18 03:38:453495 if (GetLastCommittedEntry()->IsInitialEntry() && params.url.IsAboutBlank()) {
Antonio Sartori78a749f2020-11-30 12:03:393496 if (node->current_frame_host() &&
3497 node->current_frame_host()->policy_container_host()) {
Titouan Rigoudy6ec70402021-02-02 15:42:193498 pending_entry_->GetFrameEntry(node)->set_policy_container_policies(
Antonio Sartori5d09b30f2021-03-02 09:27:163499 node->current_frame_host()
3500 ->policy_container_host()
3501 ->policies()
Titouan Rigoudy72f892d2022-05-02 18:21:233502 .ClonePtr());
Antonio Sartori78a749f2020-11-30 12:03:393503 }
clamy21718cc22018-06-13 13:34:243504 }
3505
3506 // navigation_ui_data should only be present for main frame navigations.
Ian Vollick1c6dd3e2022-04-13 02:06:263507 DCHECK(node->IsOutermostMainFrame() || !params.navigation_ui_data);
clamy21718cc22018-06-13 13:34:243508
Tsuyoshi Horo167ca6432022-03-09 05:16:393509 // This will be used to set the Navigation Timing API navigationStart
3510 // parameter for browser navigations in new tabs (intents, tabs opened through
3511 // "Open link in new tab"). If the navigation must wait on the current
3512 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3513 // will be updated when the BeforeUnload ack is received.
3514 const auto navigation_start_time = base::TimeTicks::Now();
3515
Camille Lamy5193caa2018-10-12 11:59:423516 std::unique_ptr<NavigationRequest> request =
3517 CreateNavigationRequestFromLoadParams(
3518 node, params, override_user_agent, should_replace_current_entry,
Antonio Sartori2f763d9d2021-04-21 10:04:143519 params.has_user_gesture, network::mojom::SourceLocation::New(),
Tsuyoshi Horo167ca6432022-03-09 05:16:393520 reload_type, pending_entry_, pending_entry_->GetFrameEntry(node),
3521 navigation_start_time);
clamy21718cc22018-06-13 13:34:243522
3523 // If the navigation couldn't start, return immediately and discard the
3524 // pending NavigationEntry.
3525 if (!request) {
3526 DiscardPendingEntry(false);
Harkiran Bolariaba823e42021-05-21 18:30:363527 return nullptr;
clamy21718cc22018-06-13 13:34:243528 }
3529
Camille Lamy5193caa2018-10-12 11:59:423530#if DCHECK_IS_ON()
3531 // Safety check that NavigationRequest and NavigationEntry match.
3532 ValidateRequestMatchesEntry(request.get(), pending_entry_);
3533#endif
3534
clamy21718cc22018-06-13 13:34:243535 // This call does not support re-entrancy. See http://crbug.com/347742.
3536 CHECK(!in_navigate_to_pending_entry_);
3537 in_navigate_to_pending_entry_ = true;
3538
arthursonzogni66f711c2019-10-08 14:40:363539 // It is not possible to delete the pending NavigationEntry while navigating
3540 // to it. Grab a reference to delay potential deletion until the end of this
3541 // function.
3542 std::unique_ptr<PendingEntryRef> pending_entry_ref = ReferencePendingEntry();
3543
Harkiran Bolariaba823e42021-05-21 18:30:363544 base::WeakPtr<NavigationHandle> created_navigation_handle(
3545 request->GetWeakPtr());
Lukasz Anforowicz9ee83c272020-12-01 20:14:053546 node->navigator().Navigate(std::move(request), reload_type);
clamy21718cc22018-06-13 13:34:243547
3548 in_navigate_to_pending_entry_ = false;
Harkiran Bolariaba823e42021-05-21 18:30:363549 return created_navigation_handle;
clamy21718cc22018-06-13 13:34:243550}
3551
clamyea99ea12018-05-28 13:54:233552void NavigationControllerImpl::HandleRendererDebugURL(
3553 FrameTreeNode* frame_tree_node,
3554 const GURL& url) {
3555 if (!frame_tree_node->current_frame_host()->IsRenderFrameLive()) {
clamy21718cc22018-06-13 13:34:243556 // Any renderer-side debug URLs or javascript: URLs should be ignored if
3557 // the renderer process is not live, unless it is the initial navigation
3558 // of the tab.
clamyea99ea12018-05-28 13:54:233559 if (!IsInitialNavigation()) {
3560 DiscardNonCommittedEntries();
3561 return;
3562 }
Fergal Dalyecd3b0202020-06-25 01:57:373563 // The current frame is always a main frame. If IsInitialNavigation() is
3564 // true then there have been no navigations and any frames of this tab must
3565 // be in the same renderer process. If that has crashed then the only frame
3566 // that can be revived is the main frame.
3567 frame_tree_node->render_manager()
3568 ->InitializeMainRenderFrameForImmediateUse();
clamyea99ea12018-05-28 13:54:233569 }
Julie Jeongeun Kim50d124c2022-10-21 13:51:223570
3571 // Several tests expect a load of Chrome Debug URLs to send a DidStopLoading
3572 // notification, so set is loading to true here to properly surface it when
3573 // the renderer process is done handling the URL.
3574 // TODO(crbug.com/1254130): Remove the test dependency on this behavior.
3575 if (!url.SchemeIs(url::kJavaScriptScheme)) {
3576 bool was_loading = frame_tree_node->frame_tree()
3577 ->LoadingTree()
3578 ->IsLoadingIncludingInnerFrameTrees();
3579 frame_tree_node->current_frame_host()->SetIsLoadingForRendererDebugURL();
3580 frame_tree_node->DidStartLoading(true /* should_show_loading_ui */,
3581 was_loading);
3582 }
clamyea99ea12018-05-28 13:54:233583 frame_tree_node->current_frame_host()->HandleRendererDebugURL(url);
3584}
3585
clamy21718cc22018-06-13 13:34:243586std::unique_ptr<NavigationEntryImpl>
3587NavigationControllerImpl::CreateNavigationEntryFromLoadParams(
3588 FrameTreeNode* node,
Camille Lamy5193caa2018-10-12 11:59:423589 const LoadURLParams& params,
3590 bool override_user_agent,
3591 bool should_replace_current_entry,
3592 bool has_user_gesture) {
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393593 // Browser initiated navigations might not have a blob_url_loader_factory set
3594 // in params even if the navigation is to a blob URL. If that happens, lookup
3595 // the correct url loader factory to use here.
3596 auto blob_url_loader_factory = params.blob_url_loader_factory;
Kinuko Yasuda7d925ea22019-08-01 10:08:483597 if (!blob_url_loader_factory && params.url.SchemeIsBlob()) {
Marijn Kruisselbrink8ffda442020-09-03 18:29:473598 // Resolve the blob URL in the storage partition associated with the target
3599 // frame. This is the storage partition the URL will be loaded in, and only
3600 // URLs that can be resolved by it should be able to access its data.
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393601 blob_url_loader_factory = ChromeBlobStorageContext::URLLoaderFactoryForUrl(
Marijn Kruisselbrink8ffda442020-09-03 18:29:473602 node->current_frame_host()->GetStoragePartition(), params.url);
Marijn Kruisselbrink0c87e6e2018-06-22 22:57:393603 }
3604
clamy21718cc22018-06-13 13:34:243605 std::unique_ptr<NavigationEntryImpl> entry;
Tommy C. Li03eee77a2019-02-05 02:07:443606 // extra_headers in params are \n separated; navigation entries want \r\n.
3607 std::string extra_headers_crlf;
3608 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
clamy21718cc22018-06-13 13:34:243609
3610 // For subframes, create a pending entry with a corresponding frame entry.
3611 if (!node->IsMainFrame()) {
Rakina Zata Amnie2d31312022-11-18 03:38:453612 entry = GetLastCommittedEntry()->Clone();
clamy21718cc22018-06-13 13:34:243613 entry->AddOrUpdateFrameEntry(
Nate Chapinfbfe5af2021-06-10 17:22:083614 node, NavigationEntryImpl::UpdatePolicy::kReplace, -1, -1, "", nullptr,
clamy21718cc22018-06-13 13:34:243615 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()),
Anton Bikineevf62d1bf2021-05-15 17:56:073616 params.url, absl::nullopt, params.referrer, params.initiator_origin,
Miyoung Shin5d77f72072020-10-09 15:14:203617 params.redirect_chain, blink::PageState(), "GET", -1,
Antonio Sartori78a749f2020-11-30 12:03:393618 blob_url_loader_factory, nullptr /* web_bundle_navigation_info */,
Kunihiko Sakamoto346a74e2021-03-10 08:57:483619 nullptr /* subresource_web_bundle_navigation_info */,
Antonio Sartori78a749f2020-11-30 12:03:393620 // If in NavigateWithoutEntry we later determine that this navigation is
Charlie Reis7e2cb6d2021-01-26 01:27:163621 // a conversion of a new navigation into a reload, we will set the right
3622 // document policies there.
Titouan Rigoudy6ec70402021-02-02 15:42:193623 nullptr /* policy_container_policies */);
clamy21718cc22018-06-13 13:34:243624 } else {
3625 // Otherwise, create a pending entry for the main frame.
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173626 // If `node` is the outermost main frame, it rewrites a virtual url in order
3627 // to adjust the original input url if needed. For inner frames such as
3628 // fenced frames or subframes, they don't rewrite urls as the urls are not
3629 // input urls by users.
3630 bool rewrite_virtual_urls = node->IsOutermostMainFrame();
clamy21718cc22018-06-13 13:34:243631 entry = NavigationEntryImpl::FromNavigationEntry(CreateNavigationEntry(
Lukasz Anforowicz435bcb582019-07-12 20:50:063632 params.url, params.referrer, params.initiator_origin,
Lukasz Anforowicz641234d52019-11-07 21:07:103633 params.source_site_instance.get(), params.transition_type,
3634 params.is_renderer_initiated, extra_headers_crlf, browser_context_,
Julie Jeongeun Kim5b9aff72022-05-02 02:10:173635 blob_url_loader_factory, rewrite_virtual_urls));
clamy21718cc22018-06-13 13:34:243636 entry->set_source_site_instance(
3637 static_cast<SiteInstanceImpl*>(params.source_site_instance.get()));
3638 entry->SetRedirectChain(params.redirect_chain);
3639 }
3640
3641 // Set the FTN ID (only used in non-site-per-process, for tests).
3642 entry->set_frame_tree_node_id(node->frame_tree_node_id());
clamy21718cc22018-06-13 13:34:243643 entry->set_should_clear_history_list(params.should_clear_history_list);
Camille Lamy5193caa2018-10-12 11:59:423644 entry->SetIsOverridingUserAgent(override_user_agent);
3645 entry->set_has_user_gesture(has_user_gesture);
Robert Ogden011a8082019-01-23 19:04:543646 entry->set_reload_type(params.reload_type);
clamy21718cc22018-06-13 13:34:243647
clamy21718cc22018-06-13 13:34:243648 switch (params.load_type) {
3649 case LOAD_TYPE_DEFAULT:
3650 break;
3651 case LOAD_TYPE_HTTP_POST:
3652 entry->SetHasPostData(true);
3653 entry->SetPostData(params.post_data);
3654 break;
3655 case LOAD_TYPE_DATA:
3656 entry->SetBaseURLForDataURL(params.base_url_for_data_url);
3657 entry->SetVirtualURL(params.virtual_url_for_data_url);
Xiaohan Wang7f8052e02022-01-14 18:44:283658#if BUILDFLAG(IS_ANDROID)
clamy21718cc22018-06-13 13:34:243659 entry->SetDataURLAsString(params.data_url_as_string);
3660#endif
3661 entry->SetCanLoadLocalResources(params.can_load_local_resources);
3662 break;
clamy21718cc22018-06-13 13:34:243663 }
3664
3665 // TODO(clamy): NavigationEntry is meant for information that will be kept
3666 // after the navigation ended and therefore is not appropriate for
3667 // started_from_context_menu. Move started_from_context_menu to
3668 // NavigationUIData.
3669 entry->set_started_from_context_menu(params.started_from_context_menu);
3670
3671 return entry;
3672}
3673
clamyea99ea12018-05-28 13:54:233674std::unique_ptr<NavigationRequest>
Camille Lamy5193caa2018-10-12 11:59:423675NavigationControllerImpl::CreateNavigationRequestFromLoadParams(
3676 FrameTreeNode* node,
3677 const LoadURLParams& params,
3678 bool override_user_agent,
3679 bool should_replace_current_entry,
3680 bool has_user_gesture,
Antonio Sartori2f763d9d2021-04-21 10:04:143681 network::mojom::SourceLocationPtr source_location,
Camille Lamy5193caa2018-10-12 11:59:423682 ReloadType reload_type,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573683 NavigationEntryImpl* entry,
Tsuyoshi Horo167ca6432022-03-09 05:16:393684 FrameNavigationEntry* frame_entry,
Nan Lin944e9b4e2022-04-12 13:51:223685 base::TimeTicks navigation_start_time,
Garrett Tanzer405f3402022-07-21 20:12:493686 bool is_embedder_initiated_fenced_frame_navigation,
3687 bool is_unfenced_top_navigation) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573688 DCHECK_EQ(-1, GetIndexOfEntry(entry));
Camille Lamyb9ed3c52018-11-19 15:34:283689 DCHECK(frame_entry);
Nasko Oskov3c2f9e252019-01-10 17:45:533690 // All renderer-initiated navigations must have an initiator_origin.
3691 DCHECK(!params.is_renderer_initiated || params.initiator_origin.has_value());
Camille Lamyff7c4822018-11-07 15:42:513692
Camille Lamy5193caa2018-10-12 11:59:423693 GURL url_to_load;
3694 GURL virtual_url;
Nasko Oskov03912102019-01-11 00:21:323695
Camille Lamy2baa8022018-10-19 16:43:173696 // For main frames, rewrite the URL if necessary and compute the virtual URL
3697 // that should be shown in the address bar.
Ian Vollick1c6dd3e2022-04-13 02:06:263698 if (node->IsOutermostMainFrame()) {
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423699 bool ignored_reverse_on_redirect = false;
Camille Lamy2baa8022018-10-19 16:43:173700 RewriteUrlForNavigation(params.url, browser_context_, &url_to_load,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423701 &virtual_url, &ignored_reverse_on_redirect);
Camille Lamy5193caa2018-10-12 11:59:423702
Camille Lamy2baa8022018-10-19 16:43:173703 // For DATA loads, override the virtual URL.
3704 if (params.load_type == LOAD_TYPE_DATA)
3705 virtual_url = params.virtual_url_for_data_url;
Camille Lamy5193caa2018-10-12 11:59:423706
Camille Lamy2baa8022018-10-19 16:43:173707 if (virtual_url.is_empty())
3708 virtual_url = url_to_load;
3709
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573710 CHECK(virtual_url == entry->GetVirtualURL());
Camille Lamyb9ed3c52018-11-19 15:34:283711
Aran Gilman249eb122019-12-02 23:32:463712 // This is a LOG and not a CHECK/DCHECK as URL rewrite has non-deterministic
3713 // behavior: it is possible for two calls to RewriteUrlForNavigation to
3714 // return different results, leading to a different URL in the
3715 // NavigationRequest and FrameEntry. This will be fixed once we remove the
3716 // pending NavigationEntry, as we'll only make one call to
3717 // RewriteUrlForNavigation.
3718 VLOG_IF(1, (url_to_load != frame_entry->url()))
3719 << "NavigationRequest and FrameEntry have different URLs: "
3720 << url_to_load << " vs " << frame_entry->url();
Camille Lamyb9ed3c52018-11-19 15:34:283721
Camille Lamy2baa8022018-10-19 16:43:173722 // TODO(clamy): In order to remove the pending NavigationEntry,
Lukasz Anforowiczb2eb19b12020-01-25 00:40:423723 // |virtual_url| and |ignored_reverse_on_redirect| should be stored in the
Camille Lamy2baa8022018-10-19 16:43:173724 // NavigationRequest.
3725 } else {
3726 url_to_load = params.url;
3727 virtual_url = params.url;
Camille Lamyf664f7622019-01-07 19:28:243728 CHECK(!frame_entry || url_to_load == frame_entry->url());
Camille Lamy2baa8022018-10-19 16:43:173729 }
Camille Lamy5193caa2018-10-12 11:59:423730
Ehsan Karamad44fc72112019-02-26 18:15:473731 if (node->render_manager()->is_attaching_inner_delegate()) {
3732 // Avoid starting any new navigations since this node is now preparing for
3733 // attaching an inner delegate.
3734 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203735 }
Camille Lamy5193caa2018-10-12 11:59:423736
Ian Vollick1c6dd3e2022-04-13 02:06:263737 if (!IsValidURLForNavigation(node->IsOutermostMainFrame(), virtual_url,
3738 url_to_load))
Camille Lamy5193caa2018-10-12 11:59:423739 return nullptr;
3740
danakjd83d706d2020-11-25 22:11:123741 // Look for a pending commit that is to another document in this
3742 // FrameTreeNode. If one exists, then the last committed URL will not be the
3743 // current URL by the time this navigation commits.
3744 bool has_pending_cross_document_commit =
3745 node->render_manager()->HasPendingCommitForCrossDocumentNavigation();
Miyoung Shina2dd6a42021-10-07 12:19:213746 bool is_currently_error_page = node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123747
Minggang Wangb9f3fa92021-07-01 15:30:313748 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjb952ef12021-01-14 19:58:493749 /*old_url=*/node->current_url(),
3750 /*new_url=*/url_to_load, reload_type, entry, *frame_entry,
3751 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer267c2b82022-07-26 16:53:133752 /*is_same_document_history_load=*/false,
3753 is_embedder_initiated_fenced_frame_navigation,
3754 is_unfenced_top_navigation);
Camille Lamy5193caa2018-10-12 11:59:423755
3756 // Create the NavigationParams based on |params|.
3757
Hiroki Nakagawa4ed61282021-06-18 05:37:233758 bool is_view_source_mode = entry->IsViewSourceMode();
3759 DCHECK_EQ(is_view_source_mode, virtual_url.SchemeIs(kViewSourceScheme));
Charlie Harrison8c113a32019-01-07 16:08:293760
Antonio Sartori6984c742021-08-26 08:03:413761 blink::NavigationDownloadPolicy download_policy = params.download_policy;
Hiroki Nakagawa4ed61282021-06-18 05:37:233762 // Update |download_policy| if the virtual URL is view-source.
Charlie Harrison8c113a32019-01-07 16:08:293763 if (is_view_source_mode)
Yeunjoo Choi3df791a2021-02-17 07:07:253764 download_policy.SetDisallowed(blink::NavigationDownloadType::kViewSource);
Charlie Harrison8c113a32019-01-07 16:08:293765
Minggang Wangb9f3fa92021-07-01 15:30:313766 blink::mojom::CommonNavigationParamsPtr common_params =
3767 blink::mojom::CommonNavigationParams::New(
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513768 url_to_load, params.initiator_origin,
3769 blink::mojom::Referrer::New(params.referrer.url,
3770 params.referrer.policy),
Scott Violetcf6ea7e2021-06-09 21:09:213771 params.transition_type, navigation_type, download_policy,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513772 should_replace_current_entry, params.base_url_for_data_url,
Tsuyoshi Horo167ca6432022-03-09 05:16:393773 navigation_start_time,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513774 params.load_type == LOAD_TYPE_HTTP_POST ? "POST" : "GET",
Antonio Sartori2f763d9d2021-04-21 10:04:143775 params.post_data, std::move(source_location),
arthursonzogniaf7c62c52020-02-12 10:49:413776 params.started_from_context_menu, has_user_gesture,
Antonio Sartori636adba2021-03-09 12:15:273777 false /* has_text_fragment_token */,
3778 network::mojom::CSPDisposition::CHECK, std::vector<int>(),
3779 params.href_translate,
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513780 false /* is_history_navigation_in_new_child_frame */,
Nan Lind91c8152021-10-21 16:22:373781 params.input_start, network::mojom::RequestDestination::kEmpty);
Camille Lamy5193caa2018-10-12 11:59:423782
Minggang Wangb9f3fa92021-07-01 15:30:313783 blink::mojom::CommitNavigationParamsPtr commit_params =
3784 blink::mojom::CommitNavigationParams::New(
Rakina Zata Amnic7367852022-11-07 17:10:403785 absl::nullopt,
Antonio Sartori3e8de6d2021-07-26 10:28:413786 // The correct storage key will be computed before committing the
3787 // navigation.
Pâris Meuleman4d97a702022-07-05 10:42:003788 blink::StorageKey(), override_user_agent, params.redirect_chain,
Lucas Furukawa Gadani81e294b2019-08-29 16:26:323789 std::vector<network::mojom::URLResponseHeadPtr>(),
jongdeok.kim5de823b32022-06-14 04:37:503790 std::vector<net::RedirectInfo>(), params.post_content_type,
3791 common_params->url, common_params->method,
3792 params.can_load_local_resources,
Minggang Wangb9f3fa92021-07-01 15:30:313793 frame_entry->page_state().ToEncodedData(), entry->GetUniqueID(),
Yoav Weiss8c573952022-11-17 17:35:133794 entry->GetSubframeUniqueNames(node),
3795 /*intended_as_new_entry=*/true,
3796 /*pending_history_list_offset=*/-1,
Lucas Furukawa Gadania9c45682019-07-31 22:05:143797 params.should_clear_history_list ? -1 : GetLastCommittedEntryIndex(),
3798 params.should_clear_history_list ? 0 : GetEntryCount(),
Yoav Weiss8c573952022-11-17 17:35:133799 /*was_discarded=*/false, is_view_source_mode,
Minggang Wangb9f3fa92021-07-01 15:30:313800 params.should_clear_history_list,
3801 blink::mojom::NavigationTiming::New(),
Minggang Wangf59db47b2021-06-16 01:56:223802 blink::mojom::WasActivatedOption::kUnknown,
Yoav Weiss8c573952022-11-17 17:35:133803 /*navigation_token=*/base::UnguessableToken::Create(),
Minggang Wang7ee0c742021-06-16 16:16:513804 std::vector<blink::mojom::PrefetchedSignedExchangeInfoPtr>(),
Xiaohan Wang7f8052e02022-01-14 18:44:283805#if BUILDFLAG(IS_ANDROID)
Yoav Weiss8c573952022-11-17 17:35:133806 /*data_url_as_string=*/std::string(),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143807#endif
Yoav Weiss8c573952022-11-17 17:35:133808 /*is_browser_initiated=*/!params.is_renderer_initiated,
3809 /*web_bundle_physical_url=*/GURL(),
3810 /*base_url_override_for_web_bundle=*/GURL(),
3811 /*document_ukm_source_id=*/ukm::kInvalidSourceId,
Jiewei Qian0406fc02020-03-09 06:02:073812 node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133813 /*force_enabled_origin_trials=*/std::vector<std::string>(),
3814 /*origin_agent_cluster=*/false,
3815 /*origin_agent_cluster_left_as_default=*/true,
3816 /*enabled_client_hints=*/
3817 std::vector<network::mojom::WebClientHintsType>(),
3818 /*is_cross_browsing_instance=*/false, /*old_page_info=*/nullptr,
3819 /*http_response_code=*/-1,
Domenic Denicolacd30f5f82022-03-16 21:48:013820 blink::mojom::NavigationApiHistoryEntryArrays::New(),
Yoav Weiss8c573952022-11-17 17:35:133821 /*early_hints_preloaded_resources=*/std::vector<GURL>(),
3822 /*ad_auction_components=*/absl::nullopt,
shivanigithubc7b97ca2022-04-05 19:41:403823 /*fenced_frame_reporting_metadata=*/nullptr,
Clark DuVall8ee487a22021-11-10 02:25:583824 // This timestamp will be populated when the commit IPC is sent.
Yoav Weiss8c573952022-11-17 17:35:133825 /*commit_sent=*/base::TimeTicks(), /*srcdoc_value=*/std::string(),
3826 /*fallback_srcdoc_baseurl_value=*/GURL(),
3827 /*should_load_data_url=*/false,
Victor Tan10d93aca2022-08-12 16:46:283828 /*ancestor_or_self_has_cspee=*/node->AncestorOrSelfHasCSPEE(),
Yoav Weiss8c573952022-11-17 17:35:133829 /*reduced_accept_language=*/std::string(),
William Liu2c825472022-10-31 12:01:443830 /*navigation_delivery_type=*/
Khushal Sagar7b26135c62022-11-08 20:25:423831 network::mojom::NavigationDeliveryType::kDefault,
Yoav Weiss8c573952022-11-17 17:35:133832 /*view_transition_state=*/absl::nullopt,
sbinglera07ae732022-12-02 20:49:053833 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
3834 /*modified_runtime_features=*/
3835 base::flat_map<::blink::mojom::RuntimeFeatureState, bool>());
Xiaohan Wang7f8052e02022-01-14 18:44:283836#if BUILDFLAG(IS_ANDROID)
Camille Lamy5193caa2018-10-12 11:59:423837 if (ValidateDataURLAsString(params.data_url_as_string)) {
Lucas Furukawa Gadania9c45682019-07-31 22:05:143838 commit_params->data_url_as_string = params.data_url_as_string->data();
Camille Lamy5193caa2018-10-12 11:59:423839 }
3840#endif
3841
Lucas Furukawa Gadania9c45682019-07-31 22:05:143842 commit_params->was_activated = params.was_activated;
Camille Lamy5193caa2018-10-12 11:59:423843
Camille Lamy5193caa2018-10-12 11:59:423844 // extra_headers in params are \n separated; NavigationRequests want \r\n.
3845 std::string extra_headers_crlf;
3846 base::ReplaceChars(params.extra_headers, "\n", "\r\n", &extra_headers_crlf);
Yao Xiaodc5ed102019-06-04 19:19:093847
3848 auto navigation_request = NavigationRequest::CreateBrowserInitiated(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143849 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:083850 !params.is_renderer_initiated, params.was_opener_suppressed,
Antonio Sartori9a82f6f32020-12-14 09:22:453851 params.initiator_frame_token.has_value()
3852 ? &(params.initiator_frame_token.value())
3853 : nullptr,
3854 params.initiator_process_id, extra_headers_crlf, frame_entry, entry,
jongdeok.kim5de823b32022-06-14 04:37:503855 params.is_form_submission,
John Delaney50425f82020-04-07 16:26:213856 params.navigation_ui_data ? params.navigation_ui_data->Clone() : nullptr,
Garrett Tanzer47852462022-07-20 18:16:413857 params.impression, params.is_pdf,
3858 is_embedder_initiated_fenced_frame_navigation);
Yao Xiaodc5ed102019-06-04 19:19:093859 navigation_request->set_from_download_cross_origin_redirect(
3860 params.from_download_cross_origin_redirect);
W. James MacLean00568d72022-02-24 19:36:553861 navigation_request->set_force_new_browsing_instance(
3862 params.force_new_browsing_instance);
Yao Xiaodc5ed102019-06-04 19:19:093863 return navigation_request;
Camille Lamy5193caa2018-10-12 11:59:423864}
3865
3866std::unique_ptr<NavigationRequest>
3867NavigationControllerImpl::CreateNavigationRequestFromEntry(
clamyea99ea12018-05-28 13:54:233868 FrameTreeNode* frame_tree_node,
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573869 NavigationEntryImpl* entry,
clamyea99ea12018-05-28 13:54:233870 FrameNavigationEntry* frame_entry,
3871 ReloadType reload_type,
3872 bool is_same_document_history_load,
Nate Chapin45f620582021-09-30 17:45:433873 bool is_history_navigation_in_new_child_frame,
Yoav Weiss8c573952022-11-17 17:35:133874 bool is_browser_initiated,
3875 absl::optional<blink::scheduler::TaskAttributionId>
3876 soft_navigation_heuristics_task_id) {
Alex Moshchuk47d1a4bd2020-06-01 22:15:343877 DCHECK(frame_entry);
clamyea99ea12018-05-28 13:54:233878 GURL dest_url = frame_entry->url();
Rakina Zata Amnif297a802022-01-18 03:53:433879 // We should never navigate to an existing initial NavigationEntry that is the
3880 // initial NavigationEntry for the initial empty document that hasn't been
3881 // overridden by the synchronous about:blank commit, to preserve previous
3882 // behavior where trying to reload when the main frame is on the initial empty
3883 // document won't result in a navigation.
3884 // See also https://crbug.com/1277414.
3885 DCHECK(!entry->IsInitialEntryNotForSynchronousAboutBlank());
Nasko Oskov03912102019-01-11 00:21:323886
clamyea99ea12018-05-28 13:54:233887 Referrer dest_referrer = frame_entry->referrer();
Ryan Sturmc4da1992018-07-17 16:59:013888 if (reload_type == ReloadType::ORIGINAL_REQUEST_URL &&
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573889 entry->GetOriginalRequestURL().is_valid() && !entry->GetHasPostData()) {
clamyea99ea12018-05-28 13:54:233890 // We may have been redirected when navigating to the current URL.
3891 // Use the URL the user originally intended to visit as signaled by the
3892 // ReloadType, if it's valid and if a POST wasn't involved; the latter
Ryan Sturmc4da1992018-07-17 16:59:013893 // case avoids issues with sending data to the wrong page.
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573894 dest_url = entry->GetOriginalRequestURL();
clamyea99ea12018-05-28 13:54:233895 dest_referrer = Referrer();
clamyea99ea12018-05-28 13:54:233896 }
3897
Ehsan Karamad44fc72112019-02-26 18:15:473898 if (frame_tree_node->render_manager()->is_attaching_inner_delegate()) {
3899 // Avoid starting any new navigations since this node is now preparing for
3900 // attaching an inner delegate.
3901 return nullptr;
Ehsan Karamaddd9a4142018-12-04 20:38:203902 }
3903
Ian Vollick1c6dd3e2022-04-13 02:06:263904 if (!IsValidURLForNavigation(frame_tree_node->IsOutermostMainFrame(),
Lucas Furukawa Gadani5553a1582019-01-08 18:55:573905 entry->GetVirtualURL(), dest_url)) {
clamyea99ea12018-05-28 13:54:233906 return nullptr;
3907 }
3908
clamyea99ea12018-05-28 13:54:233909 // This will be used to set the Navigation Timing API navigationStart
3910 // parameter for browser navigations in new tabs (intents, tabs opened through
3911 // "Open link in new tab"). If the navigation must wait on the current
3912 // RenderFrameHost to execute its BeforeUnload event, the navigation start
3913 // will be updated when the BeforeUnload ack is received.
3914 base::TimeTicks navigation_start = base::TimeTicks::Now();
clamyea99ea12018-05-28 13:54:233915
danakjd83d706d2020-11-25 22:11:123916 // Look for a pending commit that is to another document in this
3917 // FrameTreeNode. If one exists, then the last committed URL will not be the
3918 // current URL by the time this navigation commits.
3919 bool has_pending_cross_document_commit =
3920 frame_tree_node->render_manager()
3921 ->HasPendingCommitForCrossDocumentNavigation();
danakjb952ef12021-01-14 19:58:493922 bool is_currently_error_page =
Miyoung Shina2dd6a42021-10-07 12:19:213923 frame_tree_node->current_frame_host()->IsErrorDocument();
danakjd83d706d2020-11-25 22:11:123924
Minggang Wangb9f3fa92021-07-01 15:30:313925 blink::mojom::NavigationType navigation_type = GetNavigationType(
danakjd83d706d2020-11-25 22:11:123926 /*old_url=*/frame_tree_node->current_url(),
3927 /*new_url=*/dest_url, reload_type, entry, *frame_entry,
danakjb952ef12021-01-14 19:58:493928 has_pending_cross_document_commit, is_currently_error_page,
Garrett Tanzer405f3402022-07-21 20:12:493929 is_same_document_history_load,
Garrett Tanzer267c2b82022-07-26 16:53:133930 /*is_embedder_initiated_fenced_frame_navigation=*/false,
Garrett Tanzer405f3402022-07-21 20:12:493931 /*is_unfenced_top_navigation=*/false);
Camille Lamy5193caa2018-10-12 11:59:423932
3933 // A form submission may happen here if the navigation is a
3934 // back/forward/reload navigation that does a form resubmission.
3935 scoped_refptr<network::ResourceRequestBody> request_body;
3936 std::string post_content_type;
jongdeok.kim5de823b32022-06-14 04:37:503937 // TODO(https://crbug.com/931209) Store |is_form_submission| in the history
3938 // entry. This way, it could be directly retrieved here. Right now, it is only
3939 // partially recovered when request.method == "POST" and request.body exists.
3940 bool is_form_submission = false;
Camille Lamy5193caa2018-10-12 11:59:423941 if (frame_entry->method() == "POST") {
3942 request_body = frame_entry->GetPostData(&post_content_type);
3943 // Might have a LF at end.
Peter Kastingb53b81912021-04-28 19:23:303944 post_content_type = std::string(
3945 base::TrimWhitespaceASCII(post_content_type, base::TRIM_ALL));
jongdeok.kim5de823b32022-06-14 04:37:503946 is_form_submission = !!request_body;
Camille Lamy5193caa2018-10-12 11:59:423947 }
3948
3949 // Create the NavigationParams based on |entry| and |frame_entry|.
Minggang Wangb9f3fa92021-07-01 15:30:313950 blink::mojom::CommonNavigationParamsPtr common_params =
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513951 entry->ConstructCommonNavigationParams(
3952 *frame_entry, request_body, dest_url,
3953 blink::mojom::Referrer::New(dest_referrer.url, dest_referrer.policy),
Tarun Bansalbcd62c82022-01-18 17:27:383954 navigation_type, navigation_start,
Charlie Hu5ffc0152019-12-06 15:59:533955 base::TimeTicks() /* input_start */);
Lucas Furukawa Gadanief8290a2019-07-29 20:27:513956 common_params->is_history_navigation_in_new_child_frame =
Arthur Hemerybee4a752019-05-29 10:50:553957 is_history_navigation_in_new_child_frame;
Camille Lamy5193caa2018-10-12 11:59:423958
3959 // TODO(clamy): |intended_as_new_entry| below should always be false once
3960 // Reload no longer leads to this being called for a pending NavigationEntry
3961 // of index -1.
Minggang Wangb9f3fa92021-07-01 15:30:313962 blink::mojom::CommitNavigationParamsPtr commit_params =
Lucas Furukawa Gadania9c45682019-07-31 22:05:143963 entry->ConstructCommitNavigationParams(
Rakina Zata Amnic7367852022-11-07 17:10:403964 *frame_entry, common_params->url, common_params->method,
3965 entry->GetSubframeUniqueNames(frame_tree_node),
Lucas Furukawa Gadania9c45682019-07-31 22:05:143966 GetPendingEntryIndex() == -1 /* intended_as_new_entry */,
Charlie Hu5ffc0152019-12-06 15:59:533967 GetIndexOfEntry(entry), GetLastCommittedEntryIndex(), GetEntryCount(),
Liam Bradyd2a41e152022-07-19 13:58:483968 frame_tree_node->pending_frame_policy(),
Yoav Weiss8c573952022-11-17 17:35:133969 frame_tree_node->AncestorOrSelfHasCSPEE(),
3970 soft_navigation_heuristics_task_id);
Lucas Furukawa Gadania9c45682019-07-31 22:05:143971 commit_params->post_content_type = post_content_type;
Camille Lamy5193caa2018-10-12 11:59:423972
W. James MacLeanb7d6092682022-10-05 15:23:263973 if (common_params->url.IsAboutSrcdoc()) {
3974 // TODO(wjmaclean): initialize this in NavigationRequest's constructor
3975 // instead.
W. James MacLean81b8d01f2022-01-25 20:50:593976 commit_params->srcdoc_value = frame_tree_node->srcdoc_value();
W. James MacLeanb7d6092682022-10-05 15:23:263977 }
clamyea99ea12018-05-28 13:54:233978 return NavigationRequest::CreateBrowserInitiated(
Lucas Furukawa Gadania9c45682019-07-31 22:05:143979 frame_tree_node, std::move(common_params), std::move(commit_params),
Nate Chapin45f620582021-09-30 17:45:433980 is_browser_initiated, false /* was_opener_suppressed */,
Takashi Toyoshimae87b7be2021-01-22 11:51:083981 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:453982 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
jongdeok.kim5de823b32022-06-14 04:37:503983 entry->extra_headers(), frame_entry, entry, is_form_submission,
Daniel Hosseinianf0fbfb42021-09-08 02:20:473984 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
3985 false /* is_pdf */);
clamyea99ea12018-05-28 13:54:233986}
3987
[email protected]d202a7c2012-01-04 07:53:473988void NavigationControllerImpl::NotifyNavigationEntryCommitted(
[email protected]8ff00d72012-10-23 19:12:213989 LoadCommittedDetails* details) {
[email protected]6286a3792013-10-09 04:03:273990 details->entry = GetLastCommittedEntry();
[email protected]df1af242009-05-01 00:11:403991
Takashi Toyoshimaea534ef22021-07-21 03:27:593992 // We need to notify the ssl_manager_ before the WebContents so the
[email protected]df1af242009-05-01 00:11:403993 // location bar will have up-to-date information about the security style
3994 // when it wants to draw. See http://crbug.com/11157
[email protected]b0f724c2013-09-05 04:21:133995 ssl_manager_.DidCommitProvisionalLoad(*details);
[email protected]df1af242009-05-01 00:11:403996
Abhijeet Kandalkar3dc6e602022-11-09 05:08:373997 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]ec6c05f2013-10-23 18:41:573998 delegate_->NotifyNavigationEntryCommitted(*details);
[email protected]cbb1ef592013-06-05 19:49:463999
[email protected]b0f724c2013-09-05 04:21:134000 // TODO(avi): Remove. http://crbug.com/170921
4001 NotificationDetails notification_details =
4002 Details<LoadCommittedDetails>(details);
Aran Gilman37d11632019-10-08 23:07:154003 NotificationService::current()->Notify(NOTIFICATION_NAV_ENTRY_COMMITTED,
4004 Source<NavigationController>(this),
4005 notification_details);
initial.commit09911bf2008-07-26 23:55:294006}
4007
initial.commit09911bf2008-07-26 23:55:294008// static
[email protected]d202a7c2012-01-04 07:53:474009size_t NavigationControllerImpl::max_entry_count() {
[email protected]9b51970d2011-12-09 23:10:234010 if (max_entry_count_for_testing_ != kMaxEntryCountForTestingNotSet)
Aran Gilman37d11632019-10-08 23:07:154011 return max_entry_count_for_testing_;
Miyoung Shin1c565c912021-03-17 12:11:214012 return blink::kMaxSessionHistoryEntries;
[email protected]9b51970d2011-12-09 23:10:234013}
4014
[email protected]d202a7c2012-01-04 07:53:474015void NavigationControllerImpl::SetActive(bool is_active) {
[email protected]ee613922009-09-02 20:38:224016 if (is_active && needs_reload_)
4017 LoadIfNecessary();
initial.commit09911bf2008-07-26 23:55:294018}
4019
[email protected]d202a7c2012-01-04 07:53:474020void NavigationControllerImpl::LoadIfNecessary() {
Rakina Zata Amnid605d462022-06-01 10:17:034021 SCOPED_CRASH_KEY_BOOL("nav_reentrancy_caller1", "LoadIf_pending",
4022 !!pending_entry_);
initial.commit09911bf2008-07-26 23:55:294023 if (!needs_reload_)
4024 return;
4025
Bo Liucdfa4b12018-11-06 00:21:444026 UMA_HISTOGRAM_ENUMERATION("Navigation.LoadIfNecessaryType",
4027 needs_reload_type_);
4028
initial.commit09911bf2008-07-26 23:55:294029 // Calling Reload() results in ignoring state, and not loading.
4030 // Explicitly use NavigateToPendingEntry so that the renderer uses the
4031 // cached state.
avicc872d7242015-08-19 21:26:344032 if (pending_entry_) {
Yoav Weiss8c573952022-11-17 17:35:134033 NavigateToExistingPendingEntry(
4034 ReloadType::NONE,
4035 /*initiator_rfh=*/nullptr,
4036 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4037 /*navigation_api_key=*/nullptr);
Rakina Zata Amnie2d31312022-11-18 03:38:454038 } else if (!GetLastCommittedEntry()
Rakina Zata Amnif297a802022-01-18 03:53:434039 ->IsInitialEntryNotForSynchronousAboutBlank()) {
arthursonzogni5c4c202d2017-04-25 23:41:274040 pending_entry_ = entries_[last_committed_entry_index_].get();
avicc872d7242015-08-19 21:26:344041 pending_entry_index_ = last_committed_entry_index_;
Yoav Weiss8c573952022-11-17 17:35:134042 NavigateToExistingPendingEntry(
4043 ReloadType::NONE,
4044 /*initiator_rfh=*/nullptr,
4045 /*soft_navigation_heuristics_task_id=*/absl::nullopt,
4046 /*navigation_api_key=*/nullptr);
avicc872d7242015-08-19 21:26:344047 } else {
Rakina Zata Amnif297a802022-01-18 03:53:434048 // We should never navigate to an existing initial NavigationEntry that is
4049 // the initial NavigationEntry for the initial empty document that hasn't
4050 // been overridden by the synchronous about:blank commit, to preserve
4051 // legacy behavior where trying to reload when the main frame is on the
4052 // initial empty document won't result in a navigation. See also
4053 // https://crbug.com/1277414. If there is something to reload, the
4054 // successful reload will clear the |needs_reload_| flag. Otherwise, just do
4055 // it here.
avicc872d7242015-08-19 21:26:344056 needs_reload_ = false;
4057 }
initial.commit09911bf2008-07-26 23:55:294058}
4059
Kevin McNeeccca6172021-10-19 17:11:144060base::WeakPtr<NavigationHandle>
4061NavigationControllerImpl::LoadPostCommitErrorPage(
Carlos IL42b416592019-10-07 23:10:364062 RenderFrameHost* render_frame_host,
4063 const GURL& url,
4064 const std::string& error_page_html,
4065 net::Error error) {
Rakina Zata Amni919b7922020-12-11 09:03:134066 RenderFrameHostImpl* rfhi =
4067 static_cast<RenderFrameHostImpl*>(render_frame_host);
Sreeja Kamishettydb8e2892021-03-10 09:30:584068
4069 // Only active documents can load post-commit error pages:
4070 // - If the document is in pending deletion, the browser already committed to
4071 // destroying this RenderFrameHost so ignore loading the error page.
4072 // - If the document is in back-forward cache, it's not allowed to navigate as
4073 // it should remain frozen. Ignore the request and evict the document from
4074 // back-forward cache.
4075 // - If the document is prerendering, it can navigate but when loading error
4076 // pages, cancel prerendering.
Fergal Daly1336ac642021-09-14 15:13:114077 if (rfhi->IsInactiveAndDisallowActivation(
4078 DisallowActivationReasonId::kLoadPostCommitErrorPage)) {
Kevin McNeeccca6172021-10-19 17:11:144079 return nullptr;
Fergal Daly1336ac642021-09-14 15:13:114080 }
Sreeja Kamishettydb8e2892021-03-10 09:30:584081
Rakina Zata Amni919b7922020-12-11 09:03:134082 FrameTreeNode* node = rfhi->frame_tree_node();
John Delaney131ad362019-08-08 21:57:414083
Minggang Wangb9f3fa92021-07-01 15:30:314084 blink::mojom::CommonNavigationParamsPtr common_params =
Minggang Wanga13c796e2021-07-02 05:54:434085 blink::CreateCommonNavigationParams();
Rakina Zata Amnid2da1542020-12-23 00:52:594086 // |url| might be empty, such as when LoadPostCommitErrorPage happens before
4087 // the frame actually committed (e.g. iframe with "src" set to a
4088 // slow-responding URL). We should rewrite the URL to about:blank in this
4089 // case, as the renderer will only think a page is an error page if it has a
4090 // non-empty unreachable URL.
Rakina Zata Amni919b7922020-12-11 09:03:134091 common_params->url = url.is_empty() ? GURL("about:blank") : url;
Minggang Wangb9f3fa92021-07-01 15:30:314092 blink::mojom::CommitNavigationParamsPtr commit_params =
Minggang Wanga13c796e2021-07-02 05:54:434093 blink::CreateCommitNavigationParams();
Antonio Sartori58591c892021-04-21 06:54:334094 commit_params->original_url = common_params->url;
John Delaney131ad362019-08-08 21:57:414095
arthursonzogni70ac7302020-05-28 08:49:054096 // Error pages have a fully permissive FramePolicy.
4097 // TODO(arthursonzogni): Consider providing the minimal capabilities to the
4098 // error pages.
4099 commit_params->frame_policy = blink::FramePolicy();
4100
John Delaney131ad362019-08-08 21:57:414101 std::unique_ptr<NavigationRequest> navigation_request =
4102 NavigationRequest::CreateBrowserInitiated(
4103 node, std::move(common_params), std::move(commit_params),
Takashi Toyoshimae87b7be2021-01-22 11:51:084104 true /* browser_initiated */, false /* was_opener_suppressed */,
Lingqi Chi82efa95e2020-12-29 05:31:194105 nullptr /* initiator_frame_token */,
Antonio Sartori9a82f6f32020-12-14 09:22:454106 ChildProcessHost::kInvalidUniqueID /* initiator_process_id */,
John Delaneyf43556d2020-05-04 23:19:064107 "" /* extra_headers */, nullptr /* frame_entry */,
jongdeok.kim5de823b32022-06-14 04:37:504108 nullptr /* entry */, false /* is_form_submission */,
Daniel Hosseinianf0fbfb42021-09-08 02:20:474109 nullptr /* navigation_ui_data */, absl::nullopt /* impression */,
4110 false /* is_pdf */);
Carlos IL42b416592019-10-07 23:10:364111 navigation_request->set_post_commit_error_page_html(error_page_html);
John Delaney131ad362019-08-08 21:57:414112 navigation_request->set_net_error(error);
4113 node->CreatedNavigationRequest(std::move(navigation_request));
4114 DCHECK(node->navigation_request());
Kevin McNeeccca6172021-10-19 17:11:144115
4116 // Calling BeginNavigation may destroy the NavigationRequest.
4117 base::WeakPtr<NavigationRequest> created_navigation_request(
4118 node->navigation_request()->GetWeakPtr());
John Delaney131ad362019-08-08 21:57:414119 node->navigation_request()->BeginNavigation();
Kevin McNeeccca6172021-10-19 17:11:144120 return created_navigation_request;
John Delaney131ad362019-08-08 21:57:414121}
4122
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574123void NavigationControllerImpl::NotifyEntryChanged(NavigationEntry* entry) {
[email protected]8ff00d72012-10-23 19:12:214124 EntryChangedDetails det;
[email protected]534e54b2008-08-13 15:40:094125 det.changed_entry = entry;
Aran Gilman37d11632019-10-08 23:07:154126 det.index = GetIndexOfEntry(NavigationEntryImpl::FromNavigationEntry(entry));
Sam McNally5c087a32017-08-25 01:46:144127 delegate_->NotifyNavigationEntryChanged(det);
initial.commit09911bf2008-07-26 23:55:294128}
4129
[email protected]d202a7c2012-01-04 07:53:474130void NavigationControllerImpl::FinishRestore(int selected_index,
[email protected]2ca1ea662012-10-04 02:26:364131 RestoreType type) {
Charlie Reis23c26da2022-01-29 00:57:474132 // TODO(https://crbug.com/1287624): Don't allow an index of -1, which would
4133 // represent a no-committed-entry state.
4134 DCHECK(selected_index >= -1 && selected_index < GetEntryCount());
[email protected]2ca1ea662012-10-04 02:26:364135 ConfigureEntriesForRestore(&entries_, type);
Charlie Reis23c26da2022-01-29 00:57:474136 // TODO(https://crbug.com/1287624): This will be pointing to the wrong entry
4137 // if `entries_` contains pre-existing entries from the NavigationController
4138 // before restore, which would not be removed and will be at the front of the
4139 // entries list, causing the index to be off by the amount of pre-existing
4140 // entries in the list. Fix this to point to the correct entry.
initial.commit09911bf2008-07-26 23:55:294141 last_committed_entry_index_ = selected_index;
initial.commit09911bf2008-07-26 23:55:294142}
[email protected]765b35502008-08-21 00:51:204143
arthursonzogni69a6a1b2019-09-17 09:23:004144void NavigationControllerImpl::DiscardNonCommittedEntries() {
Rakina Zata Amnia4e27222021-12-22 01:05:004145 DiscardNonCommittedEntriesWithCommitDetails(nullptr /* commit_details */);
4146}
4147
4148void NavigationControllerImpl::DiscardNonCommittedEntriesWithCommitDetails(
4149 LoadCommittedDetails* commit_details) {
Michael Thiessen9b14d512019-09-23 21:19:474150 // Avoid sending a notification if there is nothing to discard.
Michael Thiessenc5676d22019-09-25 22:32:104151 // TODO(mthiesse): Temporarily checking failed_pending_entry_id_ to help
4152 // diagnose https://bugs.chromium.org/p/chromium/issues/detail?id=1007570.
Carlos IL4dea8902020-05-26 15:14:294153 if (!pending_entry_ && failed_pending_entry_id_ == 0) {
Michael Thiessen9b14d512019-09-23 21:19:474154 return;
Michael Thiessenc5676d22019-09-25 22:32:104155 }
avi45a72532015-04-07 21:01:454156 DiscardPendingEntry(false);
Rakina Zata Amnidaa84f62022-02-17 00:55:314157
4158 if (!delegate_)
4159 return;
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374160 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_ALL);
[email protected]b12eb222013-09-10 00:11:484161}
4162
avi7c6f35e2015-05-08 17:52:384163int NavigationControllerImpl::GetEntryIndexWithUniqueID(
4164 int nav_entry_id) const {
4165 for (int i = static_cast<int>(entries_.size()) - 1; i >= 0; --i) {
4166 if (entries_[i]->GetUniqueID() == nav_entry_id)
4167 return i;
4168 }
4169 return -1;
4170}
4171
[email protected]d202a7c2012-01-04 07:53:474172void NavigationControllerImpl::InsertEntriesFrom(
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574173 NavigationControllerImpl* source,
[email protected]e1cd5452010-08-26 18:03:254174 int max_index) {
Lucas Furukawa Gadani5553a1582019-01-08 18:55:574175 DCHECK_LE(max_index, source->GetEntryCount());
Nate Chapin214a86a2021-06-21 20:35:574176 std::unique_ptr<NavigationEntryRestoreContextImpl> context =
4177 std::make_unique<NavigationEntryRestoreContextImpl>();
[email protected]e1cd5452010-08-26 18:03:254178 for (int i = 0; i < max_index; i++) {
Nate Chapin9f169072021-06-09 19:32:374179 // Normally, cloning a NavigationEntryImpl results in sharing
4180 // FrameNavigationEntries between the original and the clone. However, when
4181 // cloning from a different NavigationControllerImpl, we want to fork the
4182 // FrameNavigationEntries.
Nate Chapin9f169072021-06-09 19:32:374183 entries_.insert(entries_.begin() + i,
Nate Chapin214a86a2021-06-21 20:35:574184 source->entries_[i]->CloneWithoutSharing(context.get()));
[email protected]e1cd5452010-08-26 18:03:254185 }
Rakina Zata Amnie2d31312022-11-18 03:38:454186 DCHECK_GE(entries_.size(), 1u);
arthursonzogni5c4c202d2017-04-25 23:41:274187 DCHECK(pending_entry_index_ == -1 ||
4188 pending_entry_ == GetEntryAtIndex(pending_entry_index_));
[email protected]e1cd5452010-08-26 18:03:254189}
[email protected]c5b88d82012-10-06 17:03:334190
4191void NavigationControllerImpl::SetGetTimestampCallbackForTest(
Makoto Shimazud2aa2202019-10-09 13:57:184192 const base::RepeatingCallback<base::Time()>& get_timestamp_callback) {
[email protected]c5b88d82012-10-06 17:03:334193 get_timestamp_callback_ = get_timestamp_callback;
4194}
[email protected]8ff00d72012-10-23 19:12:214195
Shivani Sharmaffb32b82019-04-09 16:58:474196// History manipulation intervention:
4197void NavigationControllerImpl::SetShouldSkipOnBackForwardUIIfNeeded(
Shivani Sharmaffb32b82019-04-09 16:58:474198 bool replace_entry,
4199 bool previous_document_was_activated,
Alexander Timine3ec4192020-04-20 16:39:404200 bool is_renderer_initiated,
4201 ukm::SourceId previous_page_load_ukm_source_id) {
Shivani Sharma712d5d72019-04-16 21:56:454202 // Note that for a subframe, previous_document_was_activated is true if the
4203 // gesture happened in any subframe (propagated to main frame) or in the main
4204 // frame itself.
Shivani Sharmaffb32b82019-04-09 16:58:474205 if (replace_entry || previous_document_was_activated ||
shivanigithubcceeacf2020-03-06 20:00:274206 !is_renderer_initiated) {
Shivani Sharmaffb32b82019-04-09 16:58:474207 return;
4208 }
4209 if (last_committed_entry_index_ == -1)
4210 return;
4211
Shivani Sharmac4cc8922019-04-18 03:11:174212 SetSkippableForSameDocumentEntries(last_committed_entry_index_, true);
Shivani Sharmaffb32b82019-04-09 16:58:474213
Alexander Timine3ec4192020-04-20 16:39:404214 // Log UKM with the URL we are navigating away from.
4215 ukm::builders::HistoryManipulationIntervention(
4216 previous_page_load_ukm_source_id)
4217 .Record(ukm::UkmRecorder::Get());
Shivani Sharmaffb32b82019-04-09 16:58:474218}
4219
Shivani Sharmac4cc8922019-04-18 03:11:174220void NavigationControllerImpl::SetSkippableForSameDocumentEntries(
4221 int reference_index,
4222 bool skippable) {
4223 auto* reference_entry = GetEntryAtIndex(reference_index);
4224 reference_entry->set_should_skip_on_back_forward_ui(skippable);
4225
4226 int64_t document_sequence_number =
4227 reference_entry->root_node()->frame_entry->document_sequence_number();
4228 for (int index = 0; index < GetEntryCount(); index++) {
4229 auto* entry = GetEntryAtIndex(index);
4230 if (entry->root_node()->frame_entry->document_sequence_number() ==
4231 document_sequence_number) {
4232 entry->set_should_skip_on_back_forward_ui(skippable);
4233 }
4234 }
4235}
4236
arthursonzogni66f711c2019-10-08 14:40:364237std::unique_ptr<NavigationControllerImpl::PendingEntryRef>
4238NavigationControllerImpl::ReferencePendingEntry() {
4239 DCHECK(pending_entry_);
4240 auto pending_entry_ref =
4241 std::make_unique<PendingEntryRef>(weak_factory_.GetWeakPtr());
4242 pending_entry_refs_.insert(pending_entry_ref.get());
4243 return pending_entry_ref;
4244}
4245
4246void NavigationControllerImpl::PendingEntryRefDeleted(PendingEntryRef* ref) {
4247 // Ignore refs that don't correspond to the current pending entry.
4248 auto it = pending_entry_refs_.find(ref);
4249 if (it == pending_entry_refs_.end())
4250 return;
4251 pending_entry_refs_.erase(it);
4252
4253 if (!pending_entry_refs_.empty())
4254 return;
4255
4256 // The pending entry may be deleted before the last PendingEntryRef.
4257 if (!pending_entry_)
4258 return;
4259
4260 // We usually clear the pending entry when the matching NavigationRequest
4261 // fails, so that an arbitrary URL isn't left visible above a committed page.
4262 //
4263 // However, we do preserve the pending entry in some cases, such as on the
4264 // initial navigation of an unmodified blank tab. We also allow the delegate
4265 // to say when it's safe to leave aborted URLs in the omnibox, to let the
4266 // user edit the URL and try again. This may be useful in cases that the
4267 // committed page cannot be attacker-controlled. In these cases, we still
4268 // allow the view to clear the pending entry and typed URL if the user
4269 // requests (e.g., hitting Escape with focus in the address bar).
4270 //
4271 // Do not leave the pending entry visible if it has an invalid URL, since this
4272 // might be formatted in an unexpected or unsafe way.
4273 // TODO(creis): Block navigations to invalid URLs in https://crbug.com/850824.
arthursonzogni66f711c2019-10-08 14:40:364274 bool should_preserve_entry =
4275 (pending_entry_ == GetVisibleEntry()) &&
4276 pending_entry_->GetURL().is_valid() &&
4277 (IsUnmodifiedBlankTab() || delegate_->ShouldPreserveAbortedURLs());
4278 if (should_preserve_entry)
4279 return;
4280
4281 DiscardPendingEntry(true);
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374282 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
arthursonzogni66f711c2019-10-08 14:40:364283}
4284
Titouan Rigoudy6ec70402021-02-02 15:42:194285std::unique_ptr<PolicyContainerPolicies>
4286NavigationControllerImpl::ComputePolicyContainerPoliciesForFrameEntry(
Antonio Sartori78a749f2020-11-30 12:03:394287 RenderFrameHostImpl* rfh,
4288 bool is_same_document,
Rakina Zata Amniafd3c6582021-11-30 06:19:174289 const GURL& url) {
Antonio Sartori78a749f2020-11-30 12:03:394290 if (is_same_document) {
Rakina Zata Amnie2d31312022-11-18 03:38:454291 DCHECK(GetLastCommittedEntry());
Antonio Sartori78a749f2020-11-30 12:03:394292 FrameNavigationEntry* previous_frame_entry =
4293 GetLastCommittedEntry()->GetFrameEntry(rfh->frame_tree_node());
4294
4295 // TODO(https://crbug.com/608402): Remove this nullptr check when we can
4296 // ensure we always have a FrameNavigationEntry here.
4297 if (!previous_frame_entry)
4298 return nullptr;
4299
Titouan Rigoudy6ec70402021-02-02 15:42:194300 const PolicyContainerPolicies* previous_policies =
4301 previous_frame_entry->policy_container_policies();
Antonio Sartori78a749f2020-11-30 12:03:394302
Titouan Rigoudy6ec70402021-02-02 15:42:194303 if (!previous_policies)
Antonio Sartori78a749f2020-11-30 12:03:394304 return nullptr;
4305
4306 // Make a copy of the policy container for the new FrameNavigationEntry.
Titouan Rigoudy72f892d2022-05-02 18:21:234307 return previous_policies->ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394308 }
4309
Titouan Rigoudy72f892d2022-05-02 18:21:234310 return rfh->policy_container_host()->policies().ClonePtr();
Antonio Sartori78a749f2020-11-30 12:03:394311}
4312
Hayato Ito2c8c08d02021-06-23 03:38:434313void NavigationControllerImpl::BroadcastHistoryOffsetAndLength() {
Carlos Caballeroede6f8c2021-01-28 11:01:504314 OPTIONAL_TRACE_EVENT2(
Hayato Ito2c8c08d02021-06-23 03:38:434315 "content", "NavigationControllerImpl::BroadcastHistoryOffsetAndLength",
4316 "history_offset", GetLastCommittedEntryIndex(), "history_length",
4317 GetEntryCount());
Carlos Caballeroede6f8c2021-01-28 11:01:504318
4319 auto callback = base::BindRepeating(
4320 [](int history_offset, int history_length, RenderViewHostImpl* rvh) {
4321 if (auto& broadcast = rvh->GetAssociatedPageBroadcast()) {
4322 broadcast->SetHistoryOffsetAndLength(history_offset, history_length);
4323 }
4324 },
Hayato Ito2c8c08d02021-06-23 03:38:434325 GetLastCommittedEntryIndex(), GetEntryCount());
Ali Hijazid87307d2022-11-07 20:15:034326 frame_tree_->root()->render_manager()->ExecutePageBroadcastMethod(callback);
Carlos Caballeroede6f8c2021-01-28 11:01:504327}
4328
4329void NavigationControllerImpl::DidAccessInitialMainDocument() {
4330 // We may have left a failed browser-initiated navigation in the address bar
4331 // to let the user edit it and try again. Clear it now that content might
4332 // show up underneath it.
Ali Hijazid87307d2022-11-07 20:15:034333 if (!frame_tree_->IsLoadingIncludingInnerFrameTrees() && GetPendingEntry())
Carlos Caballeroede6f8c2021-01-28 11:01:504334 DiscardPendingEntry(false);
4335
4336 // Update the URL display.
Abhijeet Kandalkar3dc6e602022-11-09 05:08:374337 delegate_->NotifyNavigationStateChangedFromController(INVALIDATE_TYPE_URL);
Carlos Caballeroede6f8c2021-01-28 11:01:504338}
4339
4340void NavigationControllerImpl::UpdateStateForFrame(
4341 RenderFrameHostImpl* rfhi,
4342 const blink::PageState& page_state) {
Alexander Timinf785f342021-03-18 00:00:564343 OPTIONAL_TRACE_EVENT1("content",
4344 "NavigationControllerImpl::UpdateStateForFrame",
4345 "render_frame_host", rfhi);
Carlos Caballeroede6f8c2021-01-28 11:01:504346 // The state update affects the last NavigationEntry associated with the given
4347 // |render_frame_host|. This may not be the last committed NavigationEntry (as
4348 // in the case of an UpdateState from a frame being swapped out). We track
4349 // which entry this is in the RenderFrameHost's nav_entry_id.
4350 NavigationEntryImpl* entry = GetEntryWithUniqueID(rfhi->nav_entry_id());
4351 if (!entry)
4352 return;
4353
4354 FrameNavigationEntry* frame_entry =
4355 entry->GetFrameEntry(rfhi->frame_tree_node());
4356 if (!frame_entry)
4357 return;
4358
4359 // The SiteInstance might not match if we do a cross-process navigation with
4360 // replacement (e.g., auto-subframe), in which case the swap out of the old
4361 // RenderFrameHost runs in the background after the old FrameNavigationEntry
4362 // has already been replaced and destroyed.
4363 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
4364 return;
4365
4366 if (page_state == frame_entry->page_state())
4367 return; // Nothing to update.
4368
4369 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
4370
4371 // The document_sequence_number and item_sequence_number recorded in the
4372 // FrameNavigationEntry should not differ from the one coming with the update,
4373 // since it must come from the same document. Do not update it if a difference
4374 // is detected, as this indicates that |frame_entry| is not the correct one.
4375 blink::ExplodedPageState exploded_state;
4376 if (!blink::DecodePageState(page_state.ToEncodedData(), &exploded_state))
4377 return;
4378
4379 if (exploded_state.top.document_sequence_number !=
4380 frame_entry->document_sequence_number() ||
4381 exploded_state.top.item_sequence_number !=
4382 frame_entry->item_sequence_number()) {
4383 return;
4384 }
4385
4386 frame_entry->SetPageState(page_state);
4387 NotifyEntryChanged(entry);
4388}
4389
Domenic Denicolacd30f5f82022-03-16 21:48:014390std::vector<blink::mojom::NavigationApiHistoryEntryPtr>
4391NavigationControllerImpl::PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574392 Direction direction,
4393 int entry_index,
4394 const url::Origin& pending_origin,
4395 FrameTreeNode* node,
4396 SiteInstance* site_instance,
Nate Chapin63db0d12022-01-20 22:03:304397 int64_t pending_item_sequence_number,
4398 int64_t pending_document_sequence_number) {
Domenic Denicolacd30f5f82022-03-16 21:48:014399 std::vector<blink::mojom::NavigationApiHistoryEntryPtr> entries;
Rakina Zata Amnie2d31312022-11-18 03:38:454400 if (GetLastCommittedEntry()->IsInitialEntry()) {
Rakina Zata Amniafd3c6582021-11-30 06:19:174401 // Don't process the initial entry.
4402 DCHECK_EQ(GetEntryCount(), 1);
4403 return entries;
4404 }
Nate Chapind1fe3612021-04-16 20:45:574405 int offset = direction == Direction::kForward ? 1 : -1;
Nate Chapin63db0d12022-01-20 22:03:304406 int64_t previous_item_sequence_number = pending_item_sequence_number;
Nate Chapind1fe3612021-04-16 20:45:574407 for (int i = entry_index + offset; i >= 0 && i < GetEntryCount();
4408 i += offset) {
4409 FrameNavigationEntry* frame_entry = GetEntryAtIndex(i)->GetFrameEntry(node);
Nate Chapindedfa642022-01-28 23:59:414410 if (!frame_entry)
Nate Chapind1fe3612021-04-16 20:45:574411 break;
Domenic Denicolacd30f5f82022-03-16 21:48:014412 // An entry should only appear in the navigation API entries if it is for
4413 // the same origin as the document being committed. Check the committed
4414 // origin, or if that is not available (during restore), check against the
4415 // FNE's url.
Nate Chapindedfa642022-01-28 23:59:414416 url::Origin frame_entry_origin =
4417 frame_entry->committed_origin().value_or(url::Origin::Resolve(
4418 frame_entry->url(),
4419 frame_entry->initiator_origin().value_or(url::Origin())));
4420 if (!pending_origin.IsSameOriginWith(frame_entry_origin))
Nate Chapind1fe3612021-04-16 20:45:574421 break;
4422 if (previous_item_sequence_number == frame_entry->item_sequence_number())
4423 continue;
4424 blink::ExplodedPageState exploded_page_state;
4425 if (blink::DecodePageState(frame_entry->page_state().ToEncodedData(),
4426 &exploded_page_state)) {
4427 blink::ExplodedFrameState frame_state = exploded_page_state.top;
Nate Chapin63db0d12022-01-20 22:03:304428
4429 // If the document represented by this FNE hid its full url from appearing
4430 // in a referrer via a "no-referrer" or "origin" referrer policy, censor
Domenic Denicolacd30f5f82022-03-16 21:48:014431 // the url in the navigation API as well (unless we're navigating to that
Nate Chapin63db0d12022-01-20 22:03:304432 // document).
4433 std::u16string url;
4434 if (pending_document_sequence_number ==
4435 frame_entry->document_sequence_number() ||
Domenic Denicolacc094fb2022-03-16 23:40:574436 !frame_entry->protect_url_in_navigation_api()) {
Nate Chapin63db0d12022-01-20 22:03:304437 url = frame_state.url_string.value_or(std::u16string());
4438 }
4439
Domenic Denicolacd30f5f82022-03-16 21:48:014440 blink::mojom::NavigationApiHistoryEntryPtr entry =
4441 blink::mojom::NavigationApiHistoryEntry::New(
Domenic Denicolacc094fb2022-03-16 23:40:574442 frame_state.navigation_api_key.value_or(std::u16string()),
4443 frame_state.navigation_api_id.value_or(std::u16string()), url,
Nate Chapinab5c3a712021-11-18 22:17:094444 frame_state.item_sequence_number,
4445 frame_state.document_sequence_number,
Nate Chapin393cbde12022-05-27 00:36:304446 frame_state.navigation_api_state);
Rakina Zata Amniafd3c6582021-11-30 06:19:174447
Nate Chapin63db0d12022-01-20 22:03:304448 DCHECK(entry->url.empty() ||
4449 pending_origin.CanBeDerivedFrom(GURL(entry->url)));
Nate Chapind1fe3612021-04-16 20:45:574450 entries.push_back(std::move(entry));
4451 previous_item_sequence_number = frame_entry->item_sequence_number();
4452 }
4453 }
4454 // If |entries| was constructed by iterating backwards from
4455 // |entry_index|, it's latest-at-the-front, but the renderer will want it
4456 // earliest-at-the-front. Reverse it.
4457 if (direction == Direction::kBack)
4458 std::reverse(entries.begin(), entries.end());
4459 return entries;
4460}
4461
Domenic Denicolacd30f5f82022-03-16 21:48:014462blink::mojom::NavigationApiHistoryEntryArraysPtr
4463NavigationControllerImpl::GetNavigationApiHistoryEntryVectors(
Nate Chapin97d2f542022-02-18 01:34:554464 FrameTreeNode* node,
Nate Chapind1fe3612021-04-16 20:45:574465 NavigationRequest* request) {
Rakina Zata Amnic7367852022-11-07 17:10:404466 url::Origin pending_origin = request
Lukasz Anforowicz435e68d2022-11-09 21:47:444467 ? request->GetOriginToCommit().value()
Rakina Zata Amnic7367852022-11-07 17:10:404468 : url::Origin::Create(node->current_url());
Nate Chapind1fe3612021-04-16 20:45:574469
Nate Chapind1fe3612021-04-16 20:45:574470 scoped_refptr<SiteInstance> site_instance =
Nate Chapin97d2f542022-02-18 01:34:554471 node->current_frame_host()->GetSiteInstance();
Nate Chapind1fe3612021-04-16 20:45:574472
Nate Chapine82339d02022-05-03 23:48:254473 // NOTE: |entry_index| is the index where this entry will commit if no
4474 // modifications are made between now and DidCommitNavigation. This is used to
4475 // walk |entries_| and determine which entries should be exposed by the
4476 // navigation API. It is important to calculate this correctly, because blink
4477 // will cancel a same-document history commit if it's not present in the
4478 // entries blink knows about.
4479 int entry_index = GetLastCommittedEntryIndex();
Nate Chapind1fe3612021-04-16 20:45:574480 int64_t pending_item_sequence_number = 0;
Nate Chapin63db0d12022-01-20 22:03:304481 int64_t pending_document_sequence_number = 0;
Nate Chapine82339d02022-05-03 23:48:254482 bool will_create_new_entry = false;
4483 if (GetPendingEntryIndex() != -1) {
4484 entry_index = GetPendingEntryIndex();
4485 if (auto* frame_entry = GetPendingEntry()->GetFrameEntry(node)) {
4486 pending_item_sequence_number = frame_entry->item_sequence_number();
4487 pending_document_sequence_number =
4488 frame_entry->document_sequence_number();
4489 }
4490 } else if (request &&
4491 !NavigationTypeUtils::IsReload(
4492 request->common_params().navigation_type) &&
4493 !NavigationTypeUtils::IsHistory(
4494 request->common_params().navigation_type) &&
4495 !request->common_params().should_replace_current_entry &&
4496 !request->common_params()
4497 .is_history_navigation_in_new_child_frame) {
4498 will_create_new_entry = true;
4499 entry_index = GetLastCommittedEntryIndex() + 1;
4500 // Don't set pending_item_sequence_number or
4501 // pending_document_sequence_number in this case - a new unique isn/dsn will
4502 // be calculated in the renderer later.
4503 } else if (GetLastCommittedEntryIndex() != -1) {
4504 entry_index = GetLastCommittedEntryIndex();
4505 if (auto* frame_entry = GetLastCommittedEntry()->GetFrameEntry(node)) {
Nate Chapind1fe3612021-04-16 20:45:574506 pending_item_sequence_number = frame_entry->item_sequence_number();
Nate Chapin63db0d12022-01-20 22:03:304507 pending_document_sequence_number =
4508 frame_entry->document_sequence_number();
4509 }
Nate Chapind1fe3612021-04-16 20:45:574510 }
4511
Domenic Denicolacd30f5f82022-03-16 21:48:014512 auto entry_arrays = blink::mojom::NavigationApiHistoryEntryArrays::New();
Nate Chapine82339d02022-05-03 23:48:254513 if (entry_index == -1) {
4514 // TODO(rakina): Exit early when there is no last committed entry.
4515 // Remove when InitialNavigationEntry ships.
4516 return entry_arrays;
4517 }
4518
Domenic Denicolacd30f5f82022-03-16 21:48:014519 entry_arrays->back_entries = PopulateSingleNavigationApiHistoryEntryVector(
Nate Chapind1fe3612021-04-16 20:45:574520 Direction::kBack, entry_index, pending_origin, node, site_instance.get(),
Nate Chapin4e657a472022-02-06 03:38:374521 pending_item_sequence_number, pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574522
4523 // Don't populate forward entries if they will be truncated by a new entry.
4524 if (!will_create_new_entry) {
Domenic Denicolacd30f5f82022-03-16 21:48:014525 entry_arrays->forward_entries =
4526 PopulateSingleNavigationApiHistoryEntryVector(
4527 Direction::kForward, entry_index, pending_origin, node,
4528 site_instance.get(), pending_item_sequence_number,
4529 pending_document_sequence_number);
Nate Chapind1fe3612021-04-16 20:45:574530 }
Nate Chapin4e657a472022-02-06 03:38:374531 return entry_arrays;
Nate Chapind1fe3612021-04-16 20:45:574532}
4533
Nate Chapinfbfe5af2021-06-10 17:22:084534NavigationControllerImpl::HistoryNavigationAction
Domenic Denicolacc094fb2022-03-16 23:40:574535NavigationControllerImpl::ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084536 FrameNavigationEntry* current_entry,
4537 FrameNavigationEntry* target_entry,
Domenic Denicolacc094fb2022-03-16 23:40:574538 const std::string& navigation_api_key) {
Nate Chapinfbfe5af2021-06-10 17:22:084539 if (!target_entry || !target_entry->committed_origin())
4540 return HistoryNavigationAction::kStopLooking;
4541 if (current_entry->site_instance() != target_entry->site_instance())
4542 return HistoryNavigationAction::kStopLooking;
4543 if (!current_entry->committed_origin()->IsSameOriginWith(
4544 *target_entry->committed_origin())) {
4545 return HistoryNavigationAction::kStopLooking;
4546 }
4547
4548 // NOTE: We don't actually care between kSameDocument and
4549 // kDifferentDocument, so always use kDifferentDocument by convention.
Domenic Denicolacc094fb2022-03-16 23:40:574550 if (target_entry->navigation_api_key() == navigation_api_key)
Nate Chapinfbfe5af2021-06-10 17:22:084551 return HistoryNavigationAction::kDifferentDocument;
4552 return HistoryNavigationAction::kKeepLooking;
4553}
4554
Domenic Denicolacc094fb2022-03-16 23:40:574555void NavigationControllerImpl::NavigateToNavigationApiKey(
Nate Chapinbf682fa32022-09-26 22:41:204556 RenderFrameHostImpl* initiator_rfh,
Yoav Weissa7449c3b2022-11-22 15:15:144557 absl::optional<blink::scheduler::TaskAttributionId>
4558 soft_navigation_heuristics_task_id,
Domenic Denicolacc094fb2022-03-16 23:40:574559 const std::string& key) {
Nate Chapinbf682fa32022-09-26 22:41:204560 FrameTreeNode* node = initiator_rfh->frame_tree_node();
Nate Chapinfbfe5af2021-06-10 17:22:084561 FrameNavigationEntry* current_entry =
4562 GetLastCommittedEntry()->GetFrameEntry(node);
4563 if (!current_entry)
4564 return;
4565
Yoav Weiss8c573952022-11-17 17:35:134566 // TODO(https://crbug.com/1383704): Make sure that the right task ID is passed
4567 // when `navigation.traverseTo()` is called.
4568
Nate Chapinfbfe5af2021-06-10 17:22:084569 // We want to find the nearest matching entry that is contiguously
4570 // same-instance and same-origin. Check back first, then forward.
4571 // TODO(japhet): Link spec here once it exists.
4572 for (int i = GetCurrentEntryIndex() - 1; i >= 0; i--) {
Domenic Denicolacc094fb2022-03-16 23:40:574573 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084574 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4575 if (result == HistoryNavigationAction::kStopLooking)
4576 break;
4577 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144578 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084579 return;
4580 }
4581 }
4582 for (int i = GetCurrentEntryIndex() + 1; i < GetEntryCount(); i++) {
Domenic Denicolacc094fb2022-03-16 23:40:574583 auto result = ShouldNavigateToEntryForNavigationApiKey(
Nate Chapinfbfe5af2021-06-10 17:22:084584 current_entry, GetEntryAtIndex(i)->GetFrameEntry(node), key);
4585 if (result == HistoryNavigationAction::kStopLooking)
4586 break;
4587 if (result != HistoryNavigationAction::kKeepLooking) {
Yoav Weissa7449c3b2022-11-22 15:15:144588 GoToIndex(i, initiator_rfh, soft_navigation_heuristics_task_id, &key);
Nate Chapinfbfe5af2021-06-10 17:22:084589 return;
4590 }
4591 }
Nate Chapinbf682fa32022-09-26 22:41:204592
4593 // If we fall through to here, a matching NavigationEntry couldn't be found.
4594 // Notify the renderer that the navigation was cancelled.
4595 initiator_rfh->GetAssociatedLocalFrame()->TraverseCancelled(
4596 key, blink::mojom::TraverseCancelledReason::kNotFound);
Nate Chapinfbfe5af2021-06-10 17:22:084597}
4598
Domenic Denicolacc094fb2022-03-16 23:40:574599bool NavigationControllerImpl::ShouldProtectUrlInNavigationApi(
Nate Chapin63db0d12022-01-20 22:03:304600 network::mojom::ReferrerPolicy referrer_policy) {
4601 return referrer_policy == network::mojom::ReferrerPolicy::kNever ||
4602 referrer_policy == network::mojom::ReferrerPolicy::kOrigin;
4603}
4604
shivanigithubf405bf0d2021-11-05 17:58:334605bool NavigationControllerImpl::ShouldMaintainTrivialSessionHistory(
4606 const FrameTreeNode* frame_tree_node) const {
4607 // TODO(https://crbug.com/1197384): We may have to add portals in addition to
4608 // prerender and fenced frames. This should be kept in sync with
Hayato Ito7a80db42021-07-05 06:18:544609 // LocalFrame version, LocalFrame::ShouldMaintainTrivialSessionHistory.
Ali Hijazid87307d2022-11-07 20:15:034610 return frame_tree_->is_prerendering() ||
shivanigithubf405bf0d2021-11-05 17:58:334611 frame_tree_node->IsInFencedFrameTree();
Hayato Ito7a80db42021-07-05 06:18:544612}
4613
Julie Jeongeun Kim0e242242022-11-30 10:45:094614void NavigationControllerImpl::DidChangeReferrerPolicy(
4615 FrameTreeNode* node,
4616 network::mojom::ReferrerPolicy referrer_policy) {
4617 FrameNavigationEntry* entry = GetLastCommittedEntry()->GetFrameEntry(node);
4618 if (!entry)
4619 return;
4620
4621 // The FrameNavigationEntry may want to change whether to protect its url
4622 // in the navigation API when the referrer policy changes.
4623 entry->set_protect_url_in_navigation_api(
4624 ShouldProtectUrlInNavigationApi(referrer_policy));
4625}
4626
[email protected]8ff00d72012-10-23 19:12:214627} // namespace content