blob: cc23bbdad6f445744cf8681efbf361bffc5c458a [file] [log] [blame]
[email protected]91854cd2012-01-10 19:43:571// Copyright (c) 2012 The Chromium Authors. All rights reserved.
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
[email protected]93ddb3c2012-04-11 21:44:295#include "content/browser/web_contents/web_contents_impl.h"
[email protected]39526562011-02-05 03:41:516
avib7348942015-12-25 20:57:107#include <stddef.h>
8
Avi Drissman33972942020-06-19 14:16:019#include <algorithm>
w.shackleton49bcd392016-01-06 17:38:2210#include <cmath>
[email protected]2bb171882012-03-07 02:09:4611#include <utility>
rkaplowe56a52032017-02-07 00:14:5412#include <vector>
[email protected]b75b8292010-10-01 07:28:2513
Sebastien Marchandf8cbfab2019-01-25 16:02:3014#include "base/bind.h"
[email protected]36fb2c7c2011-04-04 15:49:0815#include "base/command_line.h"
Avi Drissman33972942020-06-19 14:16:0116#include "base/containers/flat_set.h"
creisfafed882016-07-29 00:03:0917#include "base/debug/dump_without_crashing.h"
zqzhang181047e62016-07-01 13:37:1718#include "base/feature_list.h"
Marijn Kruisselbrink46fa4bd2019-07-11 18:15:4719#include "base/files/file_path.h"
[email protected]cbb1ef592013-06-05 19:49:4620#include "base/lazy_instance.h"
skyostil95082a62015-06-05 19:53:0721#include "base/location.h"
[email protected]6d636e62013-07-31 03:15:5622#include "base/logging.h"
avib7348942015-12-25 20:57:1023#include "base/macros.h"
fdorayba121422016-12-23 19:51:4824#include "base/memory/ptr_util.h"
dmazzonid95ae842016-04-12 21:17:3925#include "base/memory/ref_counted.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2026#include "base/metrics/field_trial.h"
asvitkine8d51e9d2016-09-02 23:55:4327#include "base/metrics/histogram_macros.h"
bratell0a7406f2017-03-28 07:46:3728#include "base/metrics/user_metrics.h"
Avi Drissman4891b852018-09-25 18:12:5829#include "base/no_destructor.h"
Carlos Caballero1215f882019-10-29 15:58:4330#include "base/optional.h"
[email protected]04cbd3d2013-12-04 04:58:2031#include "base/process/process.h"
skyostil95082a62015-06-05 19:53:0732#include "base/single_thread_task_runner.h"
Arthur Sonzogni929d29f2018-09-17 14:19:4433#include "base/stl_util.h"
[email protected]348fbaac2013-06-11 06:31:5134#include "base/strings/string16.h"
35#include "base/strings/string_number_conversions.h"
Avi Drissman4891b852018-09-25 18:12:5836#include "base/strings/string_split.h"
[email protected]348fbaac2013-06-11 06:31:5137#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0038#include "base/strings/utf_string_conversions.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2039#include "base/system/sys_info.h"
gab30f26df2016-05-11 19:37:5540#include "base/threading/thread_task_runner_handle.h"
[email protected]a43858f2013-06-28 15:18:3741#include "base/time/time.h"
ssid3e765612015-01-28 04:03:4242#include "base/trace_event/trace_event.h"
avib7348942015-12-25 20:57:1043#include "build/build_config.h"
Darin Fisher6cf20e782020-08-07 22:25:3644#include "build/lacros_buildflags.h"
Min Qinda0ed2062018-02-23 22:00:5345#include "components/download/public/common/download_stats.h"
nzolghadrd87a308d2016-12-07 15:45:5646#include "components/rappor/public/rappor_utils.h"
rsleevi24f64dc22015-08-07 21:39:2147#include "components/url_formatter/url_formatter.h"
Abigail Kleinaa898742019-11-01 02:31:2548#include "content/browser/accessibility/accessibility_event_recorder.h"
James Wallace-Leeeafc94cb92018-07-23 21:35:0949#include "content/browser/accessibility/accessibility_tree_formatter_blink.h"
jamescookda2505812015-03-20 18:01:1850#include "content/browser/bad_message.h"
Max Morinddebb972018-09-20 10:04:1451#include "content/browser/browser_main_loop.h"
[email protected]7a846df2012-09-20 19:17:3952#include "content/browser/browser_plugin/browser_plugin_embedder.h"
53#include "content/browser/browser_plugin/browser_plugin_guest.h"
[email protected]b9535422012-02-09 01:47:5954#include "content/browser/child_process_security_policy_impl.h"
John Delaney732721e92020-02-07 23:11:2755#include "content/browser/conversions/conversion_host.h"
Pavel Feldman3c1842b2017-08-02 05:00:1656#include "content/browser/devtools/protocol/page_handler.h"
dgozmanf00c4f72016-10-19 17:45:1557#include "content/browser/devtools/render_frame_devtools_agent_host.h"
Becca Hughes3b5a43482018-07-17 22:31:5558#include "content/browser/display_cutout/display_cutout_host_impl.h"
[email protected]5f2aa722013-08-07 16:59:4159#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0460#include "content/browser/dom_storage/session_storage_namespace_impl.h"
[email protected]aa4f3972012-03-01 18:12:1261#include "content/browser/download/mhtml_generation_manager.h"
[email protected]a53209b2012-01-20 16:48:1662#include "content/browser/download/save_package.h"
paulmeyerc0b762b2016-04-13 11:55:1763#include "content/browser/find_request_manager.h"
[email protected]bffc8302014-01-23 20:52:1664#include "content/browser/frame_host/cross_process_frame_connector.h"
ananta4b7467a52016-09-23 01:42:3865#include "content/browser/frame_host/frame_tree_node.h"
[email protected]d4a8ca482013-10-30 21:06:4066#include "content/browser/frame_host/navigation_entry_impl.h"
Arthur Hemeryc3380172018-01-22 14:00:1767#include "content/browser/frame_host/navigation_request.h"
Hiroki Nakagawa080f86c2020-05-13 10:56:4268#include "content/browser/frame_host/navigator.h"
[email protected]52913802013-12-10 05:52:1869#include "content/browser/frame_host/render_frame_host_impl.h"
lfgdb5c4ed2016-03-04 23:09:0770#include "content/browser/frame_host/render_frame_proxy_host.h"
Kenneth Russell954ed9ce2018-04-12 23:07:0171#include "content/browser/gpu/gpu_data_manager_impl.h"
mlamouriefdca9d2014-09-16 16:55:4072#include "content/browser/manifest/manifest_manager_host.h"
Max Morin5bc74f52018-05-09 07:00:2173#include "content/browser/media/audio_stream_broker.h"
dalecurtisbc6572e12014-09-12 19:22:3074#include "content/browser/media/audio_stream_monitor.h"
miu50f97892014-09-22 22:49:5275#include "content/browser/media/capture/web_contents_audio_muter.h"
dalecurtis88c240072015-12-09 02:11:1876#include "content/browser/media/media_web_contents_observer.h"
zqzhang1adf3cb2016-11-01 11:26:4577#include "content/browser/media/session/media_session_impl.h"
Mike Wassermandabad612020-08-13 04:26:2778#include "content/browser/permissions/permission_controller_impl.h"
Yuzu Saijoa11069a2020-04-22 10:56:5579#include "content/browser/plugin_content_origin_allowlist.h"
Kevin McNee94ea52f52020-06-23 17:42:0680#include "content/browser/portal/portal.h"
Tal Pressman5dcd2382020-08-26 07:13:0581#include "content/browser/renderer_host/agent_scheduling_group_host.h"
David Black9cca3592019-11-06 23:02:2282#include "content/browser/renderer_host/frame_token_message_queue.h"
[email protected]f3b1a082011-11-18 00:34:3083#include "content/browser/renderer_host/render_process_host_impl.h"
[email protected]21161032014-05-05 16:56:5084#include "content/browser/renderer_host/render_view_host_delegate_view.h"
[email protected]b3c41c0b2012-03-06 15:48:3285#include "content/browser/renderer_host/render_view_host_impl.h"
[email protected]bafe6cd2012-05-23 23:09:5086#include "content/browser/renderer_host/render_widget_host_impl.h"
kenrb2a565f82015-09-02 20:24:5987#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
[email protected]cfd80b02014-05-01 17:46:4888#include "content/browser/renderer_host/render_widget_host_view_base.h"
Ken Buchanandaef006b2017-08-17 18:32:1589#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
ekaramadadd882292016-06-08 15:22:5690#include "content/browser/renderer_host/text_input_manager.h"
Mike Wassermanb213b9352020-04-16 00:32:3491#include "content/browser/screen_enumeration/screen_change_monitor.h"
leon.han552e9de2017-02-09 14:37:3092#include "content/browser/screen_orientation/screen_orientation_provider.h"
[email protected]b6583592012-01-25 19:52:3393#include "content/browser/site_instance_impl.h"
Charlie Reis96077362019-07-04 00:34:0494#include "content/browser/web_contents/javascript_dialog_navigation_deferrer.h"
lfgc740d4b22016-04-15 16:45:3395#include "content/browser/web_contents/web_contents_view_child_frame.h"
Tsuyoshi Horob0d8d902020-03-12 00:09:3996#include "content/browser/web_package/save_as_web_bundle_job.h"
[email protected]86a0a6e2013-01-28 06:33:0397#include "content/browser/webui/web_ui_controller_factory_registry.h"
[email protected]d2353452012-01-19 19:53:5698#include "content/browser/webui/web_ui_impl.h"
[email protected]8eb04562013-03-06 03:41:1499#include "content/common/browser_plugin/browser_plugin_constants.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20100#include "content/common/content_switches_internal.h"
Paul Meyer0c58c3712016-11-17 22:59:51101#include "content/common/drag_messages.h"
[email protected]f114fa42013-12-06 17:06:44102#include "content/common/frame_messages.h"
[email protected]1f3fc1d2014-04-03 14:50:17103#include "content/common/input_messages.h"
lfgdb5c4ed2016-03-04 23:09:07104#include "content/common/page_messages.h"
nasko34634672016-07-29 18:46:06105#include "content/common/page_state_serialization.h"
rockot5c478a72016-09-28 23:14:18106#include "content/common/render_message_filter.mojom.h"
[email protected]2c5569662011-03-22 20:45:02107#include "content/common/view_messages.h"
Albert J. Wong3c93c182018-09-27 17:29:43108#include "content/common/widget_messages.h"
Abigail Kleinabb428332019-09-13 18:26:21109#include "content/public/browser/accessibility_tree_formatter.h"
[email protected]31a71eaf2014-03-13 01:47:36110#include "content/public/browser/ax_event_notification_details.h"
[email protected]ccb797302011-12-15 16:55:11111#include "content/public/browser/browser_context.h"
[email protected]139355f2014-05-11 14:21:28112#include "content/public/browser/browser_plugin_guest_manager.h"
Eric Seckler8652dcd52018-09-20 10:42:28113#include "content/public/browser/browser_task_traits.h"
Gabriel Charette790754c2018-03-16 21:32:59114#include "content/public/browser/browser_thread.h"
[email protected]87f3c082011-10-19 18:07:44115#include "content/public/browser/content_browser_client.h"
Lukasz Anforowicz8c4446dc2020-03-11 22:16:42116#include "content/public/browser/context_menu_params.h"
Ken Rockotce010f02019-12-12 23:32:32117#include "content/public/browser/device_service.h"
[email protected]e582fdd2011-12-20 16:48:17118#include "content/public/browser/download_manager.h"
Kent Tamura512a27e2018-10-04 00:49:32119#include "content/public/browser/file_select_listener.h"
ekaramada110f642016-12-21 19:47:28120#include "content/public/browser/focused_node_details.h"
Danyao Wanga78f3dd22020-03-05 05:31:27121#include "content/public/browser/global_routing_id.h"
[email protected]d9083482012-01-06 00:38:46122#include "content/public/browser/invalidate_type.h"
[email protected]71a88bb2013-02-01 22:05:15123#include "content/public/browser/javascript_dialog_manager.h"
skyf65d9bb2017-03-24 02:26:39124#include "content/public/browser/keyboard_event_processing_result.h"
[email protected]09d31d52012-03-11 22:30:27125#include "content/public/browser/load_notification_details.h"
[email protected]5b96836f2011-12-22 07:39:00126#include "content/public/browser/navigation_details.h"
[email protected]375fa1b2012-05-22 22:05:37127#include "content/public/browser/notification_details.h"
[email protected]be2510c02012-05-28 14:52:14128#include "content/public/browser/notification_service.h"
scottmg011d96e32016-06-29 19:15:08129#include "content/public/browser/notification_types.h"
[email protected]95640212014-07-26 18:14:30130#include "content/public/browser/render_widget_host_iterator.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06131#include "content/public/browser/restore_type.h"
estark5ea80e52015-06-19 18:43:12132#include "content/public/browser/security_style_explanations.h"
falken52a56e32016-12-08 05:02:40133#include "content/public/browser/ssl_status.h"
[email protected]4c3a23582012-08-18 08:54:34134#include "content/public/browser/storage_partition.h"
[email protected]674bc592011-12-20 23:00:42135#include "content/public/browser/web_contents_delegate.h"
Julie Jeongeun Kim7d0986172019-12-04 03:17:25136#include "content/public/browser/web_contents_receiver_set.h"
Lei Zhangee3b63ad2018-06-06 23:25:31137#include "content/public/browser/web_ui_controller.h"
[email protected]e091df82011-10-11 18:13:21138#include "content/public/common/bindings_policy.h"
alexmosc9e76ec2016-05-16 22:59:37139#include "content/public/common/child_process_host.h"
Hans Wennborg5ffd1392019-10-16 11:00:02140#include "content/public/common/content_client.h"
[email protected]54087fe2011-10-28 22:02:48141#include "content/public/common/content_constants.h"
Francois Doray3f2afbd2018-04-06 19:18:18142#include "content/public/common/content_features.h"
[email protected]64d69de42012-02-06 00:19:54143#include "content/public/common/content_switches.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06144#include "content/public/common/page_state.h"
Leon Han963dc182018-11-06 05:41:48145#include "content/public/common/referrer_type_converters.h"
[email protected]04cbd3d2013-12-04 04:58:20146#include "content/public/common/result_codes.h"
[email protected]f16cc6782013-12-16 23:42:57147#include "content/public/common/url_utils.h"
danakjffc8baf2019-10-10 23:49:42148#include "content/public/common/use_zoom_for_dsf_policy.h"
[email protected]b3a97b52014-07-09 06:25:05149#include "content/public/common/web_preferences.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20150#include "media/base/media_switches.h"
Max Morinddebb972018-09-20 10:04:14151#include "media/base/user_input_monitor.h"
wjmaclean64951902016-04-29 20:59:12152#include "net/base/url_util.h"
[email protected]8bfc8272013-09-09 20:10:53153#include "net/http/http_cache.h"
154#include "net/http/http_transaction_factory.h"
David Van Clevef99881632020-07-16 19:41:13155#include "net/http/http_util.h"
rhalavati0fbaeef32017-06-01 15:56:30156#include "net/traffic_annotation/network_traffic_annotation.h"
Scott Violet02e38b92018-03-27 23:42:14157#include "ppapi/buildflags/buildflags.h"
Mounir Lamourifd9dcefa2017-07-06 10:26:55158#include "services/metrics/public/cpp/ukm_recorder.h"
John Abd-El-Malekb175a612018-12-03 20:11:58159#include "services/network/public/cpp/features.h"
arthursonzognib93a4472020-04-10 07:38:00160#include "services/network/public/cpp/web_sandbox_flags.h"
161#include "services/network/public/mojom/web_sandbox_flags.mojom.h"
rockot734fb662016-10-15 16:41:30162#include "services/service_manager/public/cpp/interface_provider.h"
Becca Hughes6daf5662018-06-27 16:50:54163#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
Blink Reformata30d4232018-04-07 15:31:06164#include "third_party/blink/public/common/mime_util/mime_util.h"
danakj938b37a62019-09-24 18:35:54165#include "third_party/blink/public/common/page/page_zoom.h"
Sergio Villar Senin9d9d4f52019-10-15 10:57:57166#include "third_party/blink/public/common/security/security_style.h"
Abhijeet Kandalkarde7348e2020-01-13 06:06:54167#include "third_party/blink/public/mojom/frame/frame.mojom.h"
Dave Tapuskaa4189512019-10-15 20:27:34168#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
Takuto Ikutaaa3b796c2019-02-06 02:54:56169#include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h"
Antonio Gomes0d42960a2019-06-05 12:35:51170#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
halton.huoca2eabd2015-07-06 08:17:40171#include "third_party/skia/include/core/SkBitmap.h"
dmazzonid95ae842016-04-12 21:17:39172#include "ui/accessibility/ax_tree_combiner.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20173#include "ui/base/device_form_factor.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45174#if defined(USE_AURA)
175#include "ui/aura/window.h"
176#endif
[email protected]a08412b62012-05-29 21:28:56177#include "ui/base/layout.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20178#include "ui/base/ui_base_features.h"
179#include "ui/base/ui_base_switches.h"
180#include "ui/display/screen.h"
Daniel Cheng90196c82018-04-25 21:49:14181#include "ui/events/base_event_utils.h"
chongz4a9751942016-08-17 17:49:39182#include "ui/events/blink/web_input_event_traits.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20183#include "ui/gfx/animation/animation.h"
[email protected]66bd5512012-08-01 02:02:52184#include "ui/gl/gl_switches.h"
[email protected]3c733bde2010-12-21 19:56:31185
ekaramada110f642016-12-21 19:47:28186#if defined(OS_WIN)
187#include "content/browser/renderer_host/dip_util.h"
188#include "ui/gfx/geometry/dip_util.h"
189#endif
190
[email protected]583418cc2013-01-17 14:01:10191#if defined(OS_ANDROID)
mfomitchev2b8b066a2016-01-28 19:23:15192#include "content/browser/android/date_time_chooser_android.h"
sammcf5f1b0f2016-09-20 23:05:11193#include "content/browser/android/java_interfaces_impl.h"
Leon Hanccb985f2019-08-26 02:43:24194#include "content/browser/android/nfc_host.h"
[email protected]155c7f22013-12-09 17:07:18195#include "content/browser/web_contents/web_contents_android.h"
Ke He31d0bb02018-02-24 07:16:24196#include "services/device/public/mojom/nfc.mojom.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45197#include "ui/android/view_android.h"
mcnee336ea2c2017-05-23 22:50:59198#else // !OS_ANDROID
199#include "content/browser/host_zoom_map_impl.h"
mfomitchev2b8b066a2016-01-28 19:23:15200#endif // OS_ANDROID
[email protected]583418cc2013-01-17 14:01:10201
brettw4b461082016-11-19 18:55:16202#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17203#include "content/browser/media/session/pepper_playback_observer.h"
Lei Zhangebcc6302018-01-12 19:46:45204#endif
zqzhang181047e62016-07-01 13:37:17205
[email protected]8ff00d72012-10-23 19:12:21206namespace content {
Abigail Kleinaa898742019-11-01 02:31:25207
208using AccessibilityEventCallback =
209 base::RepeatingCallback<void(const std::string&)>;
210
[email protected]420ae012009-04-24 05:16:32211namespace {
212
[email protected]960b0372014-05-19 18:01:00213const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
[email protected]82114f52012-03-20 22:53:41214const char kDotGoogleDotCom[] = ".google.com";
[email protected]ca406032011-07-19 21:53:05215
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50216using LifecycleState = RenderFrameHostImpl::LifecycleState;
217
Alexander Timin33bd754c02020-03-10 22:50:18218// TODO(crbug.com/1059903): Clean up after the initial investigation.
219constexpr base::Feature kCheckWebContentsAccessFromNonCurrentFrame{
220 "CheckWebContentsAccessFromNonCurrentFrame",
221 base::FEATURE_DISABLED_BY_DEFAULT};
222
Avi Drissmana9114822018-03-23 18:25:55223base::LazyInstance<std::vector<
224 WebContentsImpl::FriendWrapper::CreatedCallback>>::DestructorAtExit
225 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
[email protected]cbb1ef592013-06-05 19:49:46226
dcheng57e39e22016-01-21 00:25:38227bool HasMatchingProcess(FrameTree* tree, int render_process_id) {
228 for (FrameTreeNode* node : tree->Nodes()) {
229 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id)
230 return true;
alexmos4cf2aa32015-07-15 23:40:43231 }
dcheng57e39e22016-01-21 00:25:38232 return false;
[email protected]95640212014-07-26 18:14:30233}
234
kenrb19221852016-04-29 17:21:40235bool HasMatchingWidgetHost(FrameTree* tree, RenderWidgetHost* host) {
236 // This method scans the frame tree rather than checking whether
237 // host->delegate() == this, which allows it to return false when the host
238 // for a frame that is pending or pending deletion.
239 if (!host)
240 return false;
241
242 for (FrameTreeNode* node : tree->Nodes()) {
243 if (node->current_frame_host()->GetRenderWidgetHost() == host)
244 return true;
245 }
246 return false;
247}
248
dmazzonif8a31042016-12-03 00:52:13249void UpdateAccessibilityModeOnFrame(RenderFrameHost* frame_host) {
250 static_cast<RenderFrameHostImpl*>(frame_host)->UpdateAccessibilityMode();
[email protected]95640212014-07-26 18:14:30251}
252
dtseng0dd3fa12015-07-22 19:00:52253void ResetAccessibility(RenderFrameHost* rfh) {
254 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
255}
256
Ian Clelland5cbaaf82017-11-27 22:00:03257RenderFrameHostImpl* FindOpenerRFH(const WebContents::CreateParams& params) {
258 RenderFrameHostImpl* opener_rfh = nullptr;
alexmose201c7cd2015-06-10 17:14:21259 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
Ian Clelland5cbaaf82017-11-27 22:00:03260 opener_rfh = RenderFrameHostImpl::FromID(params.opener_render_process_id,
261 params.opener_render_frame_id);
alexmose201c7cd2015-06-10 17:14:21262 }
Ian Clelland5cbaaf82017-11-27 22:00:03263 return opener_rfh;
lukasza6f8ac622017-06-06 03:10:20264}
265
Dominick Ng37a15052018-07-17 23:56:35266// Returns |true| if |type| is the kind of user input that should trigger the
267// user interaction observers.
268bool IsUserInteractionInputType(blink::WebInputEvent::Type type) {
269 // Ideally, this list would be based more off of
270 // https://whatwg.org/C/interaction.html#triggered-by-user-activation.
Dave Tapuska347d60a2020-04-21 23:55:47271 return type == blink::WebInputEvent::Type::kMouseDown ||
272 type == blink::WebInputEvent::Type::kGestureScrollBegin ||
273 type == blink::WebInputEvent::Type::kTouchStart ||
274 type == blink::WebInputEvent::Type::kRawKeyDown;
Dominick Ng37a15052018-07-17 23:56:35275}
276
Pavel Feldman3c1842b2017-08-02 05:00:16277// Ensures that OnDialogClosed is only called once.
278class CloseDialogCallbackWrapper
279 : public base::RefCountedThreadSafe<CloseDialogCallbackWrapper> {
280 public:
Avi Drissmane04d3992017-10-05 15:11:36281 using CloseCallback =
282 base::OnceCallback<void(bool, bool, const base::string16&)>;
283
284 explicit CloseDialogCallbackWrapper(CloseCallback callback)
285 : callback_(std::move(callback)) {}
Pavel Feldman3c1842b2017-08-02 05:00:16286
287 void Run(bool dialog_was_suppressed,
288 bool success,
289 const base::string16& user_input) {
Avi Drissmane04d3992017-10-05 15:11:36290 if (callback_.is_null())
Pavel Feldman3c1842b2017-08-02 05:00:16291 return;
Avi Drissmane04d3992017-10-05 15:11:36292 std::move(callback_).Run(dialog_was_suppressed, success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:16293 }
294
295 private:
296 friend class base::RefCountedThreadSafe<CloseDialogCallbackWrapper>;
297 ~CloseDialogCallbackWrapper() {}
Avi Drissmane04d3992017-10-05 15:11:36298
299 CloseCallback callback_;
Pavel Feldman3c1842b2017-08-02 05:00:16300};
301
Arthur Sonzogni929d29f2018-09-17 14:19:44302bool FrameCompareDepth(RenderFrameHostImpl* a, RenderFrameHostImpl* b) {
303 return a->frame_tree_node()->depth() < b->frame_tree_node()->depth();
304}
305
Raymes Khoury58373df2019-08-06 06:29:20306bool AreValidRegisterProtocolHandlerArguments(const std::string& protocol,
307 const GURL& url,
308 const url::Origin& origin) {
309 ChildProcessSecurityPolicyImpl* policy =
310 ChildProcessSecurityPolicyImpl::GetInstance();
311 if (policy->IsPseudoScheme(protocol))
312 return false;
313
314 url::Origin url_origin = url::Origin::Create(url);
315 if (url_origin.opaque())
316 return false;
317
318 if (!url_origin.IsSameOriginWith(origin))
319 return false;
320
321 return true;
322}
323
yilkal796e89e2019-10-02 23:58:28324void RecordMaxFrameCountUMA(size_t max_frame_count) {
325 UMA_HISTOGRAM_COUNTS_10000("Navigation.MainFrame.MaxFrameCount",
326 max_frame_count);
327}
328
Jeremy Roman03ce13ce2020-05-29 22:16:57329// Returns whether the condition provided applies to any inner contents.
330// This check is not recursive (however, the predicate provided may itself
331// recurse each contents' own inner contents).
332//
333// For example, if this is used to aggregate state from inner contents to outer
334// contents, then that propagation will gather transitive descendants without
335// need for this helper to do so. In fact, in such cases recursing on inner
336// contents here would make that operation quadratic rather than linear.
337template <typename Functor>
338bool AnyInnerWebContents(WebContents* web_contents, const Functor& f) {
339 const auto& inner_contents = web_contents->GetInnerWebContents();
340 return std::any_of(inner_contents.begin(), inner_contents.end(), f);
341}
342
Xuehui Xieb2300ae42020-06-09 20:25:05343std::vector<RenderFrameHost*> GetAllFramesImpl(FrameTree& frame_tree,
344 bool include_pending) {
345 std::vector<RenderFrameHost*> frame_hosts;
346 for (FrameTreeNode* node : frame_tree.Nodes()) {
347 frame_hosts.push_back(node->current_frame_host());
348 if (include_pending) {
349 RenderFrameHostImpl* pending_frame_host =
350 node->render_manager()->speculative_frame_host();
351 if (pending_frame_host)
352 frame_hosts.push_back(pending_frame_host);
353 }
354 }
355 return frame_hosts;
356}
357
358int SendToAllFramesImpl(FrameTree& frame_tree,
359 bool include_pending,
360 IPC::Message* message) {
361 int number_of_messages = 0;
362 std::vector<RenderFrameHost*> frame_hosts =
363 GetAllFramesImpl(frame_tree, include_pending);
364 for (RenderFrameHost* rfh : frame_hosts) {
365 if (!rfh->IsRenderFrameLive())
366 continue;
367
368 ++number_of_messages;
369 IPC::Message* message_copy = new IPC::Message(*message);
370 message_copy->set_routing_id(rfh->GetRoutingID());
371 rfh->Send(message_copy);
372 }
373 delete message;
374 return number_of_messages;
375}
376
Avi Drissman33972942020-06-19 14:16:01377// Returns the set of all WebContentses that are reachable from |web_contents|
378// by applying some combination of WebContents::GetOriginalOpener() and
379// WebContents::GetOuterWebContents(). The |web_contents| parameter will be
380// included in the returned set.
381base::flat_set<WebContentsImpl*> GetAllOpeningWebContents(
382 WebContentsImpl* web_contents) {
383 base::flat_set<WebContentsImpl*> result;
384 base::flat_set<WebContentsImpl*> current;
385
386 current.insert(web_contents);
387
388 while (!current.empty()) {
389 WebContentsImpl* current_contents = *current.begin();
390 current.erase(current.begin());
391 auto insert_result = result.insert(current_contents);
392
393 if (insert_result.second) {
394 RenderFrameHostImpl* opener_rfh = current_contents->GetOriginalOpener();
395 if (opener_rfh) {
396 current.insert(static_cast<WebContentsImpl*>(
397 WebContents::FromRenderFrameHost(opener_rfh)));
398 }
399
400 WebContentsImpl* outer_contents = current_contents->GetOuterWebContents();
401 if (outer_contents)
402 current.insert(outer_contents);
403 }
404 }
405
406 return result;
407}
408
Rakina Zata Amni4029b6d2020-07-28 02:36:20409#if defined(OS_ANDROID)
410float GetDeviceScaleAdjustment(int min_width) {
411 static const float kMinFSM = 1.05f;
412 static const int kWidthForMinFSM = 320;
413 static const float kMaxFSM = 1.3f;
414 static const int kWidthForMaxFSM = 800;
415
416 if (min_width <= kWidthForMinFSM)
417 return kMinFSM;
418 if (min_width >= kWidthForMaxFSM)
419 return kMaxFSM;
420
421 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
422 float ratio = static_cast<float>(min_width - kWidthForMinFSM) /
423 (kWidthForMaxFSM - kWidthForMinFSM);
424 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
425}
426#endif
427
Avi Drissman33972942020-06-19 14:16:01428// Used to attach the "set of fullscreen contents" to a browser context. Storing
429// sets of WebContents on their browser context is done for two reasons. One,
430// related WebContentses must necessarily share a browser context, so this saves
431// lookup time by restricting to one specific browser context. Two, separating
432// by browser context is preemptive paranoia about keeping things separate.
433class FullscreenContentsHolder : public base::SupportsUserData::Data {
434 public:
435 FullscreenContentsHolder() = default;
436 ~FullscreenContentsHolder() override = default;
437
438 FullscreenContentsHolder(const FullscreenContentsHolder&) = delete;
439 FullscreenContentsHolder& operator=(const FullscreenContentsHolder&) = delete;
440
441 base::flat_set<WebContentsImpl*>* set() { return &set_; }
442
443 private:
444 base::flat_set<WebContentsImpl*> set_;
445};
446
447const char kFullscreenContentsSet[] = "fullscreen-contents";
448
449base::flat_set<WebContentsImpl*>* FullscreenContentsSet(
450 BrowserContext* browser_context) {
451 auto* set_holder = static_cast<FullscreenContentsHolder*>(
452 browser_context->GetUserData(kFullscreenContentsSet));
453 if (!set_holder) {
454 auto new_holder = std::make_unique<FullscreenContentsHolder>();
455 set_holder = new_holder.get();
456 browser_context->SetUserData(kFullscreenContentsSet, std::move(new_holder));
457 }
458
459 return set_holder->set();
460}
461
Mike Wasserman5b7d3bf2020-08-21 21:52:26462// Returns true if |host| has the Window Placement permission granted.
463bool WindowPlacementGranted(RenderFrameHost* host) {
464 auto* controller =
465 PermissionControllerImpl::FromBrowserContext(host->GetBrowserContext());
466 return controller && controller->GetPermissionStatusForFrame(
467 PermissionType::WINDOW_PLACEMENT, host,
468 host->GetLastCommittedURL()) ==
469 blink::mojom::PermissionStatus::GRANTED;
470}
471
Mike Wassermanb6bc0152020-08-25 22:46:20472// Adjust the requested |bounds| for opening or placing a window and return the
473// id of the display where the window will be placed. The bounds may not extend
474// outside a single screen's work area, and the |host| requires permission to
475// specify bounds on a screen other than its current screen.
Mike Wassermandabad612020-08-13 04:26:27476// TODO(crbug.com/897300): These adjustments are inaccurate for window.open(),
477// which specifies the inner content size, and for window.moveTo, resizeTo, etc.
478// calls on newly created windows, which may pass empty sizes or positions to
479// indicate uninitialized placement information in the renderer. Constraints
480// enforced later should resolve most inaccuracies, but this early enforcement
481// is needed to ensure bounds indicate the appropriate display.
Mike Wassermanb6bc0152020-08-25 22:46:20482int64_t AdjustRequestedWindowBounds(gfx::Rect* bounds, RenderFrameHost* host) {
Mike Wassermandabad612020-08-13 04:26:27483 auto* screen = display::Screen::GetScreen();
Mike Wassermanb6bc0152020-08-25 22:46:20484 auto display = screen->GetDisplayMatching(*bounds);
Mike Wassermandabad612020-08-13 04:26:27485
486 // Check, but do not prompt, for permission to place windows on other screens.
487 // Sites generally need permission to get such bounds in the first place.
488 // Also clamp offscreen bounds to the window's current screen.
Mike Wassermanb6bc0152020-08-25 22:46:20489 if (!bounds->Intersects(display.bounds()) || !WindowPlacementGranted(host))
Mike Wassermandabad612020-08-13 04:26:27490 display = screen->GetDisplayNearestView(host->GetNativeView());
Mike Wassermandabad612020-08-13 04:26:27491
Mike Wassermanb6bc0152020-08-25 22:46:20492 bounds->AdjustToFit(display.work_area());
493 return display.id();
Mike Wassermandabad612020-08-13 04:26:27494}
495
lukasza6f8ac622017-06-06 03:10:20496} // namespace
497
Joel Hockey8c2011b22020-04-30 05:07:19498CreatedWindow::CreatedWindow() = default;
499CreatedWindow::CreatedWindow(std::unique_ptr<WebContentsImpl> contents,
500 GURL target_url)
501 : contents(std::move(contents)), target_url(std::move(target_url)) {}
502CreatedWindow::~CreatedWindow() = default;
503CreatedWindow::CreatedWindow(CreatedWindow&&) = default;
504CreatedWindow& CreatedWindow::operator=(CreatedWindow&&) = default;
505
Erik Chenbb8e738e2018-04-28 14:10:43506std::unique_ptr<WebContents> WebContents::Create(
507 const WebContents::CreateParams& params) {
Albert J. Wong65fe64d2019-09-20 02:48:14508 return WebContentsImpl::Create(params);
509}
510
511std::unique_ptr<WebContentsImpl> WebContentsImpl::Create(
512 const CreateParams& params) {
513 return CreateWithOpener(params, FindOpenerRFH(params));
[email protected]d1198fd2012-08-13 22:50:19514}
515
erikchenade1fef2018-05-02 22:07:57516std::unique_ptr<WebContents> WebContents::CreateWithSessionStorage(
[email protected]54944cde2012-12-09 09:24:59517 const WebContents::CreateParams& params,
[email protected]fdac6ade2013-07-20 01:06:30518 const SessionStorageNamespaceMap& session_storage_namespace_map) {
erikchenade1fef2018-05-02 22:07:57519 std::unique_ptr<WebContentsImpl> new_contents(
520 new WebContentsImpl(params.browser_context));
Ian Clelland5cbaaf82017-11-27 22:00:03521 RenderFrameHostImpl* opener_rfh = FindOpenerRFH(params);
522 FrameTreeNode* opener = nullptr;
523 if (opener_rfh)
524 opener = opener_rfh->frame_tree_node();
525 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
[email protected]fdac6ade2013-07-20 01:06:30526
jdoerrie55ec69d2018-10-08 13:34:46527 for (auto it = session_storage_namespace_map.begin();
528 it != session_storage_namespace_map.end(); ++it) {
Fergal Daly09d6c762020-05-29 02:05:18529 new_contents->GetController().SetSessionStorageNamespace(it->first,
530 it->second.get());
[email protected]fdac6ade2013-07-20 01:06:30531 }
532
Sean Toppingbbc4a2bd2019-01-30 02:16:14533 WebContentsImpl* outer_web_contents = nullptr;
Sam McNally69a33772018-06-27 16:54:12534 if (params.guest_delegate) {
535 // This makes |new_contents| act as a guest.
536 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:04537 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
538 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:14539 outer_web_contents = static_cast<WebContentsImpl*>(
540 params.guest_delegate->GetOwnerWebContents());
Sam McNally69a33772018-06-27 16:54:12541 }
542
[email protected]54944cde2012-12-09 09:24:59543 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:14544 if (outer_web_contents)
545 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:19546 return new_contents;
[email protected]a81343d232011-12-27 07:39:20547}
[email protected]746d3052012-05-22 15:15:47548
benwells5e7260d2017-03-20 23:36:33549void WebContentsImpl::FriendWrapper::AddCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37550 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46551 g_created_callbacks.Get().push_back(callback);
552}
553
benwells5e7260d2017-03-20 23:36:33554void WebContentsImpl::FriendWrapper::RemoveCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37555 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46556 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
Robert Liao1db5a352019-06-05 20:57:34557 if (g_created_callbacks.Get().at(i) == callback) {
[email protected]cbb1ef592013-06-05 19:49:46558 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
559 return;
560 }
561 }
562}
563
avidf38c952015-10-27 13:45:13564WebContents* WebContents::FromRenderViewHost(RenderViewHost* rvh) {
565 if (!rvh)
566 return nullptr;
[email protected]746d3052012-05-22 15:15:47567 return rvh->GetDelegate()->GetAsWebContents();
568}
569
[email protected]a86c0e962013-12-17 17:10:39570WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
avidf38c952015-10-27 13:45:13571 if (!rfh)
572 return nullptr;
Alexander Timin33bd754c02020-03-10 22:50:18573 if (!rfh->IsCurrent() && base::FeatureList::IsEnabled(
574 kCheckWebContentsAccessFromNonCurrentFrame)) {
575 // TODO(crbug.com/1059903): return nullptr here eventually.
576 base::debug::DumpWithoutCrashing();
577 }
avidf38c952015-10-27 13:45:13578 return static_cast<RenderFrameHostImpl*>(rfh)->delegate()->GetAsWebContents();
[email protected]a86c0e962013-12-17 17:10:39579}
580
ananta4b7467a52016-09-23 01:42:38581WebContents* WebContents::FromFrameTreeNodeId(int frame_tree_node_id) {
582 FrameTreeNode* frame_tree_node =
583 FrameTreeNode::GloballyFindByID(frame_tree_node_id);
anantab8cfa3b2016-10-14 22:43:19584 if (!frame_tree_node)
585 return nullptr;
jam8c4edd02017-05-06 18:50:33586 return WebContentsImpl::FromFrameTreeNode(frame_tree_node);
ananta4b7467a52016-09-23 01:42:38587}
588
leon.han552e9de2017-02-09 14:37:30589void WebContents::SetScreenOrientationDelegate(
590 ScreenOrientationDelegate* delegate) {
591 ScreenOrientationProvider::SetDelegate(delegate);
592}
593
[email protected]7fff43e2013-05-21 20:21:10594// WebContentsImpl::DestructionObserver ----------------------------------------
595
596class WebContentsImpl::DestructionObserver : public WebContentsObserver {
597 public:
598 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
Fergal Daly09d6c762020-05-29 02:05:18599 : WebContentsObserver(watched_contents), owner_(owner) {}
[email protected]7fff43e2013-05-21 20:21:10600
601 // WebContentsObserver:
dchengc2282aa2014-10-21 12:07:58602 void WebContentsDestroyed() override {
[email protected]12a46832014-05-09 13:35:58603 owner_->OnWebContentsDestroyed(
604 static_cast<WebContentsImpl*>(web_contents()));
[email protected]7fff43e2013-05-21 20:21:10605 }
606
607 private:
608 WebContentsImpl* owner_;
609
610 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
611};
612
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50613// TODO(sreejakshetty): Make |WebContentsImpl::ColorChooser| per-frame instead
614// of WebContents-owned.
Joel Hockey85b379d2017-12-11 10:42:13615// WebContentsImpl::ColorChooser ----------------------------------------------
Joel Hockey163835a2017-12-20 11:51:57616class WebContentsImpl::ColorChooser : public blink::mojom::ColorChooser {
Joel Hockey85b379d2017-12-11 10:42:13617 public:
618 ColorChooser(content::ColorChooser* chooser,
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20619 mojo::PendingReceiver<blink::mojom::ColorChooser> receiver,
620 mojo::PendingRemote<blink::mojom::ColorChooserClient> client)
Joel Hockey85b379d2017-12-11 10:42:13621 : chooser_(chooser),
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20622 receiver_(this, std::move(receiver)),
Joel Hockey85b379d2017-12-11 10:42:13623 client_(std::move(client)) {
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20624 receiver_.set_disconnect_handler(
Joel Hockey85b379d2017-12-11 10:42:13625 base::BindOnce([](content::ColorChooser* chooser) { chooser->End(); },
626 base::Unretained(chooser)));
627 }
[email protected]8ed16472014-04-11 19:02:48628
Joel Hockey85b379d2017-12-11 10:42:13629 ~ColorChooser() override { chooser_->End(); }
[email protected]8ed16472014-04-11 19:02:48630
Joel Hockey85b379d2017-12-11 10:42:13631 void SetSelectedColor(SkColor color) override {
632 chooser_->SetSelectedColor(color);
633 }
634
635 void DidChooseColorInColorChooser(SkColor color) {
636 client_->DidChooseColor(color);
637 }
638
639 private:
640 // Color chooser that was opened by this tab.
641 std::unique_ptr<content::ColorChooser> chooser_;
642
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20643 // mojo receiver.
644 mojo::Receiver<blink::mojom::ColorChooser> receiver_;
Joel Hockey85b379d2017-12-11 10:42:13645
646 // mojo renderer client.
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20647 mojo::Remote<blink::mojom::ColorChooserClient> client_;
Joel Hockey85b379d2017-12-11 10:42:13648};
nicka0ac8382016-12-15 23:59:23649
lazyboy6ec48b2a2015-06-29 15:18:14650// WebContentsImpl::WebContentsTreeNode ----------------------------------------
lfg601233692017-03-06 22:45:44651WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode(
652 WebContentsImpl* current_web_contents)
653 : current_web_contents_(current_web_contents),
654 outer_web_contents_(nullptr),
lazyboy6ec48b2a2015-06-29 15:18:14655 outer_contents_frame_tree_node_id_(
avallee0206f782016-07-28 18:55:33656 FrameTreeNode::kFrameTreeNodeInvalidId),
lfg601233692017-03-06 22:45:44657 focused_web_contents_(current_web_contents) {}
lazyboy6ec48b2a2015-06-29 15:18:14658
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18659WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {}
lazyboy6ec48b2a2015-06-29 15:18:14660
Lucas Furukawa Gadani99125822019-01-03 15:41:49661std::unique_ptr<WebContents>
662WebContentsImpl::WebContentsTreeNode::DisconnectFromOuterWebContents() {
663 std::unique_ptr<WebContents> inner_contents =
664 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
665 OuterContentsFrameTreeNode()->RemoveObserver(this);
666 outer_contents_frame_tree_node_id_ = FrameTreeNode::kFrameTreeNodeInvalidId;
667 outer_web_contents_ = nullptr;
668 return inner_contents;
669}
670
paulmeyerfeafc2d2017-04-25 21:46:40671void WebContentsImpl::WebContentsTreeNode::AttachInnerWebContents(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50672 std::unique_ptr<WebContents> inner_web_contents,
673 RenderFrameHostImpl* render_frame_host) {
674 WebContentsImpl* inner_web_contents_impl =
675 static_cast<WebContentsImpl*>(inner_web_contents.get());
676 WebContentsTreeNode& inner_web_contents_node = inner_web_contents_impl->node_;
677
678 inner_web_contents_node.focused_web_contents_ = nullptr;
679 inner_web_contents_node.outer_web_contents_ = current_web_contents_;
680 inner_web_contents_node.outer_contents_frame_tree_node_id_ =
681 render_frame_host->frame_tree_node()->frame_tree_node_id();
682
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18683 inner_web_contents_.push_back(std::move(inner_web_contents));
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50684
685 render_frame_host->frame_tree_node()->AddObserver(&inner_web_contents_node);
Jeremy Roman03ce13ce2020-05-29 22:16:57686 current_web_contents_->InnerWebContentsAttached(inner_web_contents_impl);
paulmeyerfeafc2d2017-04-25 21:46:40687}
688
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18689std::unique_ptr<WebContents>
690WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents(
paulmeyerfeafc2d2017-04-25 21:46:40691 WebContentsImpl* inner_web_contents) {
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18692 std::unique_ptr<WebContents> detached_contents;
693 for (std::unique_ptr<WebContents>& web_contents : inner_web_contents_) {
694 if (web_contents.get() == inner_web_contents) {
695 detached_contents = std::move(web_contents);
696 std::swap(web_contents, inner_web_contents_.back());
697 inner_web_contents_.pop_back();
Jeremy Roman03ce13ce2020-05-29 22:16:57698 current_web_contents_->InnerWebContentsDetached(inner_web_contents);
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18699 return detached_contents;
700 }
701 }
702
703 NOTREACHED();
704 return nullptr;
paulmeyerfeafc2d2017-04-25 21:46:40705}
706
lfga3e2bdc2017-03-07 20:44:01707FrameTreeNode*
708WebContentsImpl::WebContentsTreeNode::OuterContentsFrameTreeNode() const {
709 return FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id_);
lfg601233692017-03-06 22:45:44710}
711
lfga3e2bdc2017-03-07 20:44:01712void WebContentsImpl::WebContentsTreeNode::OnFrameTreeNodeDestroyed(
713 FrameTreeNode* node) {
714 DCHECK_EQ(outer_contents_frame_tree_node_id_, node->frame_tree_node_id())
715 << "WebContentsTreeNode should only receive notifications for the "
716 "FrameTreeNode in its outer WebContents that hosts it.";
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18717
718 // Deletes |this| too.
719 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
lazyboy6ec48b2a2015-06-29 15:18:14720}
721
avallee0206f782016-07-28 18:55:33722void WebContentsImpl::WebContentsTreeNode::SetFocusedWebContents(
723 WebContentsImpl* web_contents) {
724 DCHECK(!outer_web_contents())
725 << "Only the outermost WebContents tracks focus.";
726 focused_web_contents_ = web_contents;
727}
728
paulmeyerfeafc2d2017-04-25 21:46:40729WebContentsImpl*
730WebContentsImpl::WebContentsTreeNode::GetInnerWebContentsInFrame(
731 const FrameTreeNode* frame) {
732 auto ftn_id = frame->frame_tree_node_id();
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18733 for (auto& contents : inner_web_contents_) {
734 WebContentsImpl* impl = static_cast<WebContentsImpl*>(contents.get());
735 if (impl->node_.outer_contents_frame_tree_node_id() == ftn_id) {
736 return impl;
paulmeyerfeafc2d2017-04-25 21:46:40737 }
738 }
739 return nullptr;
740}
741
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18742std::vector<WebContentsImpl*>
743WebContentsImpl::WebContentsTreeNode::GetInnerWebContents() const {
744 std::vector<WebContentsImpl*> inner_web_contents;
745 for (auto& contents : inner_web_contents_)
746 inner_web_contents.push_back(static_cast<WebContentsImpl*>(contents.get()));
747
748 return inner_web_contents;
paulmeyerfeafc2d2017-04-25 21:46:40749}
750
Alexander Timin90c20c32020-08-12 15:28:32751// WebContentsObserverList -----------------------------------------------------
752WebContentsImpl::WebContentsObserverList::WebContentsObserverList() = default;
753WebContentsImpl::WebContentsObserverList::~WebContentsObserverList() = default;
754
755void WebContentsImpl::WebContentsObserverList::AddObserver(
756 WebContentsObserver* observer) {
757 observers_.AddObserver(observer);
758}
759
760void WebContentsImpl::WebContentsObserverList::RemoveObserver(
761 WebContentsObserver* observer) {
762 observers_.RemoveObserver(observer);
763}
764
[email protected]b172aee2012-04-10 17:05:26765// WebContentsImpl -------------------------------------------------------------
[email protected]420ae012009-04-24 05:16:32766
alexmose201c7cd2015-06-10 17:14:21767WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28768 : delegate_(nullptr),
[email protected]69e797f2013-04-30 01:10:22769 controller_(this, browser_context),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28770 render_view_host_delegate_view_(nullptr),
alexmose201c7cd2015-06-10 17:14:21771 created_with_opener_(false),
Lucas Furukawa Gadani99125822019-01-03 15:41:49772 node_(this),
Fergal Daly09d6c762020-05-29 02:05:18773 frame_tree_(&controller_, this, this, this, this, this),
[email protected]6dfed692014-05-22 04:18:03774 is_load_to_different_document_(false),
[email protected]443b80e2010-12-14 00:42:23775 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
776 crashed_error_code_(0),
[email protected]d5f942ba2008-09-26 19:30:34777 waiting_for_response_(false),
[email protected]fcf75d42013-12-03 20:11:26778 load_state_(net::LOAD_STATE_IDLE, base::string16()),
[email protected]094e5b22009-09-25 04:23:56779 upload_size_(0),
780 upload_position_(0),
dfalcantarae6b7b46752015-07-10 18:14:16781 is_resume_pending_(false),
[email protected]b4c84012014-04-28 19:51:10782 has_accessed_initial_document_(false),
Collin Bakerc5259962019-11-14 17:51:58783 visible_capturer_count_(0),
784 hidden_capturer_count_(0),
[email protected]fdd61c62009-04-22 19:22:57785 is_being_destroyed_(false),
786 notify_disconnection_(false),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28787 dialog_manager_(nullptr),
[email protected]7ab1e7d62009-10-14 23:32:01788 is_showing_before_unload_dialog_(false),
gab0dccfef2015-05-20 18:43:39789 last_active_time_(base::TimeTicks::Now()),
[email protected]ebf40a72010-07-22 01:46:38790 closed_by_user_gesture_(false),
danakj938b37a62019-09-24 18:35:54791 minimum_zoom_percent_(
792 static_cast<int>(blink::kMinimumPageZoomFactor * 100)),
793 maximum_zoom_percent_(
794 static_cast<int>(blink::kMaximumPageZoomFactor * 100)),
w.shackleton49bcd392016-01-06 17:38:22795 zoom_scroll_remainder_(0),
alexmosc9e76ec2016-05-16 22:59:37796 fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID),
[email protected]5dcaf8e2013-12-28 01:31:42797 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
[email protected]0b431992014-06-24 00:08:03798 fullscreen_widget_had_focus_at_shutdown_(false),
[email protected]34ff1cfc2014-08-20 06:16:05799 force_disable_overscroll_content_(false),
[email protected]95640212014-07-26 18:14:30800 last_dialog_suppressed_(false),
waffles1c12bf402016-02-10 17:45:48801 accessibility_mode_(
Dominic Mazzoni21fb0282019-02-13 18:32:47802 GetContentClient()->browser()->GetAXModeForBrowserContext(
803 browser_context)),
avayvodcc85bbd2015-08-28 19:11:15804 audio_stream_monitor_(this),
Thomas Guilbert882c4cec2019-02-14 05:55:45805 media_web_contents_observer_(
806 std::make_unique<MediaWebContentsObserver>(this)),
mcnee336ea2c2017-05-23 22:50:59807#if !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:46808 page_scale_factor_is_one_(true),
mcnee336ea2c2017-05-23 22:50:59809#endif // !defined(OS_ANDROID)
qinmin72e8bd02016-10-21 19:35:37810 is_overlay_content_(false),
ekaramadf6750aa2017-06-06 18:29:42811 showing_context_menu_(false),
W. James MacLean62198672019-06-04 16:46:10812 text_autosizer_page_info_({0, 0, 1.f}),
shivanigithubcceeacf2020-03-06 20:00:27813 native_theme_observer_(this) {
danakjf4b9e942019-11-29 15:43:04814 frame_tree_.SetFrameRemoveListener(base::BindRepeating(
815 &WebContentsImpl::OnFrameRemoved, base::Unretained(this)));
brettw4b461082016-11-19 18:55:16816#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17817 pepper_playback_observer_.reset(new PepperPlaybackObserver(this));
818#endif
blundelle75a8f92017-03-27 08:11:17819
Becca Hughes86334622018-07-09 21:29:38820#if defined(OS_ANDROID)
Elly Fong-Jonescdd7ae82019-02-20 23:26:33821 display_cutout_host_impl_ = std::make_unique<DisplayCutoutHostImpl>(this);
Becca Hughes86334622018-07-09 21:29:38822#endif
John Delaney732721e92020-02-07 23:11:27823
Alison Maher7f366dc62020-03-03 19:46:00824 ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForWeb();
825 native_theme_observer_.Add(native_theme);
826 using_dark_colors_ = native_theme->ShouldUseDarkColors();
827 preferred_color_scheme_ = native_theme->GetPreferredColorScheme();
828
Mike Wassermanb213b9352020-04-16 00:32:34829 screen_change_monitor_ =
830 std::make_unique<ScreenChangeMonitor>(base::BindRepeating(
831 &WebContentsImpl::OnScreensChange, base::Unretained(this)));
832
John Delaney732721e92020-02-07 23:11:27833 // ConversionHost takes a weak ref on |this|, so it must be created outside of
834 // the initializer list.
Charlie Harrison405f6212020-04-14 21:57:32835 if (base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
836 conversion_host_ = std::make_unique<ConversionHost>(this);
837 }
[email protected]332af7732009-03-11 13:21:35838}
initial.commit09911bf2008-07-26 23:55:29839
[email protected]b172aee2012-04-10 17:05:26840WebContentsImpl::~WebContentsImpl() {
creisba91ba82017-05-12 22:56:19841 // Imperfect sanity check against double free, given some crashes unexpectedly
842 // observed in the wild.
843 CHECK(!is_being_destroyed_);
844
845 // We generally keep track of is_being_destroyed_ to let other features know
846 // to avoid certain actions during destruction.
[email protected]420ae012009-04-24 05:16:32847 is_being_destroyed_ = true;
848
creis97867aa2017-02-17 18:39:45849 // A WebContents should never be deleted while it is notifying observers,
creisba91ba82017-05-12 22:56:19850 // since this will lead to a use-after-free as it continues to notify later
creis97867aa2017-02-17 18:39:45851 // observers.
Alexander Timin90c20c32020-08-12 15:28:32852 CHECK(!observers_.is_notifying_observers());
creis97867aa2017-02-17 18:39:45853
Avi Drissman33972942020-06-19 14:16:01854 FullscreenContentsSet(GetBrowserContext())->erase(this);
855
kenrb2a565f82015-09-02 20:24:59856 rwh_input_event_router_.reset();
857
Julie Jeongeun Kim7d0986172019-12-04 03:17:25858 for (auto& entry : receiver_sets_)
859 entry.second->CloseAllReceivers();
rockotf62002a2016-09-15 00:08:59860
avallee0206f782016-07-28 18:55:33861 WebContentsImpl* outermost = GetOutermostWebContents();
avallee9993fca2016-11-17 06:16:50862 if (this != outermost && ContainsOrIsFocusedWebContents()) {
avallee0206f782016-07-28 18:55:33863 // If the current WebContents is in focus, unset it.
avallee9993fca2016-11-17 06:16:50864 outermost->SetAsFocusedWebContentsIfNecessary();
avallee0206f782016-07-28 18:55:33865 }
866
Nick Carterd73635b2018-03-13 18:31:41867 if (mouse_lock_widget_)
James Hollyerd5c9de462020-03-10 19:02:45868 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
869 blink::mojom::PointerLockResult::kElementDestroyed);
Nick Carterd73635b2018-03-13 18:31:41870
dcheng72be33c2016-01-21 04:11:31871 for (FrameTreeNode* node : frame_tree_.Nodes()) {
872 // Delete all RFHs pending shutdown, which will lead the corresponding RVHs
873 // to be shutdown and be deleted as well.
dcheng57e39e22016-01-21 00:25:38874 node->render_manager()->ClearRFHsPendingShutdown();
dcheng57e39e22016-01-21 00:25:38875 node->render_manager()->ClearWebUIInstances();
dcheng72be33c2016-01-21 04:11:31876 }
carlosk35f35af2015-12-01 10:55:40877
dcheng57e39e22016-01-21 00:25:38878 for (RenderWidgetHostImpl* widget : created_widgets_)
879 widget->DetachDelegate();
[email protected]b24b68a2012-09-24 21:57:26880 created_widgets_.clear();
881
[email protected]3ab9cb82011-06-03 18:02:07882 // Clear out any JavaScript state.
avi5d3b8692016-10-12 22:00:46883 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:53884 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:46885 }
[email protected]3ab9cb82011-06-03 18:02:07886
Joel Hockey85b379d2017-12-11 10:42:13887 color_chooser_.reset();
Rakina Zata Amni16196122018-11-14 02:14:00888 find_request_manager_.reset();
[email protected]da8543762012-03-20 08:52:20889
[email protected]420ae012009-04-24 05:16:32890 NotifyDisconnected();
[email protected]420ae012009-04-24 05:16:32891
[email protected]ca13a442012-04-17 14:00:12892 // Notify any observer that have a reference on this WebContents.
[email protected]8ff00d72012-10-23 19:12:21893 NotificationService::current()->Notify(
894 NOTIFICATION_WEB_CONTENTS_DESTROYED,
895 Source<WebContents>(this),
896 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:32897
Arthur Sonzogni5a9a88c2018-10-18 13:16:00898 // Destroy all subframes now. This notifies observers.
899 GetMainFrame()->ResetChildren();
[email protected]df0c843f2014-05-23 20:37:23900 GetRenderManager()->ResetProxyHosts();
[email protected]c06c58c2014-03-12 20:31:59901
clamy0e119882015-07-31 16:12:33902 // Manually call the observer methods for the root frame tree node. It is
903 // necessary to manually delete all objects tracking navigations
904 // (NavigationHandle, NavigationRequest) for observers to be properly
905 // notified of these navigations stopping before the WebContents is
906 // destroyed.
[email protected]df0c843f2014-05-23 20:37:23907 RenderFrameHostManager* root = GetRenderManager();
naskob21fe4872015-02-24 14:15:56908
Lowell Manners20250112019-10-18 15:06:15909 GetController().GetBackForwardCache().Shutdown();
910
naskob21fe4872015-02-24 14:15:56911 root->current_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28912 root->current_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33913
Arthur Hemeryc3380172018-01-22 14:00:17914 // Do not update state as the WebContents is being destroyed.
Arthur Hemery241b9392019-10-24 11:08:41915 frame_tree_.root()->ResetNavigationRequest(true);
Arthur Hemeryc3380172018-01-22 14:00:17916 if (root->speculative_frame_host()) {
danakjf2342432019-05-15 21:46:09917 root->speculative_frame_host()->DeleteRenderFrame(
918 FrameDeleteIntention::kSpeculativeMainFrameForShutdown);
Arthur Hemeryc3380172018-01-22 14:00:17919 root->speculative_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28920 root->speculative_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33921 }
[email protected]f273ee52013-10-18 16:05:27922
brettw4b461082016-11-19 18:55:16923#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17924 // Call this before WebContentsDestroyed() is broadcasted since
925 // AudioFocusManager will be destroyed after that.
926 pepper_playback_observer_.reset();
927#endif // defined(ENABLED_PLUGINS)
928
Chris Hamiltondf0d72cd2018-05-29 16:23:53929 // If audio is playing then notify external observers of the audio stream
930 // disappearing.
931 if (is_currently_audible_) {
932 is_currently_audible_ = false;
Alexander Timin90c20c32020-08-12 15:28:32933 observers_.ForEachObserver([&](WebContentsObserver* observer) {
934 observer->OnAudioStateChanged(false);
935 });
Chris Hamiltondf0d72cd2018-05-29 16:23:53936 if (GetOuterWebContents())
937 GetOuterWebContents()->OnAudioStateChanged();
938 }
939
Alexander Timin90c20c32020-08-12 15:28:32940 observers_.ForEachObserver([&](WebContentsObserver* observer) {
941 observer->FrameDeleted(root->current_frame_host());
942 });
943 observers_.ForEachObserver([&](WebContentsObserver* observer) {
944 observer->RenderViewDeleted(root->current_host());
945 });
Kevin McNee576bb5d82019-05-29 16:47:51946#if defined(OS_ANDROID)
947 // For simplicity, destroy the Java WebContents before we notify of the
948 // destruction of the WebContents.
949 ClearWebContentsAndroid();
950#endif
951
Alexander Timin90c20c32020-08-12 15:28:32952 observers_.ForEachObserver(
953 [&](WebContentsObserver* observer) { observer->WebContentsDestroyed(); });
Becca Hughesd11d6502018-07-31 17:01:28954 if (display_cutout_host_impl_)
955 display_cutout_host_impl_->WebContentsDestroyed();
956
Alexander Timin90c20c32020-08-12 15:28:32957 observers_.ForEachObserver(
958 [&](WebContentsObserver* observer) { observer->ResetWebContents(); });
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28959 SetDelegate(nullptr);
[email protected]b5a1d11c2011-02-17 03:09:42960}
961
erikchen50735fd2018-05-05 15:08:33962std::unique_ptr<WebContentsImpl> WebContentsImpl::CreateWithOpener(
[email protected]54944cde2012-12-09 09:24:59963 const WebContents::CreateParams& params,
Ian Clelland5cbaaf82017-11-27 22:00:03964 RenderFrameHostImpl* opener_rfh) {
[email protected]e11f0e92013-06-12 15:12:03965 TRACE_EVENT0("browser", "WebContentsImpl::CreateWithOpener");
Ian Clelland5cbaaf82017-11-27 22:00:03966 FrameTreeNode* opener = nullptr;
967 if (opener_rfh)
968 opener = opener_rfh->frame_tree_node();
erikchen50735fd2018-05-05 15:08:33969 std::unique_ptr<WebContentsImpl> new_contents(
970 new WebContentsImpl(params.browser_context));
lukasza6f8ac622017-06-06 03:10:20971 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
alexmose201c7cd2015-06-10 17:14:21972
alexmosaedfc6f2016-01-21 23:57:38973 // If the opener is sandboxed, a new popup must inherit the opener's sandbox
974 // flags, and these flags take effect immediately. An exception is if the
975 // opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
976 // bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
977 // See https://html.spec.whatwg.org/#attr-iframe-sandbox.
lukasza6f8ac622017-06-06 03:10:20978 FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
alexmosaedfc6f2016-01-21 23:57:38979 if (opener) {
arthursonzognib93a4472020-04-10 07:38:00980 network::mojom::WebSandboxFlags opener_flags =
Antonio Gomes7096ac02020-02-14 14:29:54981 opener_rfh->active_sandbox_flags();
arthursonzognib93a4472020-04-10 07:38:00982 const network::mojom::WebSandboxFlags inherit_flag =
983 network::mojom::WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts;
Ehsan Karamad39407082019-02-19 23:38:19984 bool sandbox_propagates_to_auxilary_context =
985 (opener_flags & inherit_flag) == inherit_flag;
986 if (sandbox_propagates_to_auxilary_context)
Charlie Hue1b77ac2019-12-13 21:30:17987 new_root->SetPendingFramePolicy({opener_flags,
988 {} /* container_policy */,
989 {} /* required_document_policy */});
arthursonzognib93a4472020-04-10 07:38:00990 if (opener_flags == network::mojom::WebSandboxFlags::kNone ||
Ehsan Karamad39407082019-02-19 23:38:19991 sandbox_propagates_to_auxilary_context) {
992 // TODO(ekaramad, iclelland): Do not propagate feature policies from non-
993 // sandboxed disowned openers (rel=noopener).
994 // If the current page is not sandboxed, or if the sandbox is to propagate
995 // to the popups then opener's feature policy will apply to the new popup
996 // as well.
997 new_root->SetOpenerFeaturePolicyState(
Ehsan Karamad34d10682019-02-26 20:55:04998 opener_rfh->feature_policy()->GetFeatureState());
alexmosaedfc6f2016-01-21 23:57:38999 }
1000 }
1001
mark a. foltzef394fce2017-10-21 09:11:021002 // Apply starting sandbox flags.
Luna Luc3fdacdf2017-11-08 04:48:531003 blink::FramePolicy frame_policy(new_root->pending_frame_policy());
mark a. foltzef394fce2017-10-21 09:11:021004 frame_policy.sandbox_flags |= params.starting_sandbox_flags;
1005 new_root->SetPendingFramePolicy(frame_policy);
Charlie Hu5ffc0152019-12-06 15:59:531006 new_root->CommitFramePolicy(frame_policy);
mark a. foltzef394fce2017-10-21 09:11:021007
alexmose201c7cd2015-06-10 17:14:211008 // This may be true even when opener is null, such as when opening blocked
1009 // popups.
alexmos090fae8e2015-05-28 17:09:281010 if (params.created_with_opener)
1011 new_contents->created_with_opener_ = true;
1012
Sean Toppingbbc4a2bd2019-01-30 02:16:141013 WebContentsImpl* outer_web_contents = nullptr;
[email protected]4858e432014-06-23 18:14:171014 if (params.guest_delegate) {
[email protected]83100cd2014-05-10 11:50:061015 // This makes |new_contents| act as a guest.
1016 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:041017 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
1018 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:141019 outer_web_contents = static_cast<WebContentsImpl*>(
1020 params.guest_delegate->GetOwnerWebContents());
[email protected]83100cd2014-05-10 11:50:061021 }
mark a. foltzef394fce2017-10-21 09:11:021022
[email protected]54944cde2012-12-09 09:24:591023 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:141024 if (outer_web_contents)
1025 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:191026 return new_contents;
1027}
1028
[email protected]95640212014-07-26 18:14:301029// static
1030std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
1031 std::vector<WebContentsImpl*> result;
dcheng59716272016-04-09 05:19:081032 std::unique_ptr<RenderWidgetHostIterator> widgets(
[email protected]95640212014-07-26 18:14:301033 RenderWidgetHostImpl::GetRenderWidgetHosts());
[email protected]95640212014-07-26 18:14:301034 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
[email protected]95640212014-07-26 18:14:301035 RenderViewHost* rvh = RenderViewHost::From(rwh);
1036 if (!rvh)
1037 continue;
1038 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1039 if (!web_contents)
1040 continue;
avidf38c952015-10-27 13:45:131041 if (web_contents->GetRenderViewHost() != rvh)
1042 continue;
1043 // Because a WebContents can only have one current RVH at a time, there will
1044 // be no duplicate WebContents here.
1045 result.push_back(static_cast<WebContentsImpl*>(web_contents));
[email protected]95640212014-07-26 18:14:301046 }
1047 return result;
1048}
1049
clamya16aa8172015-05-26 13:07:251050// static
1051WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
paulmeyerfeafc2d2017-04-25 21:46:401052 const FrameTreeNode* frame_tree_node) {
clamya16aa8172015-05-26 13:07:251053 return static_cast<WebContentsImpl*>(
1054 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
1055}
1056
clamy0d32d6d2015-11-24 11:16:261057// static
Patrick Monette275a6f92b2020-01-09 21:05:041058WebContents* WebContentsImpl::FromRenderFrameHostID(
1059 GlobalFrameRoutingId render_frame_host_id) {
1060 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
1061 !BrowserThread::IsThreadInitialized(BrowserThread::UI));
Patrick Monette7364e6972020-01-09 22:56:021062 RenderFrameHost* render_frame_host =
1063 RenderFrameHost::FromID(render_frame_host_id);
1064 if (!render_frame_host)
1065 return nullptr;
1066
1067 return WebContents::FromRenderFrameHost(render_frame_host);
Patrick Monette275a6f92b2020-01-09 21:05:041068}
1069
1070// static
clamy0d32d6d2015-11-24 11:16:261071WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
1072 int render_frame_host_id) {
Patrick Monette7364e6972020-01-09 22:56:021073 return FromRenderFrameHostID(
1074 GlobalFrameRoutingId(render_process_host_id, render_frame_host_id));
clamy0d32d6d2015-11-24 11:16:261075}
1076
paulmeyerfeafc2d2017-04-25 21:46:401077// static
1078WebContentsImpl* WebContentsImpl::FromOuterFrameTreeNode(
1079 const FrameTreeNode* frame_tree_node) {
1080 return WebContentsImpl::FromFrameTreeNode(frame_tree_node)
1081 ->node_.GetInnerWebContentsInFrame(frame_tree_node);
1082}
1083
[email protected]b0936d22013-11-28 06:47:361084RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
[email protected]fa944cb82013-11-15 17:51:211085 return GetRenderManager();
[email protected]765187182012-01-11 23:59:281086}
1087
nicka0ac8382016-12-15 23:59:231088bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
[email protected]7bb761892012-07-20 09:32:471089 const IPC::Message& message) {
Alexander Timin90c20c32020-08-12 15:28:321090 for (auto& observer : observers_.observer_list()) {
Lukasz Anforowicz89f2c1b2017-08-30 21:36:461091 // TODO(nick, creis): https://crbug.com/758026: Replace all uses of this
1092 // variant of OnMessageReceived with the version that takes a
1093 // RenderFrameHost, and then delete it.
nicka0ac8382016-12-15 23:59:231094 if (observer.OnMessageReceived(message))
1095 return true;
[email protected]64ffefa2014-05-10 12:06:331096 }
[email protected]403415a2011-01-10 18:57:531097
Henrique Ferreiroba535472020-04-21 11:38:361098#if BUILDFLAG(ENABLE_PLUGINS)
[email protected]724159a2010-12-30 01:11:181099 bool handled = true;
nicka0ac8382016-12-15 23:59:231100 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host)
nicka0ac8382016-12-15 23:59:231101 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
1102 OnRequestPpapiBrokerPermission)
nicka0ac8382016-12-15 23:59:231103 IPC_MESSAGE_UNHANDLED(handled = false)
1104 IPC_END_MESSAGE_MAP()
nicka0ac8382016-12-15 23:59:231105 return handled;
Henrique Ferreiroba535472020-04-21 11:38:361106#else
1107 return false;
1108#endif
nicka0ac8382016-12-15 23:59:231109}
1110
1111bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
1112 const IPC::Message& message) {
Alexander Timin90c20c32020-08-12 15:28:321113 for (auto& observer : observers_.observer_list()) {
nicka0ac8382016-12-15 23:59:231114 if (observer.OnMessageReceived(message, render_frame_host))
1115 return true;
1116 }
1117
1118 bool handled = true;
brettw4b461082016-11-19 18:55:161119#if BUILDFLAG(ENABLE_PLUGINS)
Hiroki Nakagawa761b9b02020-07-13 11:12:021120 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
emaxxe70f5e12015-05-29 11:26:001121 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
1122 OnPepperInstanceCreated)
1123 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
1124 OnPepperInstanceDeleted)
tommyclie6633ca72014-10-31 00:40:421125 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
zqzhang181047e62016-07-01 13:37:171126 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
1127 OnPepperStartsPlayback)
1128 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
1129 OnPepperStopsPlayback)
tommyclie6633ca72014-10-31 00:40:421130 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
[email protected]724159a2010-12-30 01:11:181131 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]e44d1342014-05-16 21:29:331132 IPC_END_MESSAGE_MAP()
Hiroki Nakagawa761b9b02020-07-13 11:12:021133#else
1134 handled = false;
1135#endif
[email protected]724159a2010-12-30 01:11:181136
[email protected]724159a2010-12-30 01:11:181137 return handled;
1138}
1139
[email protected]d1198fd2012-08-13 22:50:191140NavigationControllerImpl& WebContentsImpl::GetController() {
[email protected]f5fa20e2011-12-21 22:35:561141 return controller_;
1142}
1143
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411144BrowserContext* WebContentsImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:551145 return controller_.GetBrowserContext();
[email protected]627e0512011-12-21 22:55:301146}
1147
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411148const GURL& WebContentsImpl::GetURL() {
Peter Boström101d7672018-12-15 00:43:591149 return GetVisibleURL();
[email protected]be1f56ab2011-12-22 06:55:311150}
1151
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411152const GURL& WebContentsImpl::GetVisibleURL() {
[email protected]c854a7e2013-05-21 16:42:241153 // We may not have a navigation entry yet.
[email protected]59167c22013-06-03 18:07:321154 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]c854a7e2013-05-21 16:42:241155 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1156}
1157
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411158const GURL& WebContentsImpl::GetLastCommittedURL() {
[email protected]c854a7e2013-05-21 16:42:241159 // We may not have a navigation entry yet.
1160 NavigationEntry* entry = controller_.GetLastCommittedEntry();
1161 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1162}
1163
[email protected]8ff00d72012-10-23 19:12:211164WebContentsDelegate* WebContentsImpl::GetDelegate() {
[email protected]be1f56ab2011-12-22 06:55:311165 return delegate_;
1166}
1167
[email protected]8ff00d72012-10-23 19:12:211168void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
[email protected]be1f56ab2011-12-22 06:55:311169 // TODO(cbentzel): remove this debugging code?
1170 if (delegate == delegate_)
1171 return;
1172 if (delegate_)
1173 delegate_->Detach(this);
1174 delegate_ = delegate;
[email protected]a6b73c62013-02-11 23:05:081175 if (delegate_) {
[email protected]be1f56ab2011-12-22 06:55:311176 delegate_->Attach(this);
[email protected]a6b73c62013-02-11 23:05:081177 // Ensure the visible RVH reflects the new delegate's preferences.
[email protected]86f98a22013-03-20 14:35:001178 if (view_)
[email protected]e85165c642014-06-10 14:34:311179 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Joel Einbinder848001c2017-09-19 21:39:311180 if (GetRenderViewHost())
1181 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]a6b73c62013-02-11 23:05:081182 }
[email protected]be1f56ab2011-12-22 06:55:311183}
1184
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411185RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
[email protected]94d0cc12013-12-18 00:07:411186 return frame_tree_.root()->current_frame_host();
[email protected]60eca4eb2013-12-06 00:02:161187}
1188
nick53d5cbf2015-04-23 22:50:141189RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
1190 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
1191 if (!focused_node)
1192 return nullptr;
1193 return focused_node->current_frame_host();
[email protected]9c9343b2014-03-08 02:56:071194}
1195
rob3e2a0732016-01-06 21:22:091196RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
creisf71a2632017-05-04 19:03:501197 int frame_tree_node_id,
1198 int process_id) {
1199 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1200
1201 // Sanity check that this is in the caller's expected process. Otherwise a
1202 // recent cross-process navigation may have led to a privilege change that the
1203 // caller is not expecting.
1204 if (!frame ||
1205 frame->current_frame_host()->GetProcess()->GetID() != process_id)
1206 return nullptr;
1207
1208 return frame->current_frame_host();
1209}
1210
1211RenderFrameHostImpl* WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId(
rob3e2a0732016-01-06 21:22:091212 int frame_tree_node_id) {
creisf71a2632017-05-04 19:03:501213 // Beware using this! The RenderFrameHost may have changed since the caller
1214 // obtained frame_tree_node_id.
rob3e2a0732016-01-06 21:22:091215 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1216 return frame ? frame->current_frame_host() : nullptr;
1217}
1218
[email protected]a86c0e962013-12-17 17:10:391219void WebContentsImpl::ForEachFrame(
Lei Zhangebcc6302018-01-12 19:46:451220 const base::RepeatingCallback<void(RenderFrameHost*)>& on_frame) {
dcheng57e39e22016-01-21 00:25:381221 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1222 on_frame.Run(node->current_frame_host());
1223 }
[email protected]a86c0e962013-12-17 17:10:391224}
1225
dchengafb53e22016-02-04 08:11:081226std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
Xuehui Xieb2300ae42020-06-09 20:25:051227 return GetAllFramesImpl(frame_tree_, /*include_pending=*/false);
1228}
1229
1230std::vector<RenderFrameHost*> WebContentsImpl::GetAllFramesIncludingPending() {
1231 return GetAllFramesImpl(frame_tree_, /*include_pending=*/true);
dchengafb53e22016-02-04 08:11:081232}
1233
lukaszacbdf52e2016-01-15 21:19:511234int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
Xuehui Xieb2300ae42020-06-09 20:25:051235 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/false, message);
1236}
lukasza1a9ab2422016-03-02 18:47:251237
Xuehui Xieb2300ae42020-06-09 20:25:051238int WebContentsImpl::SendToAllFramesIncludingPending(IPC::Message* message) {
1239 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/true, message);
[email protected]a86c0e962013-12-17 17:10:391240}
1241
lfgdb5c4ed2016-03-04 23:09:071242void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
alexmos136fd6e62016-08-15 20:58:411243 frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
lfgdb5c4ed2016-03-04 23:09:071244}
1245
Gyuyoung Kim877e86d2020-07-21 04:01:021246void WebContentsImpl::ExecutePageBroadcastMethod(
1247 PageBroadcastMethodCallback callback) {
1248 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
1249}
1250
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411251RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() {
[email protected]fa944cb82013-11-15 17:51:211252 return GetRenderManager()->current_host();
[email protected]be1f56ab2011-12-22 06:55:311253}
1254
creis89a0f782015-05-27 16:13:171255void WebContentsImpl::CancelActiveAndPendingDialogs() {
Evan Stade753fc202020-07-13 18:09:541256 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:531257 dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
Evan Stade753fc202020-07-13 18:09:541258 }
creis89a0f782015-05-27 16:13:171259 if (browser_plugin_embedder_)
1260 browser_plugin_embedder_->CancelGuestDialogs();
1261}
1262
naskoc0fceff2015-04-30 15:53:521263void WebContentsImpl::ClosePage() {
1264 GetRenderViewHost()->ClosePage();
1265}
1266
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411267RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() {
[email protected]fa944cb82013-11-15 17:51:211268 return GetRenderManager()->GetRenderWidgetHostView();
[email protected]be1f56ab2011-12-22 06:55:311269}
1270
lfg265a2672016-04-23 03:11:021271RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
1272 if (GetOuterWebContents())
1273 return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
1274 return GetRenderManager()->GetRenderWidgetHostView();
1275}
1276
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411277RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView() {
vmpstr6d9996c82017-02-23 00:43:251278 if (auto* widget_host = GetFullscreenRenderWidgetHost())
ekaramadaeb3c5c2016-11-09 03:22:351279 return widget_host->GetView();
1280 return nullptr;
[email protected]4aebbca2013-09-17 22:26:491281}
1282
[email protected]8ff00d72012-10-23 19:12:211283WebContentsView* WebContentsImpl::GetView() const {
[email protected]be1f56ab2011-12-22 06:55:311284 return view_.get();
1285}
1286
Mike Wasserman5a3cc61d2020-08-27 21:12:031287void WebContentsImpl::OnScreensChange(bool is_multi_screen_changed) {
1288 // Send |is_multi_screen_changed| events to all visible frames, but limit
1289 // other events to frames with the Window Placement permission. This obviates
1290 // the most pressing need for sites to poll isMultiScreen(), which is exposed
1291 // without explicit permission, while also protecting privacy.
1292 // TODO(crbug.com/1109989): Postpone events; refine utility/privacy balance.
Mike Wassermanb213b9352020-04-16 00:32:341293 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1294 RenderFrameHostImpl* rfh = node->current_frame_host();
Mike Wasserman5a3cc61d2020-08-27 21:12:031295 if ((is_multi_screen_changed &&
1296 rfh->GetVisibilityState() == PageVisibilityState::kVisible) ||
1297 WindowPlacementGranted(rfh)) {
1298 rfh->GetAssociatedLocalFrame()->OnScreensChange();
1299 }
Mike Wassermanb213b9352020-04-16 00:32:341300 }
1301}
1302
leon.han552e9de2017-02-09 14:37:301303void WebContentsImpl::OnScreenOrientationChange() {
1304 DCHECK(screen_orientation_provider_);
Lan Weif81c6e7c2020-02-12 16:46:091305 DidChangeScreenOrientation();
Becca Hughese9e27952018-06-25 17:08:271306 screen_orientation_provider_->OnOrientationChange();
leon.hane4db177a2017-02-07 14:19:161307}
1308
Alan Cutter92d59252019-03-29 02:32:331309base::Optional<SkColor> WebContentsImpl::GetThemeColor() {
Carlos Caballero1215f882019-10-29 15:58:431310 return GetRenderViewHost()->theme_color();
yusufod41c5f92015-03-06 00:14:281311}
1312
Alan Cutterd73a15d92020-08-21 07:12:451313base::Optional<SkColor> WebContentsImpl::GetBackgroundColor() {
1314 return GetRenderViewHost()->background_color();
1315}
1316
Doug Turner63f3c7b2017-07-29 05:10:011317void WebContentsImpl::SetAccessibilityMode(ui::AXMode mode) {
[email protected]95640212014-07-26 18:14:301318 if (mode == accessibility_mode_)
1319 return;
1320
dmazzonif8a31042016-12-03 00:52:131321 // Don't allow accessibility to be enabled for WebContents that are never
danakj77eb7e82020-01-09 19:38:461322 // user-visible, like background pages.
1323 if (IsNeverComposited())
dmazzonif8a31042016-12-03 00:52:131324 return;
1325
[email protected]95640212014-07-26 18:14:301326 accessibility_mode_ = mode;
dcheng57e39e22016-01-21 00:25:381327
1328 for (FrameTreeNode* node : frame_tree_.Nodes()) {
dmazzonif8a31042016-12-03 00:52:131329 UpdateAccessibilityModeOnFrame(node->current_frame_host());
clamy610c63b32017-12-22 15:05:181330 // Also update accessibility mode on the speculative RenderFrameHost for
1331 // this FrameTreeNode, if one exists.
Alex Moshchuk3d8a1f392017-10-24 19:01:261332 RenderFrameHost* speculative_frame_host =
1333 node->render_manager()->speculative_frame_host();
1334 if (speculative_frame_host)
1335 UpdateAccessibilityModeOnFrame(speculative_frame_host);
dcheng57e39e22016-01-21 00:25:381336 }
[email protected]95640212014-07-26 18:14:301337}
1338
Doug Turner63f3c7b2017-07-29 05:10:011339void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
1340 ui::AXMode new_mode(accessibility_mode_);
dougtcd3dad732017-03-14 03:26:231341 new_mode |= mode;
1342 SetAccessibilityMode(new_mode);
[email protected]95640212014-07-26 18:14:301343}
1344
Avi Drissman1e620f32018-03-16 13:57:291345// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
1346// Handles the callbacks from parallel snapshot requests to each frame,
1347// and feeds the results to an AXTreeCombiner, which converts them into a
1348// single combined accessibility tree.
1349class WebContentsImpl::AXTreeSnapshotCombiner
1350 : public base::RefCounted<AXTreeSnapshotCombiner> {
1351 public:
1352 explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
1353 : callback_(std::move(callback)) {}
1354
1355 AXTreeSnapshotCallback AddFrame(bool is_root) {
1356 // Adds a reference to |this|.
1357 return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
1358 is_root);
1359 }
1360
1361 void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
1362 combiner_.AddTree(snapshot, is_root);
1363 }
1364
1365 private:
1366 friend class base::RefCounted<AXTreeSnapshotCombiner>;
1367
1368 // This is called automatically after the last call to ReceiveSnapshot
1369 // when there are no more references to this object.
1370 ~AXTreeSnapshotCombiner() {
1371 combiner_.Combine();
1372 std::move(callback_).Run(combiner_.combined());
1373 }
1374
1375 ui::AXTreeCombiner combiner_;
1376 AXTreeSnapshotCallback callback_;
1377};
1378
1379void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
1380 ui::AXMode ax_mode) {
dmazzonid95ae842016-04-12 21:17:391381 // Send a request to each of the frames in parallel. Each one will return
1382 // an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
1383 // them into a single tree and call |callback| with that result, then
1384 // delete |combiner|.
Avi Drissman1e620f32018-03-16 13:57:291385 FrameTreeNode* root_node = frame_tree_.root();
tzik58faa742018-08-01 10:54:181386 auto combiner =
1387 base::MakeRefCounted<AXTreeSnapshotCombiner>(std::move(callback));
Avi Drissman1e620f32018-03-16 13:57:291388
tzik58faa742018-08-01 10:54:181389 RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner.get(), ax_mode);
Avi Drissman1e620f32018-03-16 13:57:291390}
1391
1392void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
1393 FrameTreeNode* root_node,
1394 AXTreeSnapshotCombiner* combiner,
1395 ui::AXMode ax_mode) {
dmazzonid95ae842016-04-12 21:17:391396 for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
Avi Drissman1e620f32018-03-16 13:57:291397 WebContentsImpl* inner_contents =
1398 node_.GetInnerWebContentsInFrame(frame_tree_node);
1399 if (inner_contents) {
1400 inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
1401 ax_mode);
1402 } else {
1403 bool is_root = frame_tree_node == root_node;
1404 frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
1405 combiner->AddFrame(is_root), ax_mode);
1406 }
dmazzonid95ae842016-04-12 21:17:391407 }
dmazzoni83ba5c82015-04-14 07:11:511408}
1409
Becca Hughes3b5a43482018-07-17 22:31:551410void WebContentsImpl::NotifyViewportFitChanged(
1411 blink::mojom::ViewportFit value) {
Alexander Timin90c20c32020-08-12 15:28:321412 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1413 observer->ViewportFitChanged(value);
1414 });
Becca Hughes3b5a43482018-07-17 22:31:551415}
1416
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411417FindRequestManager* WebContentsImpl::GetFindRequestManagerForTesting() {
Ehsan Karamad6beb2ea2018-11-25 18:15:131418 return GetFindRequestManager();
1419}
1420
mcnee336ea2c2017-05-23 22:50:591421#if !defined(OS_ANDROID)
akabac6bd1212018-06-25 20:10:481422void WebContentsImpl::UpdateZoom() {
1423 RenderWidgetHostImpl* rwh = GetRenderViewHost()->GetWidget();
1424 if (rwh->GetView())
1425 rwh->SynchronizeVisualProperties();
wjmaclean64951902016-04-29 20:59:121426}
1427
wjmaclean64951902016-04-29 20:59:121428
1429void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
akabac6bd1212018-06-25 20:10:481430 const std::string& host) {
wjmaclean64951902016-04-29 20:59:121431 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1432 if (!entry)
1433 return;
1434
1435 GURL url = HostZoomMap::GetURLFromEntry(entry);
1436 if (host != net::GetHostOrSpecFromURL(url) ||
1437 (!scheme.empty() && !url.SchemeIs(scheme))) {
1438 return;
1439 }
1440
akabac6bd1212018-06-25 20:10:481441 UpdateZoom();
wjmaclean64951902016-04-29 20:59:121442}
mcnee336ea2c2017-05-23 22:50:591443#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:121444
Julie Jeongeun Kim7d0986172019-12-04 03:17:251445base::OnceClosure WebContentsImpl::AddReceiverSet(
rockotf62002a2016-09-15 00:08:591446 const std::string& interface_name,
Julie Jeongeun Kim7d0986172019-12-04 03:17:251447 WebContentsReceiverSet* receiver_set) {
rockotf62002a2016-09-15 00:08:591448 auto result =
Julie Jeongeun Kim7d0986172019-12-04 03:17:251449 receiver_sets_.insert(std::make_pair(interface_name, receiver_set));
rockotf62002a2016-09-15 00:08:591450 DCHECK(result.second);
Julie Jeongeun Kim7d0986172019-12-04 03:17:251451 return base::BindOnce(&WebContentsImpl::RemoveReceiverSet,
danakjf4b9e942019-11-29 15:43:041452 weak_factory_.GetWeakPtr(), interface_name);
rockotf62002a2016-09-15 00:08:591453}
1454
Julie Jeongeun Kim7d0986172019-12-04 03:17:251455WebContentsReceiverSet* WebContentsImpl::GetReceiverSet(
rockot8bbad222017-03-22 04:34:051456 const std::string& interface_name) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:251457 auto it = receiver_sets_.find(interface_name);
1458 if (it == receiver_sets_.end())
rockot8bbad222017-03-22 04:34:051459 return nullptr;
1460 return it->second;
1461}
1462
John Delaney732721e92020-02-07 23:11:271463void WebContentsImpl::RemoveReceiverSetForTesting(
1464 const std::string& interface_name) {
1465 RemoveReceiverSet(interface_name);
1466}
1467
paulmeyerfeafc2d2017-04-25 21:46:401468std::vector<WebContentsImpl*> WebContentsImpl::GetWebContentsAndAllInner() {
1469 std::vector<WebContentsImpl*> all_contents(1, this);
1470
1471 for (size_t i = 0; i != all_contents.size(); ++i) {
1472 for (auto* inner_contents : all_contents[i]->GetInnerWebContents()) {
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:161473 all_contents.push_back(static_cast<WebContentsImpl*>(inner_contents));
paulmeyerfeafc2d2017-04-25 21:46:401474 }
1475 }
1476
1477 return all_contents;
1478}
1479
Sam McNally145fb172017-05-10 00:13:231480void WebContentsImpl::NotifyManifestUrlChanged(
Yuzu Saijo0c263c702020-06-08 03:41:241481 RenderFrameHost* rfh,
Sam McNally145fb172017-05-10 00:13:231482 const base::Optional<GURL>& manifest_url) {
Alexander Timin90c20c32020-08-12 15:28:321483 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1484 observer->DidUpdateWebManifestURL(rfh, manifest_url);
1485 });
Sam McNally145fb172017-05-10 00:13:231486}
1487
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411488WebUI* WebContentsImpl::GetWebUI() {
Nasko Oskov2f7d2112019-10-29 03:26:571489 WebUI* committed_web_ui = GetCommittedWebUI();
1490 if (committed_web_ui)
1491 return committed_web_ui;
1492
1493 if (GetRenderManager()->speculative_frame_host())
1494 return GetRenderManager()->speculative_frame_host()->web_ui();
1495
1496 return nullptr;
[email protected]be1f56ab2011-12-22 06:55:311497}
1498
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411499WebUI* WebContentsImpl::GetCommittedWebUI() {
carlosk35f35af2015-12-01 10:55:401500 return frame_tree_.root()->current_frame_host()->web_ui();
[email protected]d5f942ba2008-09-26 19:30:341501}
1502
Maks Orlovich73f374d2020-04-02 12:46:131503void WebContentsImpl::SetUserAgentOverride(
1504 const blink::UserAgentOverride& ua_override,
1505 bool override_in_new_tabs) {
1506 DCHECK(!ua_override.ua_metadata_override.has_value() ||
1507 !ua_override.ua_string_override.empty());
1508
1509 if (GetUserAgentOverride() == ua_override)
[email protected]bf70edce2012-06-20 22:32:221510 return;
1511
Changwan Ryuc1134a82018-03-07 02:10:141512 should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
1513
Maks Orlovich73f374d2020-04-02 12:46:131514 renderer_preferences_.user_agent_override = ua_override;
[email protected]bf70edce2012-06-20 22:32:221515
Bruce Long1e3e1f542019-10-16 17:56:281516 // Send the new override string to all renderers in the current page.
1517 SyncRendererPrefs();
[email protected]bf70edce2012-06-20 22:32:221518
1519 // Reload the page if a load is currently in progress to avoid having
1520 // different parts of the page loaded using different user agents.
Scott Violete1d58cc2020-04-28 23:07:171521 // No need to reload if the current entry matches that of the
1522 // NavigationRequest supplied to DidStartNavigation() as NavigationRequest
1523 // handles it.
[email protected]6286a372013-10-09 04:03:271524 NavigationEntry* entry = controller_.GetVisibleEntry();
Scott Violete1d58cc2020-04-28 23:07:171525 if (IsLoading() && entry != nullptr && entry->GetIsOverridingUserAgent() &&
1526 (!frame_tree_.root()->navigation_request() ||
1527 frame_tree_.root()->navigation_request()->ua_change_requires_reload())) {
toyoshim6142d96f2016-12-19 09:07:251528 controller_.Reload(ReloadType::BYPASSING_CACHE, true);
Scott Violete1d58cc2020-04-28 23:07:171529 }
[email protected]8d0f3312012-08-18 01:47:531530
Alexander Timin90c20c32020-08-12 15:28:321531 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1532 observer->UserAgentOverrideSet(ua_override);
1533 });
[email protected]86ef6a392012-05-11 22:03:111534}
1535
Scott Violet2a6c5bff2020-04-29 23:59:061536void WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption(
1537 NavigationController::UserAgentOverrideOption option) {
1538 renderer_initiated_user_agent_override_option_ = option;
1539}
1540
Maks Orlovich73f374d2020-04-02 12:46:131541const blink::UserAgentOverride& WebContentsImpl::GetUserAgentOverride() {
[email protected]bf70edce2012-06-20 22:32:221542 return renderer_preferences_.user_agent_override;
[email protected]86ef6a392012-05-11 22:03:111543}
1544
Scott Violet2a6c5bff2020-04-29 23:59:061545bool WebContentsImpl::ShouldOverrideUserAgentForRendererInitiatedNavigation() {
1546 NavigationEntryImpl* current_entry = controller_.GetLastCommittedEntry();
1547 if (!current_entry)
1548 return should_override_user_agent_in_new_tabs_;
1549
1550 switch (renderer_initiated_user_agent_override_option_) {
1551 case NavigationController::UA_OVERRIDE_INHERIT:
1552 return current_entry->GetIsOverridingUserAgent();
1553 case NavigationController::UA_OVERRIDE_TRUE:
1554 return true;
1555 case NavigationController::UA_OVERRIDE_FALSE:
1556 return false;
1557 default:
1558 break;
1559 }
1560 return false;
Changwan Ryuc1134a82018-03-07 02:10:141561}
1562
dmazzonidd3d51a72016-12-14 18:41:011563void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
Dominic Mazzonid9fda172019-03-07 17:12:071564 // If accessibility is already enabled, we'll need to force a reset
1565 // in order to ensure new observers of accessibility events get the
1566 // full accessibility tree from scratch.
1567 bool need_reset = GetAccessibilityMode().has_mode(ui::AXMode::kWebContents);
1568
1569 ui::AXMode desired_mode =
1570 GetContentClient()->browser()->GetAXModeForBrowserContext(
1571 GetBrowserContext());
1572 desired_mode |= ui::kAXModeWebContentsOnly;
1573 AddAccessibilityMode(desired_mode);
1574
1575 if (need_reset) {
dchengafb53e22016-02-04 08:11:081576 for (RenderFrameHost* rfh : GetAllFrames())
1577 ResetAccessibility(rfh);
dchengafb53e22016-02-04 08:11:081578 }
[email protected]95640212014-07-26 18:14:301579}
1580
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411581bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011582 return accessibility_mode_ == ui::kAXModeWebContentsOnly;
[email protected]95640212014-07-26 18:14:301583}
1584
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411585bool WebContentsImpl::IsFullAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011586 return accessibility_mode_ == ui::kAXModeComplete;
[email protected]95640212014-07-26 18:14:301587}
1588
Becca Hughes6daf5662018-06-27 16:50:541589#if defined(OS_ANDROID)
1590
1591void WebContentsImpl::SetDisplayCutoutSafeArea(gfx::Insets insets) {
Becca Hughes86334622018-07-09 21:29:381592 if (display_cutout_host_impl_)
1593 display_cutout_host_impl_->SetDisplayCutoutSafeArea(insets);
Becca Hughes6daf5662018-06-27 16:50:541594}
1595
1596#endif
1597
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411598const base::string16& WebContentsImpl::GetTitle() {
Nasko Oskov2f7d2112019-10-29 03:26:571599 WebUI* our_web_ui =
1600 GetRenderManager()->speculative_frame_host()
1601 ? GetRenderManager()->speculative_frame_host()->web_ui()
1602 : GetRenderManager()->current_frame_host()->web_ui();
[email protected]7ade2732011-02-10 00:13:581603 if (our_web_ui) {
[email protected]96d185d2009-04-24 03:28:541604 // Don't override the title in view source mode.
Carlos IL4dea8902020-05-26 15:14:291605 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]96d185d2009-04-24 03:28:541606 if (!(entry && entry->IsViewSourceMode())) {
[email protected]e0112912011-02-02 22:54:351607 // Give the Web UI the chance to override our title.
[email protected]fcf75d42013-12-03 20:11:261608 const base::string16& title = our_web_ui->GetOverriddenTitle();
[email protected]96d185d2009-04-24 03:28:541609 if (!title.empty())
1610 return title;
1611 }
1612 }
1613
1614 // We use the title for the last committed entry rather than a pending
1615 // navigation entry. For example, when the user types in a URL, we want to
1616 // keep the old page's title until the new load has committed and we get a new
1617 // title.
Carlos IL4dea8902020-05-26 15:14:291618 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]59167c22013-06-03 18:07:321619
creis072b61f2015-09-28 20:52:241620 // We make an exception for initial navigations. We only want to use the title
1621 // from the visible entry if:
1622 // 1. The pending entry has been explicitly assigned a title to display.
1623 // 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
1624 // which case there is a pending entry index other than -1.
1625 //
1626 // Otherwise, we want to stick with the last committed entry's title during
1627 // new navigations, which have pending entries at index -1 with no title.
1628 if (controller_.IsInitialNavigation() &&
1629 ((controller_.GetVisibleEntry() &&
1630 !controller_.GetVisibleEntry()->GetTitle().empty()) ||
1631 controller_.GetPendingEntryIndex() != -1)) {
1632 entry = controller_.GetVisibleEntry();
[email protected]9eeafc012013-11-25 23:49:471633 }
[email protected]59167c22013-06-03 18:07:321634
[email protected]45d0ef7f2011-01-05 13:46:231635 if (entry) {
jshin1fb76462016-04-05 22:13:031636 return entry->GetTitleForDisplay();
[email protected]45d0ef7f2011-01-05 13:46:231637 }
[email protected]987fc3a2011-05-26 14:18:091638
1639 // |page_title_when_no_navigation_entry_| is finally used
1640 // if no title cannot be retrieved.
1641 return page_title_when_no_navigation_entry_;
[email protected]96d185d2009-04-24 03:28:541642}
1643
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411644SiteInstanceImpl* WebContentsImpl::GetSiteInstance() {
[email protected]fa944cb82013-11-15 17:51:211645 return GetRenderManager()->current_host()->GetSiteInstance();
[email protected]96d185d2009-04-24 03:28:541646}
1647
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411648bool WebContentsImpl::IsLoading() {
Carlos ILd51e7702020-05-07 18:51:391649 return frame_tree_.IsLoading();
[email protected]3c9e1872010-11-18 16:17:491650}
1651
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411652double WebContentsImpl::GetLoadProgress() {
Peter Boström18a40fa2018-10-31 19:03:501653 return frame_tree_.load_progress();
1654}
1655
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411656bool WebContentsImpl::IsLoadingToDifferentDocument() {
clamy44e84ce2016-02-22 15:38:251657 return IsLoading() && is_load_to_different_document_;
[email protected]6dfed692014-05-22 04:18:031658}
1659
Alexander Timindd0fa0c52019-11-06 13:03:371660bool WebContentsImpl::IsDocumentOnLoadCompletedInMainFrame() {
1661 return GetRenderViewHost()->IsDocumentOnLoadCompletedInMainFrame();
1662}
1663
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411664bool WebContentsImpl::IsWaitingForResponse() {
Peter Boströma9a27f6e2018-11-21 13:12:191665 NavigationRequest* ongoing_navigation_request =
1666 frame_tree_.root()->navigation_request();
1667
1668 // An ongoing navigation request means we're waiting for a response.
1669 return ongoing_navigation_request != nullptr;
[email protected]be1f56ab2011-12-22 06:55:311670}
1671
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411672const net::LoadStateWithParam& WebContentsImpl::GetLoadState() {
[email protected]be1f56ab2011-12-22 06:55:311673 return load_state_;
1674}
1675
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411676const base::string16& WebContentsImpl::GetLoadStateHost() {
[email protected]be1f56ab2011-12-22 06:55:311677 return load_state_host_;
1678}
1679
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411680uint64_t WebContentsImpl::GetUploadSize() {
[email protected]be1f56ab2011-12-22 06:55:311681 return upload_size_;
1682}
1683
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411684uint64_t WebContentsImpl::GetUploadPosition() {
[email protected]be1f56ab2011-12-22 06:55:311685 return upload_position_;
1686}
1687
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411688const std::string& WebContentsImpl::GetEncoding() {
Alexander Timine5f20e22019-10-09 23:22:351689 return GetMainFrame()->GetEncoding();
[email protected]be1f56ab2011-12-22 06:55:311690}
1691
Charles Zhaod72f99d2018-09-17 14:18:271692bool WebContentsImpl::WasDiscarded() {
1693 return GetFrameTree()->root()->was_discarded();
1694}
1695
Shubhie Panickerddf2a4e2018-03-06 00:09:061696void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
1697 GetFrameTree()->root()->set_was_discarded();
1698}
1699
Collin Bakerc5259962019-11-14 17:51:581700void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size,
1701 bool stay_hidden) {
[email protected]5a652232013-02-12 06:15:251702 DCHECK(!is_being_destroyed_);
Xianzhu Wang724e08f2020-09-01 21:35:071703 if (stay_hidden) {
1704 // A hidden capture should not have side effect on the web contents, so it
1705 // should not pass a non-empty |capture_size| which will cause side effect.
1706 DCHECK(capture_size.IsEmpty());
Collin Bakerc5259962019-11-14 17:51:581707 ++hidden_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071708 } else {
Collin Bakerc5259962019-11-14 17:51:581709 ++visible_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071710 }
[email protected]222f5822014-02-05 23:40:491711
1712 // Note: This provides a hint to upstream code to size the views optimally
1713 // for quality (e.g., to avoid scaling).
1714 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1715 preferred_size_for_capture_ = capture_size;
1716 OnPreferredSizeChanged(preferred_size_);
1717 }
ccameron8807c38f2015-01-17 00:29:191718
Collin Bakerc5259962019-11-14 17:51:581719 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]54597982013-02-06 01:59:551720}
1721
Collin Bakerc5259962019-11-14 17:51:581722void WebContentsImpl::DecrementCapturerCount(bool stay_hidden) {
1723 if (stay_hidden)
1724 --hidden_capturer_count_;
1725 else
1726 --visible_capturer_count_;
1727 DCHECK_GE(hidden_capturer_count_, 0);
1728 DCHECK_GE(visible_capturer_count_, 0);
[email protected]54597982013-02-06 01:59:551729
[email protected]5a652232013-02-12 06:15:251730 if (is_being_destroyed_)
1731 return;
1732
Francois Doray24fc62c2017-12-11 17:27:331733 if (!IsBeingCaptured()) {
[email protected]222f5822014-02-05 23:40:491734 const gfx::Size old_size = preferred_size_for_capture_;
1735 preferred_size_for_capture_ = gfx::Size();
1736 OnPreferredSizeChanged(old_size);
[email protected]54597982013-02-06 01:59:551737 }
Collin Bakerc5259962019-11-14 17:51:581738
1739 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]be1f56ab2011-12-22 06:55:311740}
1741
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411742bool WebContentsImpl::IsBeingCaptured() {
Collin Bakerc5259962019-11-14 17:51:581743 return visible_capturer_count_ + hidden_capturer_count_ > 0;
[email protected]f2bd40812013-07-20 04:30:441744}
1745
Xianzhu Wangc61434c2020-08-21 19:17:301746bool WebContentsImpl::IsBeingVisiblyCaptured() {
1747 return visible_capturer_count_ > 0;
1748}
1749
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411750bool WebContentsImpl::IsAudioMuted() {
Guido Urdanetaf8372942019-11-15 09:47:211751 return audio_stream_factory_ && audio_stream_factory_->IsMuted();
miu50f97892014-09-22 22:49:521752}
1753
1754void WebContentsImpl::SetAudioMuted(bool mute) {
1755 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1756 << " for WebContentsImpl@" << this;
1757
1758 if (mute == IsAudioMuted())
1759 return;
1760
Guido Urdanetaf8372942019-11-15 09:47:211761 GetAudioStreamFactory()->SetMuted(mute);
miu50f97892014-09-22 22:49:521762
Alexander Timin90c20c32020-08-12 15:28:321763 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1764 observer->DidUpdateAudioMutingState(mute);
1765 });
Jan Rucka442c83f2017-08-08 13:27:541766 // Notification for UI updates in response to the changed muting state.
Collin Bakeraf540cf2019-09-20 20:54:161767 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541768}
1769
1770bool WebContentsImpl::IsCurrentlyAudible() {
Chris Hamiltondf0d72cd2018-05-29 16:23:531771 return is_currently_audible_;
miu50f97892014-09-22 22:49:521772}
1773
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411774bool WebContentsImpl::IsConnectedToBluetoothDevice() {
ortunodf4d7982016-04-08 02:33:351775 return bluetooth_connected_device_count_ > 0;
ortuno32e7db3c2016-03-29 16:14:201776}
1777
Ovidio Henriquez76696f62020-07-08 03:06:591778bool WebContentsImpl::IsScanningForBluetoothDevices() {
1779 return bluetooth_scanning_sessions_count_ > 0;
1780}
1781
Lucas Furukawa Gadani4b4eed02019-06-04 23:12:041782bool WebContentsImpl::IsConnectedToSerialPort() {
Reilly Grant5e7c79b22019-04-09 17:26:201783 return serial_active_frame_count_ > 0;
1784}
1785
Matt Reynoldse8c6c1f2019-11-02 09:53:531786bool WebContentsImpl::IsConnectedToHidDevice() {
1787 return hid_active_frame_count_ > 0;
1788}
1789
Marijn Kruisselbrink29051042019-08-06 22:56:551790bool WebContentsImpl::HasNativeFileSystemHandles() {
1791 return native_file_system_handle_count_ > 0;
1792}
Marijn Kruisselbrinkf1714aa22019-07-02 03:45:331793
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411794bool WebContentsImpl::HasPictureInPictureVideo() {
sawtellea7333a82018-05-31 02:36:361795 return has_picture_in_picture_video_;
1796}
1797
1798void WebContentsImpl::SetHasPictureInPictureVideo(
1799 bool has_picture_in_picture_video) {
1800 // If status of |this| is already accurate, there is no need to update.
1801 if (has_picture_in_picture_video == has_picture_in_picture_video_)
1802 return;
1803 has_picture_in_picture_video_ = has_picture_in_picture_video;
1804 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:321805 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1806 observer->MediaPictureInPictureChanged(has_picture_in_picture_video_);
1807 });
sawtellea7333a82018-05-31 02:36:361808}
1809
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411810bool WebContentsImpl::IsCrashed() {
Dominic Mazzoni73a48322018-05-25 18:14:071811 switch (crashed_status_) {
1812 case base::TERMINATION_STATUS_PROCESS_CRASHED:
1813 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
1814 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
1815 case base::TERMINATION_STATUS_OOM:
1816 case base::TERMINATION_STATUS_LAUNCH_FAILED:
Darin Fisher6cf20e782020-08-07 22:25:361817#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
Dominic Mazzoni73a48322018-05-25 18:14:071818 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
oshima620225722015-06-04 19:45:271819#endif
Dominic Mazzoni73a48322018-05-25 18:14:071820#if defined(OS_ANDROID)
1821 case base::TERMINATION_STATUS_OOM_PROTECTED:
1822#endif
Will Harris07925d12019-10-31 03:03:051823#if defined(OS_WIN)
1824 case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
1825#endif
Dominic Mazzoni73a48322018-05-25 18:14:071826 return true;
1827 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
1828 case base::TERMINATION_STATUS_STILL_RUNNING:
1829 return false;
1830 case base::TERMINATION_STATUS_MAX_ENUM:
1831 NOTREACHED();
1832 return false;
1833 }
1834
1835 NOTREACHED();
1836 return false;
[email protected]3c9e1872010-11-18 16:17:491837}
1838
[email protected]b172aee2012-04-10 17:05:261839void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1840 int error_code) {
[email protected]443b80e2010-12-14 00:42:231841 if (status == crashed_status_)
[email protected]d5f942ba2008-09-26 19:30:341842 return;
1843
[email protected]443b80e2010-12-14 00:42:231844 crashed_status_ = status;
1845 crashed_error_code_ = error_code;
[email protected]8ff00d72012-10-23 19:12:211846 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
[email protected]d5f942ba2008-09-26 19:30:341847}
1848
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411849base::TerminationStatus WebContentsImpl::GetCrashedStatus() {
[email protected]be1f56ab2011-12-22 06:55:311850 return crashed_status_;
1851}
1852
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411853int WebContentsImpl::GetCrashedErrorCode() {
afakhry98241832016-03-11 19:27:471854 return crashed_error_code_;
1855}
1856
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411857bool WebContentsImpl::IsBeingDestroyed() {
[email protected]be1f56ab2011-12-22 06:55:311858 return is_being_destroyed_;
1859}
1860
[email protected]7f924832014-08-09 05:57:221861void WebContentsImpl::NotifyNavigationStateChanged(
1862 InvalidateTypes changed_flags) {
dalecurtis88c240072015-12-09 02:11:181863 // Notify the media observer of potential audibility changes.
Collin Bakeraf540cf2019-09-20 20:54:161864 if (changed_flags & INVALIDATE_TYPE_AUDIO) {
mlamouri44e4ef42016-01-20 18:42:271865 media_web_contents_observer_->MaybeUpdateAudibleState();
dalecurtisbc6572e12014-09-12 19:22:301866 }
1867
[email protected]d5f942ba2008-09-26 19:30:341868 if (delegate_)
1869 delegate_->NavigationStateChanged(this, changed_flags);
wjmaclean1dabf3e32016-05-13 23:34:441870
1871 if (GetOuterWebContents())
1872 GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
[email protected]d5f942ba2008-09-26 19:30:341873}
1874
W. James MacLean6f34b042019-07-12 19:25:301875RenderFrameHostImpl* WebContentsImpl::GetFocusedFrameFromFocusedDelegate() {
1876 FrameTreeNode* focused_node =
1877 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
1878 return focused_node ? focused_node->current_frame_host() : nullptr;
1879}
1880
David Black9cca3592019-11-06 23:02:221881void WebContentsImpl::OnVerticalScrollDirectionChanged(
1882 viz::VerticalScrollDirection scroll_direction) {
Alexander Timin90c20c32020-08-12 15:28:321883 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1884 observer->DidChangeVerticalScrollDirection(scroll_direction);
1885 });
David Black9cca3592019-11-06 23:02:221886}
1887
Chris Hamiltondf0d72cd2018-05-29 16:23:531888void WebContentsImpl::OnAudioStateChanged() {
1889 // This notification can come from any embedded contents or from this
1890 // WebContents' stream monitor. Aggregate these signals to get the actual
1891 // state.
Jeremy Roman03ce13ce2020-05-29 22:16:571892 //
1893 // Note that guests may not be attached as inner contents, and so may need to
1894 // be checked separately.
Chris Hamiltondf0d72cd2018-05-29 16:23:531895 bool is_currently_audible =
1896 audio_stream_monitor_.IsCurrentlyAudible() ||
1897 (browser_plugin_embedder_ &&
Jeremy Roman03ce13ce2020-05-29 22:16:571898 browser_plugin_embedder_->AreAnyGuestsCurrentlyAudible()) ||
1899 AnyInnerWebContents(this, [](WebContents* inner_contents) {
1900 return inner_contents->IsCurrentlyAudible();
1901 });
Chris Hamiltondf0d72cd2018-05-29 16:23:531902 if (is_currently_audible == is_currently_audible_)
1903 return;
1904
1905 // Update internal state.
1906 is_currently_audible_ = is_currently_audible;
1907 was_ever_audible_ = was_ever_audible_ || is_currently_audible_;
1908
Gyuyoung Kim877e86d2020-07-21 04:01:021909 ExecutePageBroadcastMethod(base::BindRepeating(
1910 [](bool is_currently_audible, RenderViewHostImpl* rvh) {
1911 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
1912 broadcast->AudioStateChanged(is_currently_audible);
1913 },
1914 is_currently_audible_));
altimind8bd26c2016-11-04 11:44:541915
altiminec87fd1f2016-11-17 20:22:491916 // Notification for UI updates in response to the changed audio state.
Collin Bakeraf540cf2019-09-20 20:54:161917 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541918
Chris Hamiltondf0d72cd2018-05-29 16:23:531919 // Ensure that audio state changes propagate from innermost to outermost
1920 // WebContents.
1921 if (GetOuterWebContents())
1922 GetOuterWebContents()->OnAudioStateChanged();
Tommy Steimel18360512017-11-01 00:38:191923
Alexander Timin90c20c32020-08-12 15:28:321924 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1925 observer->OnAudioStateChanged(is_currently_audible_);
1926 });
altimind8bd26c2016-11-04 11:44:541927}
1928
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411929base::TimeTicks WebContentsImpl::GetLastActiveTime() {
[email protected]9a890452014-02-13 22:21:021930 return last_active_time_;
[email protected]3e324142012-06-25 18:26:331931}
1932
[email protected]9e2e4632012-07-27 16:38:411933void WebContentsImpl::WasShown() {
Collin Baker989e0882019-11-01 01:27:171934 UpdateVisibilityAndNotifyPageAndView(Visibility::VISIBLE);
[email protected]be1f56ab2011-12-22 06:55:311935}
1936
[email protected]b172aee2012-04-10 17:05:261937void WebContentsImpl::WasHidden() {
Collin Baker989e0882019-11-01 01:27:171938 UpdateVisibilityAndNotifyPageAndView(Visibility::HIDDEN);
[email protected]375fa1b2012-05-22 22:05:371939}
1940
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411941bool WebContentsImpl::HasRecentInteractiveInputEvent() {
Daniel Cheng90196c82018-04-25 21:49:141942 static constexpr base::TimeDelta kMaxInterval =
1943 base::TimeDelta::FromSeconds(5);
1944 base::TimeDelta delta =
1945 ui::EventTimeForNow() - last_interactive_input_event_time_;
1946 // Note: the expectation is that the caller is typically expecting an input
1947 // event, e.g. validating that a WebUI message that requires a gesture is
Daniel Chenge81030b32019-07-17 20:20:231948 // actually attached to a gesture.
Daniel Cheng90196c82018-04-25 21:49:141949 return delta <= kMaxInterval;
1950}
1951
Avi Drissman738ea192018-08-29 20:24:161952void WebContentsImpl::SetIgnoreInputEvents(bool ignore_input_events) {
1953 ignore_input_events_ = ignore_input_events;
1954}
1955
Bo Liu168c8642017-08-28 18:26:021956#if defined(OS_ANDROID)
Bo Liu16dd7b8322018-05-02 21:19:501957void WebContentsImpl::SetMainFrameImportance(
1958 ChildProcessImportance importance) {
1959 GetMainFrame()->GetRenderWidgetHost()->SetImportance(importance);
Bo Liu7c6779e92017-08-16 02:02:281960}
Bo Liu168c8642017-08-28 18:26:021961#endif
Bo Liu7c6779e92017-08-16 02:02:281962
ccameron8807c38f2015-01-17 00:29:191963void WebContentsImpl::WasOccluded() {
Collin Baker989e0882019-11-01 01:27:171964 UpdateVisibilityAndNotifyPageAndView(Visibility::OCCLUDED);
ccameron8807c38f2015-01-17 00:29:191965}
1966
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411967Visibility WebContentsImpl::GetVisibility() {
Francois Doraye6161152018-03-27 22:05:371968 return visibility_;
Francois Dorayfe4a1772018-02-17 04:17:091969}
1970
Rakina Zata Amni26e8d8a2020-08-05 06:06:061971bool WebContentsImpl::NeedToFireBeforeUnloadOrUnloadEvents() {
Alexander Timinc7bee322020-05-19 17:54:341972 if (!notify_disconnection_)
Alex Moshchuk6fcaca752018-07-14 02:13:591973 return false;
1974
1975 // Don't fire if the main frame's RenderViewHost indicates that beforeunload
1976 // and unload have already executed (e.g., after receiving a ClosePage ACK)
1977 // or should be ignored.
1978 if (GetRenderViewHost()->SuddenTerminationAllowed())
1979 return false;
1980
Alex Moshchukc78dbc722019-10-31 20:00:501981 // Check whether any frame in the frame tree needs to run beforeunload or
Rakina Zata Amni26e8d8a2020-08-05 06:06:061982 // unload-time event handlers.
Alex Moshchukc78dbc722019-10-31 20:00:501983 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1984 RenderFrameHostImpl* rfh = node->current_frame_host();
1985
Rakina Zata Amni26e8d8a2020-08-05 06:06:061986 // No need to run beforeunload/unload-time events if the RenderFrame isn't
1987 // live.
Alex Moshchukc78dbc722019-10-31 20:00:501988 if (!rfh->IsRenderFrameLive())
1989 continue;
Rakina Zata Amni26e8d8a2020-08-05 06:06:061990 bool should_run_before_unload_handler =
Dave Tapuska97d22ab2019-12-03 17:56:361991 rfh->GetSuddenTerminationDisablerState(
Rakina Zata Amni26e8d8a2020-08-05 06:06:061992 blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
1993 bool should_run_unload_handler = rfh->GetSuddenTerminationDisablerState(
1994 blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
1995 bool should_run_page_hide_handler = rfh->GetSuddenTerminationDisablerState(
1996 blink::mojom::SuddenTerminationDisablerType::kPageHideHandler);
1997 auto* rvh = static_cast<RenderViewHostImpl*>(rfh->GetRenderViewHost());
1998 // If the tab is already hidden, we should not run visibilitychange
1999 // handlers.
2000 bool is_page_visible = rvh->GetPageLifecycleStateManager()
2001 ->CalculatePageLifecycleState()
2002 ->visibility == PageVisibilityState::kVisible;
2003
2004 bool should_run_visibility_change_handler =
2005 is_page_visible && rfh->GetSuddenTerminationDisablerState(
2006 blink::mojom::SuddenTerminationDisablerType::
2007 kVisibilityChangeHandler);
2008 if (should_run_before_unload_handler || should_run_unload_handler ||
2009 should_run_page_hide_handler || should_run_visibility_change_handler) {
Alex Moshchukc78dbc722019-10-31 20:00:502010 return true;
2011 }
Aditya Keerthi34f37e62019-03-08 15:54:532012 }
Alex Moshchuk6fcaca752018-07-14 02:13:592013
Alex Moshchukc78dbc722019-10-31 20:00:502014 return false;
[email protected]be1f56ab2011-12-22 06:55:312015}
2016
Chris Hamilton3b3e315d2018-09-19 13:16:212017void WebContentsImpl::DispatchBeforeUnload(bool auto_cancel) {
2018 auto before_unload_type =
2019 auto_cancel ? RenderFrameHostImpl::BeforeUnloadType::DISCARD
2020 : RenderFrameHostImpl::BeforeUnloadType::TAB_CLOSE;
2021 GetMainFrame()->DispatchBeforeUnload(before_unload_type, false);
[email protected]1c3f80bd2014-04-08 23:02:062022}
2023
W. James MacLean2539adb32019-12-13 00:40:442024bool WebContentsImpl::IsInnerWebContentsForGuest() {
2025 return !!browser_plugin_guest_;
2026}
2027
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502028void WebContentsImpl::AttachInnerWebContents(
2029 std::unique_ptr<WebContents> inner_web_contents,
W. James MacLean62883982019-11-12 20:39:002030 RenderFrameHost* render_frame_host,
2031 bool is_full_page) {
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502032 WebContentsImpl* inner_web_contents_impl =
2033 static_cast<WebContentsImpl*>(inner_web_contents.get());
2034 DCHECK(!inner_web_contents_impl->node_.outer_web_contents());
2035 auto* render_frame_host_impl =
2036 static_cast<RenderFrameHostImpl*>(render_frame_host);
Fergal Daly445af932020-06-02 06:37:232037 DCHECK_EQ(&frame_tree_, render_frame_host_impl->frame_tree());
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392038
Yuzu Saijo3f86fb22020-06-11 03:51:102039 // Mark |render_frame_host_impl| as outer delegate frame.
2040 render_frame_host_impl->SetIsOuterDelegateFrame(true);
2041
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502042 RenderFrameHostManager* inner_render_manager =
2043 inner_web_contents_impl->GetRenderManager();
2044 RenderFrameHostImpl* inner_main_frame =
2045 inner_render_manager->current_frame_host();
2046 RenderViewHostImpl* inner_render_view_host =
2047 inner_render_manager->current_host();
2048 auto* outer_render_manager =
2049 render_frame_host_impl->frame_tree_node()->render_manager();
lfg91a79e12016-04-01 23:52:192050
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392051 // When attaching a WebContents as an inner WebContents, we need to replace
2052 // the Webcontents' view with a WebContentsViewChildFrame.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502053 inner_web_contents_impl->view_.reset(new WebContentsViewChildFrame(
2054 inner_web_contents_impl,
2055 GetContentClient()->browser()->GetWebContentsViewDelegate(
2056 inner_web_contents_impl),
2057 &inner_web_contents_impl->render_view_host_delegate_view_));
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392058
lfg91a79e12016-04-01 23:52:192059 // When the WebContents being initialized has an opener, the browser side
2060 // Render{View,Frame}Host must be initialized and the RenderWidgetHostView
2061 // created. This is needed because the usual initialization happens during
2062 // the first navigation, but when attaching a new window we don't navigate
2063 // before attaching. If the browser side is already initialized, the calls
2064 // below will just early return.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502065 inner_render_manager->InitRenderView(inner_render_view_host, nullptr);
2066 inner_main_frame->Init();
2067 if (!inner_render_manager->GetRenderWidgetHostView()) {
2068 inner_web_contents_impl->CreateRenderWidgetHostViewForRenderManager(
2069 inner_render_view_host);
2070 }
lfg91a79e12016-04-01 23:52:192071
Adithya Srinivasane6e7f842019-12-16 18:41:362072 inner_web_contents_impl->RecursivelyUnregisterFrameSinkIds();
2073
lazyboy6ec48b2a2015-06-29 15:18:142074 // Create a link to our outer WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502075 node_.AttachInnerWebContents(std::move(inner_web_contents),
2076 render_frame_host_impl);
lazyboy6ec48b2a2015-06-29 15:18:142077
lazyboy6ec48b2a2015-06-29 15:18:142078 // Create a proxy in top-level RenderFrameHostManager, pointing to the
2079 // SiteInstance of the outer WebContents. The proxy will be used to send
2080 // postMessage to the inner WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502081 auto* proxy = inner_render_manager->CreateOuterDelegateProxy(
2082 render_frame_host_impl->GetSiteInstance());
lazyboy6ec48b2a2015-06-29 15:18:142083
Lucas Furukawa Gadani99125822019-01-03 15:41:492084 // When attaching a GuestView as an inner WebContents, there should already be
2085 // a live RenderFrame, which has to be swapped. When attaching a portal, there
2086 // will not be a live RenderFrame before creating the proxy.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502087 if (render_frame_host_impl->IsRenderFrameLive()) {
2088 inner_render_manager->SwapOuterDelegateFrame(render_frame_host_impl, proxy);
Lucas Furukawa Gadani99125822019-01-03 15:41:492089
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502090 inner_web_contents_impl->ReattachToOuterWebContentsFrame();
Lucas Furukawa Gadani99125822019-01-03 15:41:492091 }
ekaramadadd882292016-06-08 15:22:562092
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502093 if (frame_tree_.GetFocusedFrame() ==
2094 render_frame_host_impl->frame_tree_node()) {
2095 inner_web_contents_impl->SetFocusedFrame(
2096 inner_web_contents_impl->frame_tree_.root(),
2097 render_frame_host_impl->GetSiteInstance());
avallee7529b2a2017-04-26 11:37:512098 }
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502099 outer_render_manager->set_attach_complete();
W. James MacLean62883982019-11-12 20:39:002100
2101 // If the inner WebContents is full frame, give it focus.
2102 if (is_full_page) {
2103 // There should only ever be one inner WebContents when |is_full_page| is
2104 // true, and it is the one we just attached.
2105 DCHECK_EQ(1u, node_.GetInnerWebContents().size());
2106 inner_web_contents_impl->SetAsFocusedWebContentsIfNecessary();
2107 }
Chris Hamilton16b5d1d2020-06-04 00:08:122108
Alexander Timin90c20c32020-08-12 15:28:322109 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2110 observer->InnerWebContentsAttached(inner_web_contents_impl,
2111 render_frame_host, is_full_page);
2112 });
lazyboy6ec48b2a2015-06-29 15:18:142113}
2114
Lucas Furukawa Gadani99125822019-01-03 15:41:492115std::unique_ptr<WebContents> WebContentsImpl::DetachFromOuterWebContents() {
Chris Hamilton16b5d1d2020-06-04 00:08:122116 auto* outer_web_contents = GetOuterWebContents();
2117 DCHECK(outer_web_contents);
Yuzu Saijo3f86fb22020-06-11 03:51:102118 GetMainFrame()->ParentOrOuterDelegateFrame()->SetIsOuterDelegateFrame(false);
Chris Hamilton16b5d1d2020-06-04 00:08:122119
Adithya Srinivasane6e7f842019-12-16 18:41:362120 RecursivelyUnregisterFrameSinkIds();
Lucas Gadanid29952582020-06-09 21:24:002121
2122 // Each RenderViewHost has a RenderWidgetHost which can have a
2123 // RenderWidgetHostView, and it needs to be re-created with the appropriate
2124 // platform view. It is important to re-create all child views, not only the
2125 // current one, since the view can be swapped due to a cross-origin
2126 // navigation.
2127 std::set<RenderViewHostImpl*> render_view_hosts;
2128 for (auto& render_view_host : GetFrameTree()->render_view_hosts()) {
2129 if (render_view_host.second->GetWidget() &&
2130 render_view_host.second->GetWidget()->GetView()) {
2131 DCHECK(render_view_host.second->GetWidget()
2132 ->GetView()
2133 ->IsRenderWidgetHostViewChildFrame());
2134 render_view_hosts.insert(render_view_host.second);
Kevin McNee6471a702020-01-27 18:23:072135 }
2136 }
Lucas Gadanid29952582020-06-09 21:24:002137
2138 for (auto* render_view_host : render_view_hosts)
2139 render_view_host->GetWidget()->GetView()->Destroy();
2140
Lucas Furukawa Gadani99125822019-01-03 15:41:492141 GetRenderManager()->DeleteOuterDelegateProxy(
2142 node_.OuterContentsFrameTreeNode()
2143 ->current_frame_host()
2144 ->GetSiteInstance());
2145 view_.reset(CreateWebContentsView(
2146 this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
2147 &render_view_host_delegate_view_));
danakjfc5184932019-09-12 18:08:322148 view_->CreateView(nullptr);
Lucas Furukawa Gadani99125822019-01-03 15:41:492149 std::unique_ptr<WebContents> web_contents =
2150 node_.DisconnectFromOuterWebContents();
2151 DCHECK_EQ(web_contents.get(), this);
2152 node_.SetFocusedWebContents(this);
Lucas Gadanid29952582020-06-09 21:24:002153
2154 for (auto* render_view_host : render_view_hosts)
2155 CreateRenderWidgetHostViewForRenderManager(render_view_host);
2156
Adithya Srinivasane6e7f842019-12-16 18:41:362157 RecursivelyRegisterFrameSinkIds();
Adithya Srinivasan6f0f67b2019-12-19 01:26:462158 // TODO(adithyas): |browser_plugin_embedder_ax_tree_id| should either not be
2159 // used for portals, or it should get a different name.
2160 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(ui::AXTreeIDUnknown());
2161 GetMainFrame()->UpdateAXTreeData();
Chris Hamilton16b5d1d2020-06-04 00:08:122162
2163 // Invoke on the *outer* web contents observers for symmetry.
Alexander Timin90c20c32020-08-12 15:28:322164 outer_web_contents->observers_.ForEachObserver(
2165 [&](WebContentsObserver* observer) {
2166 observer->InnerWebContentsDetached(this);
2167 });
Chris Hamilton16b5d1d2020-06-04 00:08:122168
Lucas Furukawa Gadani99125822019-01-03 15:41:492169 return web_contents;
2170}
2171
W. James MacLean2dc75ed42019-03-06 14:31:092172void WebContentsImpl::RecursivelyRegisterFrameSinkIds() {
Adithya Srinivasane6e7f842019-12-16 18:41:362173 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2174 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2175 if (rwhvb->IsRenderWidgetHostViewChildFrame())
2176 static_cast<RenderWidgetHostViewChildFrame*>(view)->RegisterFrameSinkId();
2177 }
2178}
W. James MacLean2dc75ed42019-03-06 14:31:092179
Adithya Srinivasane6e7f842019-12-16 18:41:362180void WebContentsImpl::RecursivelyUnregisterFrameSinkIds() {
2181 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2182 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2183 if (rwhvb->IsRenderWidgetHostViewChildFrame()) {
2184 static_cast<RenderWidgetHostViewChildFrame*>(view)
2185 ->UnregisterFrameSinkId();
2186 }
W. James MacLean2dc75ed42019-03-06 14:31:092187 }
2188}
2189
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142190void WebContentsImpl::ReattachToOuterWebContentsFrame() {
2191 DCHECK(node_.outer_web_contents());
2192 auto* render_manager = GetRenderManager();
2193 auto* parent_frame =
2194 node_.OuterContentsFrameTreeNode()->current_frame_host()->GetParent();
2195 render_manager->SetRWHViewForInnerContents(
2196 render_manager->GetRenderWidgetHostView());
2197
W. James MacLean2dc75ed42019-03-06 14:31:092198 RecursivelyRegisterFrameSinkIds();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142199
2200 // Set up the the guest's AX tree to point back at the embedder's AX tree.
2201 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(
2202 parent_frame->GetAXTreeID());
2203 GetMainFrame()->UpdateAXTreeData();
2204}
2205
Lucas Gadani972985622020-05-28 20:52:512206void WebContentsImpl::DidActivatePortal(
2207 WebContentsImpl* predecessor_web_contents,
2208 base::TimeTicks activation_time) {
2209 DCHECK(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062210 NotifyInsidePortal(false);
Alexander Timin90c20c32020-08-12 15:28:322211 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2212 observer->DidActivatePortal(predecessor_web_contents, activation_time);
2213 });
Lucas Gadani972985622020-05-28 20:52:512214 GetDelegate()->WebContentsBecamePortal(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062215}
2216
Adithya Srinivasan11af2c52019-12-16 22:52:552217void WebContentsImpl::NotifyInsidePortal(bool inside_portal) {
Gyuyoung Kim1c029712020-07-22 09:21:062218 ExecutePageBroadcastMethod(base::BindRepeating(
2219 [](bool inside_portal, RenderViewHostImpl* rvh) {
2220 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2221 broadcast->SetInsidePortal(inside_portal);
2222 },
2223 inside_portal));
Adithya Srinivasan11af2c52019-12-16 22:52:552224}
2225
dalecurtis6c58ed02016-10-28 23:02:372226void WebContentsImpl::DidChangeVisibleSecurityState() {
Emily Starkc663b0242019-04-26 19:34:452227 if (delegate_)
dalecurtis6c58ed02016-10-28 23:02:372228 delegate_->VisibleSecurityStateChanged(this);
Alexander Timin90c20c32020-08-12 15:28:322229 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2230 observer->DidChangeVisibleSecurityState();
2231 });
dalecurtis6c58ed02016-10-28 23:02:372232}
2233
Rakina Zata Amni4029b6d2020-07-28 02:36:202234const WebPreferences WebContentsImpl::ComputeWebPreferences() {
2235 TRACE_EVENT0("browser", "WebContentsImpl::ComputeWebPreferences");
2236 WebPreferences prefs;
2237
2238 const base::CommandLine& command_line =
2239 *base::CommandLine::ForCurrentProcess();
2240
2241 SetSlowWebPreferences(command_line, &prefs);
2242
2243 prefs.web_security_enabled =
2244 !command_line.HasSwitch(switches::kDisableWebSecurity);
2245
2246 prefs.remote_fonts_enabled =
2247 !command_line.HasSwitch(switches::kDisableRemoteFonts);
2248 prefs.application_cache_enabled =
2249 base::FeatureList::IsEnabled(blink::features::kAppCache);
2250 prefs.local_storage_enabled =
2251 !command_line.HasSwitch(switches::kDisableLocalStorage);
2252 prefs.databases_enabled =
2253 !command_line.HasSwitch(switches::kDisableDatabases);
2254
2255 prefs.webgl1_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2256 !command_line.HasSwitch(switches::kDisableWebGL);
2257 prefs.webgl2_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2258 !command_line.HasSwitch(switches::kDisableWebGL) &&
2259 !command_line.HasSwitch(switches::kDisableWebGL2);
2260
2261 prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d);
2262
2263 prefs.flash_3d_enabled = !command_line.HasSwitch(switches::kDisableFlash3d);
2264 prefs.flash_stage3d_enabled =
2265 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2266 prefs.flash_stage3d_baseline_enabled =
2267 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2268
2269 prefs.allow_file_access_from_file_urls =
2270 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
2271
2272 prefs.accelerated_2d_canvas_enabled =
2273 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
2274 prefs.new_canvas_2d_api_enabled =
Rakina Zata Amniea8d0c22020-07-30 17:22:502275 command_line.HasSwitch(switches::kEnableNewCanvas2DAPI) ||
2276 base::FeatureList::IsEnabled(features::kEnableNewCanvas2DAPI);
Rakina Zata Amni4029b6d2020-07-28 02:36:202277 prefs.antialiased_2d_canvas_disabled =
2278 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
2279 prefs.antialiased_clips_2d_canvas_enabled =
2280 !command_line.HasSwitch(switches::kDisable2dCanvasClipAntialiasing);
2281
2282 prefs.disable_ipc_flooding_protection =
2283 command_line.HasSwitch(switches::kDisableIpcFloodingProtection) ||
2284 command_line.HasSwitch(switches::kDisablePushStateThrottle);
2285
2286 prefs.accelerated_video_decode_enabled =
2287 !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode);
2288
2289 std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
2290 if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
2291 prefs.autoplay_policy = AutoplayPolicy::kNoUserGestureRequired;
2292 } else if (autoplay_policy ==
2293 switches::autoplay::kUserGestureRequiredPolicy) {
2294 prefs.autoplay_policy = AutoplayPolicy::kUserGestureRequired;
2295 } else if (autoplay_policy ==
2296 switches::autoplay::kDocumentUserActivationRequiredPolicy) {
2297 prefs.autoplay_policy = AutoplayPolicy::kDocumentUserActivationRequired;
2298 } else {
2299 NOTREACHED();
2300 }
2301
2302 prefs.dont_send_key_events_to_javascript =
2303 base::FeatureList::IsEnabled(features::kDontSendKeyEventsToJavascript);
2304
2305// TODO(dtapuska): Enable barrel button selection drag support on Android.
2306// crbug.com/758042
2307#if defined(OS_WIN)
2308 prefs.barrel_button_for_drag_enabled =
2309 base::FeatureList::IsEnabled(features::kDirectManipulationStylus);
2310#endif // defined(OS_WIN)
2311
Rakina Zata Amni4029b6d2020-07-28 02:36:202312 prefs.enable_scroll_animator =
2313 command_line.HasSwitch(switches::kEnableSmoothScrolling) ||
2314 (!command_line.HasSwitch(switches::kDisableSmoothScrolling) &&
2315 gfx::Animation::ScrollAnimationsEnabledBySystem());
2316
2317 prefs.prefers_reduced_motion = gfx::Animation::PrefersReducedMotion();
2318
2319 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2320 GetRenderViewHost()->GetProcess()->GetID())) {
2321 prefs.loads_images_automatically = true;
2322 prefs.javascript_enabled = true;
2323 }
2324
2325 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
2326
2327 if (IsOverridingUserAgent())
2328 prefs.viewport_meta_enabled = false;
2329
2330 prefs.main_frame_resizes_are_orientation_changes =
2331 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
2332
2333 prefs.spatial_navigation_enabled =
2334 command_line.HasSwitch(switches::kEnableSpatialNavigation);
2335
2336 if (IsSpatialNavigationDisabled())
2337 prefs.spatial_navigation_enabled = false;
2338
Rakina Zata Amni4029b6d2020-07-28 02:36:202339 prefs.disable_reading_from_canvas =
2340 command_line.HasSwitch(switches::kDisableReadingFromCanvas);
2341
2342 prefs.strict_mixed_content_checking =
2343 command_line.HasSwitch(switches::kEnableStrictMixedContentChecking);
2344
2345 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
2346 switches::kEnableStrictPowerfulFeatureRestrictions);
2347
2348 const std::string blockable_mixed_content_group =
2349 base::FieldTrialList::FindFullName("BlockableMixedContent");
2350 prefs.strictly_block_blockable_mixed_content =
2351 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
2352
2353 const std::string plugin_mixed_content_status =
2354 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
2355 prefs.block_mixed_plugin_content =
2356 plugin_mixed_content_status == "BlockableMixedContent";
2357
2358 prefs.v8_cache_options = GetV8CacheOptions();
2359
2360 prefs.user_gesture_required_for_presentation = !command_line.HasSwitch(
2361 switches::kDisableGestureRequirementForPresentation);
2362
2363 if (HideDownloadUI())
2364 prefs.hide_download_ui = true;
2365
2366 // `media_controls_enabled` is `true` by default.
2367 if (HasPersistentVideo())
2368 prefs.media_controls_enabled = false;
2369
2370#if defined(OS_ANDROID)
2371 display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
2372 gfx::Size size = display.GetSizeInPixel();
2373 int min_width = size.width() < size.height() ? size.width() : size.height();
2374 prefs.device_scale_adjustment = GetDeviceScaleAdjustment(
2375 static_cast<int>(min_width / display.device_scale_factor()));
2376#endif // OS_ANDROID
2377
2378 GetContentClient()->browser()->OverrideWebkitPrefs(GetRenderViewHost(),
2379 &prefs);
2380 return prefs;
2381}
2382
2383void WebContentsImpl::SetSlowWebPreferences(
2384 const base::CommandLine& command_line,
2385 WebPreferences* prefs) {
2386 if (web_preferences_.get()) {
2387#define SET_FROM_CACHE(prefs, field) prefs->field = web_preferences_->field
2388
2389 SET_FROM_CACHE(prefs, touch_event_feature_detection_enabled);
2390 SET_FROM_CACHE(prefs, available_pointer_types);
2391 SET_FROM_CACHE(prefs, available_hover_types);
2392 SET_FROM_CACHE(prefs, primary_pointer_type);
2393 SET_FROM_CACHE(prefs, primary_hover_type);
2394 SET_FROM_CACHE(prefs, pointer_events_max_touch_points);
2395 SET_FROM_CACHE(prefs, number_of_cpu_cores);
2396
2397#if defined(OS_ANDROID)
2398 SET_FROM_CACHE(prefs, video_fullscreen_orientation_lock_enabled);
2399 SET_FROM_CACHE(prefs, video_rotate_to_fullscreen_enabled);
2400#endif
2401
2402#undef SET_FROM_CACHE
2403 } else {
2404 // Every prefs->field modified below should have a SET_FROM_CACHE entry
2405 // above.
2406
2407 // On Android, Touch event feature detection is enabled by default,
2408 // Otherwise default is disabled.
2409 std::string touch_enabled_default_switch =
2410 switches::kTouchEventFeatureDetectionDisabled;
2411#if defined(OS_ANDROID)
2412 touch_enabled_default_switch = switches::kTouchEventFeatureDetectionEnabled;
2413#endif // defined(OS_ANDROID)
2414 const std::string touch_enabled_switch =
2415 command_line.HasSwitch(switches::kTouchEventFeatureDetection)
2416 ? command_line.GetSwitchValueASCII(
2417 switches::kTouchEventFeatureDetection)
2418 : touch_enabled_default_switch;
2419
2420 prefs->touch_event_feature_detection_enabled =
2421 (touch_enabled_switch == switches::kTouchEventFeatureDetectionAuto)
2422 ? (ui::GetTouchScreensAvailability() ==
2423 ui::TouchScreensAvailability::ENABLED)
2424 : (touch_enabled_switch.empty() ||
2425 touch_enabled_switch ==
2426 switches::kTouchEventFeatureDetectionEnabled);
2427
2428 std::tie(prefs->available_pointer_types, prefs->available_hover_types) =
2429 ui::GetAvailablePointerAndHoverTypes();
2430 prefs->primary_pointer_type =
2431 ui::GetPrimaryPointerType(prefs->available_pointer_types);
2432 prefs->primary_hover_type =
2433 ui::GetPrimaryHoverType(prefs->available_hover_types);
2434
2435 prefs->pointer_events_max_touch_points = ui::MaxTouchPoints();
2436
2437 prefs->number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
2438
2439#if defined(OS_ANDROID)
2440 const bool device_is_phone =
2441 ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE;
2442 prefs->video_fullscreen_orientation_lock_enabled = device_is_phone;
2443 prefs->video_rotate_to_fullscreen_enabled = device_is_phone;
2444#endif
2445 }
2446}
2447
2448void WebContentsImpl::OnWebPreferencesChanged() {
2449 // This is defensive code to avoid infinite loops due to code run inside
2450 // SetWebPreferences() accidentally updating more preferences and thus
2451 // calling back into this code. See crbug.com/398751 for one past example.
2452 if (updating_web_preferences_)
2453 return;
2454 updating_web_preferences_ = true;
2455 SetWebPreferences(ComputeWebPreferences());
2456#if defined(OS_ANDROID)
2457 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2458 RenderFrameHostImpl* rfh = node->current_frame_host();
2459 if (rfh->is_local_root()) {
2460 if (auto* rwh = rfh->GetRenderWidgetHost())
2461 rwh->SetForceEnableZoom(web_preferences_->force_enable_zoom);
2462 }
2463 }
2464#endif
2465 updating_web_preferences_ = false;
2466}
2467
Ahmed Fakhryd70bf37b2018-04-04 17:07:242468void WebContentsImpl::NotifyPreferencesChanged() {
Rakina Zata Amni347b70902020-07-22 10:49:042469 // Recompute the WebPreferences based on the current state of the WebContents,
Rakina Zata Amni4029b6d2020-07-28 02:36:202470 // etc. Note that OnWebPreferencesChanged will also call SetWebPreferences and
2471 // send the updated WebPreferences to all RenderViews for this WebContents.
2472 OnWebPreferencesChanged();
Ahmed Fakhryd70bf37b2018-04-04 17:07:242473}
2474
Bruce Long1e3e1f542019-10-16 17:56:282475void WebContentsImpl::SyncRendererPrefs() {
Peter Marshall2dc74e92020-07-29 20:02:302476 blink::mojom::RendererPreferences renderer_preferences = GetRendererPrefs();
Bruce Long1e3e1f542019-10-16 17:56:282477 RenderViewHostImpl::GetPlatformSpecificPrefs(&renderer_preferences);
2478 SendPageMessage(
2479 new PageMsg_SetRendererPrefs(MSG_ROUTING_NONE, renderer_preferences));
2480}
2481
Alexander Timin1cc31f42020-05-12 16:26:012482void WebContentsImpl::OnCookiesAccessed(NavigationHandle* navigation,
2483 const CookieAccessDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:322484 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2485 observer->OnCookiesAccessed(navigation, details);
2486 });
Alexander Timin1cc31f42020-05-12 16:26:012487}
2488
2489void WebContentsImpl::OnCookiesAccessed(RenderFrameHostImpl* rfh,
2490 const CookieAccessDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:322491 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2492 observer->OnCookiesAccessed(rfh, details);
2493 });
Josh Karlindaba39322019-07-17 23:24:332494}
2495
[email protected]b172aee2012-04-10 17:05:262496void WebContentsImpl::Stop() {
dcheng57e39e22016-01-21 00:25:382497 for (FrameTreeNode* node : frame_tree_.Nodes())
2498 node->StopLoading();
Alexander Timin90c20c32020-08-12 15:28:322499 observers_.ForEachObserver(
2500 [&](WebContentsObserver* observer) { observer->NavigationStopped(); });
[email protected]0bfbf882011-12-22 18:19:272501}
2502
Francois Doray47f759d2018-06-11 18:13:512503void WebContentsImpl::SetPageFrozen(bool frozen) {
2504 // A visible page is never frozen.
2505 DCHECK_NE(Visibility::VISIBLE, GetVisibility());
2506
Yuzu Saijo4fa1e9a2020-05-20 02:53:262507 for (auto& entry : frame_tree_.render_view_hosts()) {
2508 entry.second->SetIsFrozen(frozen);
2509 }
Fadi Meawada6573e02018-03-10 00:52:112510}
2511
erikchen6c7df7f7a2018-05-03 18:13:592512std::unique_ptr<WebContents> WebContentsImpl::Clone() {
[email protected]14392a52012-05-02 20:28:442513 // We use our current SiteInstance since the cloned entry will use it anyway.
alexmose201c7cd2015-06-10 17:14:212514 // We pass our own opener so that the cloned page can access it if it was set
[email protected]ed245db2012-12-18 08:00:452515 // before.
[email protected]54944cde2012-12-09 09:24:592516 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
Ian Clelland5cbaaf82017-11-27 22:00:032517 FrameTreeNode* opener = frame_tree_.root()->opener();
2518 RenderFrameHostImpl* opener_rfh = nullptr;
2519 if (opener)
2520 opener_rfh = opener->current_frame_host();
erikchen6c7df7f7a2018-05-03 18:13:592521 std::unique_ptr<WebContentsImpl> tc =
erikchen50735fd2018-05-05 15:08:332522 CreateWithOpener(create_params, opener_rfh);
Lucas Furukawa Gadani5553a152019-01-08 18:55:572523 tc->GetController().CopyStateFrom(&controller_, true);
Alexander Timin90c20c32020-08-12 15:28:322524 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2525 observer->DidCloneToNewWebContents(this, tc.get());
2526 });
[email protected]0bfbf882011-12-22 18:19:272527 return tc;
2528}
2529
[email protected]14392a52012-05-02 20:28:442530void WebContentsImpl::Observe(int type,
[email protected]8ff00d72012-10-23 19:12:212531 const NotificationSource& source,
2532 const NotificationDetails& details) {
[email protected]14392a52012-05-02 20:28:442533 switch (type) {
[email protected]8ff00d72012-10-23 19:12:212534 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
2535 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
[email protected]0b431992014-06-24 00:08:032536 RenderWidgetHostView* view = host->GetView();
2537 if (view == GetFullscreenRenderWidgetHostView()) {
2538 // We cannot just call view_->RestoreFocus() here. On some platforms,
2539 // attempting to focus the currently-invisible WebContentsView will be
2540 // flat-out ignored. Therefore, this boolean is used to track whether
2541 // we will request focus after the fullscreen widget has been
2542 // destroyed.
2543 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
2544 } else {
alexmosc2a8cec2016-05-23 22:19:532545 for (auto i = pending_widget_views_.begin();
[email protected]0b431992014-06-24 00:08:032546 i != pending_widget_views_.end(); ++i) {
2547 if (host->GetView() == i->second) {
2548 pending_widget_views_.erase(i);
2549 break;
2550 }
[email protected]bafe6cd2012-05-23 23:09:502551 }
2552 }
2553 break;
2554 }
[email protected]14392a52012-05-02 20:28:442555 default:
2556 NOTREACHED();
2557 }
2558}
2559
[email protected]ec6c05f2013-10-23 18:41:572560WebContents* WebContentsImpl::GetWebContents() {
2561 return this;
2562}
2563
[email protected]54944cde2012-12-09 09:24:592564void WebContentsImpl::Init(const WebContents::CreateParams& params) {
[email protected]fa944cb82013-11-15 17:51:212565 // This is set before initializing the render manager since
[email protected]b0936d22013-11-28 06:47:362566 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
[email protected]fa944cb82013-11-15 17:51:212567 // it should be hidden.
Francois Doraye6161152018-03-27 22:05:372568 visibility_ =
2569 params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
[email protected]d6fa88f2013-10-18 16:00:432570
Sebastien Marchand28cf23182018-06-20 02:39:352571 if (!params.last_active_time.is_null())
2572 last_active_time_ = params.last_active_time;
2573
dcheng3ce04b62015-10-26 23:30:552574 scoped_refptr<SiteInstance> site_instance = params.site_instance;
2575 if (!site_instance)
2576 site_instance = SiteInstance::Create(params.browser_context);
Lukasz Anforowicz3caa8372018-06-05 17:22:072577 if (params.desired_renderer_state == CreateParams::kNoRendererProcess) {
2578 static_cast<SiteInstanceImpl*>(site_instance.get())
2579 ->PreventAssociationWithSpareProcess();
2580 }
dcheng3ce04b62015-10-26 23:30:552581
Fergal Dalycb0c1fdf2020-03-16 07:13:492582 GetRenderManager()->InitRoot(site_instance.get(),
2583 params.renderer_initiated_creation);
lukasza464d8692016-02-22 19:26:322584
lukasza5140a412016-09-15 21:12:302585 // blink::FrameTree::setName always keeps |unique_name| empty in case of a
2586 // main frame - let's do the same thing here.
2587 std::string unique_name;
lukasza464d8692016-02-22 19:26:322588 frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
[email protected]d1198fd2012-08-13 22:50:192589
[email protected]fc2b46b2014-05-03 16:33:452590 WebContentsViewDelegate* delegate =
2591 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
2592
W. James MacLean2539adb32019-12-13 00:40:442593 if (browser_plugin_guest_) {
sky52a39e342016-12-17 17:23:222594 view_.reset(new WebContentsViewChildFrame(
2595 this, delegate, &render_view_host_delegate_view_));
2596 } else {
2597 view_.reset(CreateWebContentsView(this, delegate,
2598 &render_view_host_delegate_view_));
[email protected]d1198fd2012-08-13 22:50:192599 }
[email protected]fc2b46b2014-05-03 16:33:452600 CHECK(render_view_host_delegate_view_);
[email protected]d1198fd2012-08-13 22:50:192601 CHECK(view_.get());
2602
danakjfc5184932019-09-12 18:08:322603 view_->CreateView(params.context);
[email protected]d1198fd2012-08-13 22:50:192604
brettw4b461082016-11-19 18:55:162605#if BUILDFLAG(ENABLE_PLUGINS)
Yuzu Saijoa11069a2020-04-22 10:56:552606 plugin_content_origin_allowlist_.reset(
2607 new PluginContentOriginAllowlist(this));
tommyclieb25b2a2014-11-03 19:45:092608#endif
2609
[email protected]d1198fd2012-08-13 22:50:192610 registrar_.Add(this,
[email protected]8ff00d72012-10-23 19:12:212611 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
2612 NotificationService::AllBrowserContextsAndSources());
[email protected]f28ef9a32014-05-12 16:36:102613
leon.hane4db177a2017-02-07 14:19:162614 screen_orientation_provider_.reset(new ScreenOrientationProvider(this));
[email protected]01f83f92014-06-17 14:41:542615
mfomitchev2b8b066a2016-01-28 19:23:152616#if defined(OS_ANDROID)
Oksana Zhuravlova0b634332019-10-28 23:04:222617 DateTimeChooserAndroid::CreateForWebContents(this);
[email protected]583418cc2013-01-17 14:01:102618#endif
fsamuel7310a4262014-12-05 05:06:442619
2620 // BrowserPluginGuest::Init needs to be called after this WebContents has
W. James MacLean6e78da342019-12-13 15:13:232621 // a RenderWidgetHostViewChildFrame. That is, |view_->CreateView| above.
fsamuel7310a4262014-12-05 05:06:442622 if (browser_plugin_guest_)
2623 browser_plugin_guest_->Init();
nickf9acfbe2014-12-23 19:12:372624
2625 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
2626 g_created_callbacks.Get().at(i).Run(this);
naskob21fe4872015-02-24 14:15:562627
2628 // If the WebContents creation was renderer-initiated, it means that the
2629 // corresponding RenderView and main RenderFrame have already been created.
2630 // Ensure observers are notified about this.
2631 if (params.renderer_initiated_creation) {
Fergal Dalybb2d6592020-06-02 05:02:332632 GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
Alex Moshchuk27caae82017-09-11 23:11:182633 GetRenderViewHost()->DispatchRenderViewCreated();
naskob21fe4872015-02-24 14:15:562634 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
2635 }
naskof5940b9f2015-03-02 23:04:052636
lof84501da082016-05-23 21:22:542637 // Create the renderer process in advance if requested.
Lukasz Anforowicz3caa8372018-06-05 17:22:072638 if (params.desired_renderer_state ==
2639 CreateParams::kInitializeAndWarmupRendererProcess) {
lof84501da082016-05-23 21:22:542640 if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
2641 GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
2642 }
2643 }
2644
naskof5940b9f2015-03-02 23:04:052645 // Ensure that observers are notified of the creation of this WebContents's
2646 // main RenderFrameHost. It must be done here for main frames, since the
2647 // NotifySwappedFromRenderManager expects view_ to already be created and that
2648 // happens after RenderFrameHostManager::Init.
2649 NotifySwappedFromRenderManager(
2650 nullptr, GetRenderManager()->current_frame_host(), true);
Albert J. Wonge76bf0b82019-09-27 07:47:062651
2652 // For WebContents that are never shown, do critical initialization here which
2653 // would normally only happen when the WebContents is shown.
2654 if (params.is_never_visible) {
2655 // This has just been created so there can only be one frame. Thus it is
2656 // safe to initialize the root.
2657 GetMainFrame()->Init();
2658 }
[email protected]d1198fd2012-08-13 22:50:192659}
2660
[email protected]7fff43e2013-05-21 20:21:102661void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
2662 RemoveDestructionObserver(web_contents);
2663
[email protected]ceee8cd2013-03-08 04:59:512664 // Clear a pending contents that has been closed before being shown.
alexmosc2a8cec2016-05-23 22:19:532665 for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
[email protected]ceee8cd2013-03-08 04:59:512666 ++iter) {
Joel Hockey8c2011b22020-04-30 05:07:192667 if (iter->second.contents.get() != web_contents)
[email protected]ceee8cd2013-03-08 04:59:512668 continue;
erikchenbee5c9622018-04-27 19:30:252669
2670 // Someone else has deleted the WebContents. That should never happen!
2671 // TODO(erikchen): Fix semantics here. https://crbug.com/832879.
Joel Hockey8c2011b22020-04-30 05:07:192672 iter->second.contents.release();
[email protected]ceee8cd2013-03-08 04:59:512673 pending_contents_.erase(iter);
[email protected]ceee8cd2013-03-08 04:59:512674 return;
2675 }
2676 NOTREACHED();
[email protected]14392a52012-05-02 20:28:442677}
2678
[email protected]7fff43e2013-05-21 20:21:102679void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
Jan Wilken Dörrie73c901e2019-06-12 09:02:322680 if (!base::Contains(destruction_observers_, web_contents)) {
[email protected]7fff43e2013-05-21 20:21:102681 destruction_observers_[web_contents] =
Jeremy Roman04f27c372017-10-27 15:20:552682 std::make_unique<DestructionObserver>(this, web_contents);
[email protected]7fff43e2013-05-21 20:21:102683 }
2684}
2685
2686void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
avia8cf81982016-08-12 20:28:462687 destruction_observers_.erase(web_contents);
[email protected]7fff43e2013-05-21 20:21:102688}
2689
[email protected]b172aee2012-04-10 17:05:262690void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
[email protected]be1f56ab2011-12-22 06:55:312691 observers_.AddObserver(observer);
2692}
2693
[email protected]b172aee2012-04-10 17:05:262694void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
[email protected]be1f56ab2011-12-22 06:55:312695 observers_.RemoveObserver(observer);
2696}
2697
[email protected]948481d2014-06-11 18:32:222698std::set<RenderWidgetHostView*>
2699WebContentsImpl::GetRenderWidgetHostViewsInTree() {
2700 std::set<RenderWidgetHostView*> set;
Carlos IL07f282f2020-05-15 22:58:292701 for (RenderFrameHost* rfh : GetAllFrames()) {
2702 if (RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
2703 ->frame_tree_node()
2704 ->render_manager()
2705 ->GetRenderWidgetHostView()) {
lfgf949e0e2017-05-10 22:18:112706 set.insert(rwhv);
dchengafb53e22016-02-04 08:11:082707 }
[email protected]948481d2014-06-11 18:32:222708 }
[email protected]de3c5d82014-05-28 22:12:592709 return set;
2710}
2711
Adithya Srinivasane6e7f842019-12-16 18:41:362712std::set<RenderWidgetHostView*>
2713WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree() {
2714 std::set<RenderWidgetHostView*> result;
2715 GetRenderWidgetHostViewsInWebContentsTree(result);
2716 return result;
2717}
2718
2719void WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree(
2720 std::set<RenderWidgetHostView*>& result) {
2721 std::set<RenderWidgetHostView*> views = GetRenderWidgetHostViewsInTree();
2722 result.insert(views.begin(), views.end());
2723 for (auto* inner_web_contents : GetInnerWebContents()) {
2724 static_cast<WebContentsImpl*>(inner_web_contents)
2725 ->GetRenderWidgetHostViewsInWebContentsTree(result);
2726 }
2727}
2728
[email protected]b172aee2012-04-10 17:05:262729void WebContentsImpl::Activate() {
[email protected]d5f942ba2008-09-26 19:30:342730 if (delegate_)
2731 delegate_->ActivateContents(this);
2732}
2733
avi3e4b8512015-11-11 01:55:492734void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
2735 if (!RenderViewHostImpl::From(render_widget_host))
2736 return;
2737
[email protected]63954792011-07-11 04:17:482738 if (delegate_)
2739 delegate_->LostCapture();
2740}
2741
Yue Ru Sun979c4b162019-11-06 16:11:042742ukm::SourceId
2743WebContentsImpl::GetUkmSourceIdForLastCommittedSourceIncludingSameDocument()
2744 const {
2745 return last_committed_source_id_including_same_document_;
2746}
2747
Ahmed Fakhryfaa32d22018-10-05 15:56:162748void WebContentsImpl::SetTopControlsShownRatio(
2749 RenderWidgetHostImpl* render_widget_host,
2750 float ratio) {
2751 if (!delegate_)
2752 return;
2753
2754 RenderFrameHostImpl* rfh = GetMainFrame();
2755 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
2756 return;
2757
2758 delegate_->SetTopControlsShownRatio(this, ratio);
Ahmed Fakhry58e6ef542018-09-04 18:05:382759}
2760
Ahmed Fakhry58e6ef542018-09-04 18:05:382761void WebContentsImpl::SetTopControlsGestureScrollInProgress(bool in_progress) {
2762 if (delegate_)
2763 delegate_->SetTopControlsGestureScrollInProgress(in_progress);
2764}
2765
lazyboy63f5b312015-11-23 20:19:522766void WebContentsImpl::RenderWidgetCreated(
2767 RenderWidgetHostImpl* render_widget_host) {
2768 created_widgets_.insert(render_widget_host);
2769}
2770
[email protected]b24b68a2012-09-24 21:57:262771void WebContentsImpl::RenderWidgetDeleted(
2772 RenderWidgetHostImpl* render_widget_host) {
lazyboy63f5b312015-11-23 20:19:522773 // Note that |is_being_destroyed_| can be true at this point as
2774 // ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
2775 // us here.
2776 created_widgets_.erase(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262777
lazyboy63f5b312015-11-23 20:19:522778 if (is_being_destroyed_)
2779 return;
[email protected]44470a22013-01-24 01:21:542780
2781 if (render_widget_host &&
alexmosc9e76ec2016-05-16 22:59:372782 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_ &&
2783 render_widget_host->GetProcess()->GetID() ==
2784 fullscreen_widget_process_id_) {
[email protected]4aebbca2013-09-17 22:26:492785 if (delegate_ && delegate_->EmbedsFullscreenWidget())
mlamouri7a78d6fd2015-01-17 13:23:532786 delegate_->ExitFullscreenModeForTab(this);
Alexander Timin90c20c32020-08-12 15:28:322787 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2788 observer->DidDestroyFullscreenWidget();
2789 });
alexmosc9e76ec2016-05-16 22:59:372790 fullscreen_widget_process_id_ = ChildProcessHost::kInvalidUniqueID;
[email protected]44470a22013-01-24 01:21:542791 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
[email protected]0b431992014-06-24 00:08:032792 if (fullscreen_widget_had_focus_at_shutdown_)
2793 view_->RestoreFocus();
[email protected]44470a22013-01-24 01:21:542794 }
lfgbee1e0a2016-06-08 21:24:212795
lfg7d4caad2017-03-22 09:01:452796 if (render_widget_host == mouse_lock_widget_)
lfgff8dfc8d2016-10-21 17:42:322797 LostMouseLock(mouse_lock_widget_);
Joe Downing192998b22018-03-22 15:51:362798
Joe Downingc1a57efe2018-05-09 18:23:542799 CancelKeyboardLock(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262800}
2801
miu9e14e492014-10-25 02:39:042802void WebContentsImpl::RenderWidgetGotFocus(
2803 RenderWidgetHostImpl* render_widget_host) {
calamity7fe55ce2015-04-10 03:59:372804 // Notify the observers if an embedded fullscreen widget was focused.
2805 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
2806 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
Michael Thiessen896405db2017-07-20 17:52:322807 NotifyWebContentsFocused(render_widget_host);
calamity7fe55ce2015-04-10 03:59:372808 }
miu9e14e492014-10-25 02:39:042809}
2810
zijiehe3bee08e22017-05-17 04:14:462811void WebContentsImpl::RenderWidgetLostFocus(
2812 RenderWidgetHostImpl* render_widget_host) {
Michael Thiessen896405db2017-07-20 17:52:322813 // Notify the observers if an embedded fullscreen widget lost focus.
2814 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
2815 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
2816 NotifyWebContentsLostFocus(render_widget_host);
2817 }
zijiehe3bee08e22017-05-17 04:14:462818}
2819
estaded0a0c992015-01-21 14:12:062820void WebContentsImpl::RenderWidgetWasResized(
rouslan2f5993f2015-01-29 00:18:312821 RenderWidgetHostImpl* render_widget_host,
2822 bool width_changed) {
creisc014b402015-04-23 16:41:452823 RenderFrameHostImpl* rfh = GetMainFrame();
estadece344ec2015-01-23 00:12:292824 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
estaded0a0c992015-01-21 14:12:062825 return;
estaded0a0c992015-01-21 14:12:062826
Alexander Timin90c20c32020-08-12 15:28:322827 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2828 observer->MainFrameWasResized(width_changed);
2829 });
estaded0a0c992015-01-21 14:12:062830}
2831
skyf65d9bb2017-03-24 02:26:392832KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent(
2833 const NativeWebKeyboardEvent& event) {
W. James MacLeane1187272019-11-12 03:42:482834 auto* outermost_contents = GetOutermostWebContents();
2835 // TODO(wjmaclean): Generalize this to forward all key events to the outermost
2836 // delegate's handler.
Avi Drissman97aef042020-06-30 21:04:482837 if (outermost_contents != this && IsFullscreen() &&
W. James MacLeane1187272019-11-12 03:42:482838 event.windows_key_code == ui::VKEY_ESCAPE) {
2839 // When an inner WebContents has focus and is fullscreen, redirect <esc>
2840 // key events to the outermost WebContents so it can be handled by that
2841 // WebContents' delegate.
2842 if (outermost_contents->PreHandleKeyboardEvent(event) ==
2843 KeyboardEventProcessingResult::HANDLED) {
2844 return KeyboardEventProcessingResult::HANDLED;
2845 }
2846 }
skyf65d9bb2017-03-24 02:26:392847 return delegate_ ? delegate_->PreHandleKeyboardEvent(this, event)
2848 : KeyboardEventProcessingResult::NOT_HANDLED;
[email protected]63954792011-07-11 04:17:482849}
2850
Dave Tapuska344399e2019-09-09 15:18:262851bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) {
2852 // Handle mouse button back/forward in the browser process after the render
2853 // process is done with the event. This ensures all renderer-initiated history
2854 // navigations can be treated consistently.
2855 if (event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
2856 WebContentsImpl* outermost = GetOutermostWebContents();
2857 if (event.button == blink::WebPointerProperties::Button::kBack &&
2858 outermost->controller_.CanGoBack()) {
2859 outermost->controller_.GoBack();
2860 return true;
2861 } else if (event.button == blink::WebPointerProperties::Button::kForward &&
2862 outermost->controller_.CanGoForward()) {
2863 outermost->controller_.GoForward();
2864 return true;
2865 }
2866 }
2867 return false;
2868}
2869
Scott Violetd5caa872018-10-16 22:00:512870bool WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
[email protected]0b094002014-08-20 18:28:102871 if (browser_plugin_embedder_ &&
2872 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
Scott Violetd5caa872018-10-16 22:00:512873 return true;
[email protected]0b094002014-08-20 18:28:102874 }
Scott Violetd5caa872018-10-16 22:00:512875 return delegate_ && delegate_->HandleKeyboardEvent(this, event);
[email protected]63954792011-07-11 04:17:482876}
2877
[email protected]d92026ef2014-03-03 21:04:132878bool WebContentsImpl::HandleWheelEvent(
[email protected]180ef242013-11-07 06:50:462879 const blink::WebMouseWheelEvent& event) {
Avi Drissman7c57be72020-07-29 20:09:462880#if !defined(OS_MAC)
lanweia93644f2015-01-21 22:00:332881 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
2882 // this isn't done for two reasons:
[email protected]bccc4472013-04-18 16:37:192883 // -the OS already has a gesture to do this through pinch-zoom
2884 // -if a user starts an inertial scroll, let's go, and presses control
2885 // (i.e. control+tab) then the OS's buffered scroll events will come in
2886 // with control key set which isn't what the user wants
Blink Reformat1c4d759e2017-04-09 16:34:542887 if (delegate_ && event.wheel_ticks_y &&
Ehsan Karamad0f83cb112018-09-06 22:07:362888 event.event_action == blink::WebMouseWheelEvent::EventAction::kPageZoom) {
w.shackleton49bcd392016-01-06 17:38:222889 // Count only integer cumulative scrolls as zoom events; this handles
2890 // smooth scroll and regular scroll device behavior.
Blink Reformat1c4d759e2017-04-09 16:34:542891 zoom_scroll_remainder_ += event.wheel_ticks_y;
w.shackleton49bcd392016-01-06 17:38:222892 int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
2893 zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
2894 if (whole_zoom_scroll_remainder_ != 0) {
2895 delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
2896 }
[email protected]fb3f066e2013-02-12 19:12:522897 return true;
2898 }
[email protected]bccc4472013-04-18 16:37:192899#endif
[email protected]fb3f066e2013-02-12 19:12:522900 return false;
2901}
2902
[email protected]04bce562014-01-30 05:34:542903bool WebContentsImpl::PreHandleGestureEvent(
2904 const blink::WebGestureEvent& event) {
[email protected]28042d32014-02-03 14:10:032905 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
[email protected]04bce562014-01-30 05:34:542906}
2907
kenrb2a565f82015-09-02 20:24:592908RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
wjmacleane31234f2015-12-14 17:20:452909 if (!is_being_destroyed_ && GetOuterWebContents())
2910 return GetOuterWebContents()->GetInputEventRouter();
2911
2912 if (!rwh_input_event_router_.get() && !is_being_destroyed_)
kenrb2a565f82015-09-02 20:24:592913 rwh_input_event_router_.reset(new RenderWidgetHostInputEventRouter);
2914 return rwh_input_event_router_.get();
2915}
2916
alexmos3fcd0ca2015-10-23 18:18:332917void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
2918 // Focus loss may occur while this WebContents is being destroyed. Don't
2919 // send the message in this case, as the main frame's RenderFrameHost and
2920 // other state has already been cleared.
2921 if (is_being_destroyed_)
2922 return;
2923
2924 frame_tree_.ReplicatePageFocus(is_focused);
2925}
2926
alexmosc4cbacb2015-11-21 01:29:222927RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
2928 RenderWidgetHostImpl* receiving_widget) {
alexmosc4cbacb2015-11-21 01:29:222929 // Events for widgets other than the main frame (e.g., popup menus) should be
2930 // forwarded directly to the widget they arrived on.
2931 if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
2932 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:522933
paulmeyerfeafc2d2017-04-25 21:46:402934 // If the focused WebContents is a guest WebContents, then get the focused
2935 // frame in the embedder WebContents instead.
W. James MacLean13d834d2019-12-04 16:06:452936 FrameTreeNode* focused_frame =
2937 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
lfg1453e412017-04-11 00:48:502938
alexmosc4d183e2015-11-06 00:46:522939 if (!focused_frame)
alexmosc4cbacb2015-11-21 01:29:222940 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:522941
alexmos732ca3a2015-12-08 02:01:022942 // The view may be null if a subframe's renderer process has crashed while
2943 // the subframe has focus. Drop the event in that case. Do not give
2944 // it to the main frame, so that the user doesn't unexpectedly type into the
2945 // wrong frame if a focused subframe renderer crashes while they type.
2946 RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
2947 if (!view)
2948 return nullptr;
2949
2950 return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
alexmosc4d183e2015-11-06 00:46:522951}
2952
avallee9993fca2016-11-17 06:16:502953RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
lfg1453e412017-04-11 00:48:502954 WebContentsImpl* focused_web_contents = GetFocusedWebContents();
2955
lfg1453e412017-04-11 00:48:502956 return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:502957}
2958
Avi Drissmand1d25652020-03-06 21:28:582959bool WebContentsImpl::CanEnterFullscreenMode() {
Avi Drissman33972942020-06-19 14:16:012960 // It's possible that this WebContents was spawned while blocking UI was on
2961 // the screen, or that it was downstream from a WebContents when UI was
2962 // blocked. Therefore, disqualify it from fullscreen if it or any upstream
2963 // WebContents has an active blocker.
2964 auto openers = GetAllOpeningWebContents(this);
2965 return std::all_of(openers.begin(), openers.end(), [](auto* opener) {
2966 return opener->fullscreen_blocker_count_ == 0;
2967 });
Avi Drissmand1d25652020-03-06 21:28:582968}
2969
Dave Tapuska3ed44192018-05-01 18:53:302970void WebContentsImpl::EnterFullscreenMode(
Mike Wasserman4ca09792020-05-29 17:44:432971 RenderFrameHost* requesting_frame,
Dave Tapuskaa4189512019-10-15 20:27:342972 const blink::mojom::FullscreenOptions& options) {
Avi Drissmand1d25652020-03-06 21:28:582973 DCHECK(CanEnterFullscreenMode());
2974
mlamouri7a78d6fd2015-01-17 13:23:532975 // This method is being called to enter renderer-initiated fullscreen mode.
2976 // Make sure any existing fullscreen widget is shut down first.
[email protected]4aebbca2013-09-17 22:26:492977 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:372978 if (widget_view) {
2979 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
2980 ->ShutdownAndDestroyWidget(true);
2981 }
[email protected]4aebbca2013-09-17 22:26:492982
Joe Downing13dd76b2018-04-09 18:32:152983 if (delegate_) {
Mike Wasserman4ca09792020-05-29 17:44:432984 delegate_->EnterFullscreenModeForTab(requesting_frame, options);
mlamouri7a78d6fd2015-01-17 13:23:532985
Joe Downing13dd76b2018-04-09 18:32:152986 if (keyboard_lock_widget_)
2987 delegate_->RequestKeyboardLock(this, esc_key_locked_);
2988 }
2989
Alexander Timin90c20c32020-08-12 15:28:322990 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2991 observer->DidToggleFullscreenModeForTab(IsFullscreen(), false);
2992 });
Avi Drissman33972942020-06-19 14:16:012993 FullscreenContentsSet(GetBrowserContext())->insert(this);
mlamouri7a78d6fd2015-01-17 13:23:532994}
2995
bokanece34a82016-01-28 19:49:462996void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
mlamouri7a78d6fd2015-01-17 13:23:532997 // This method is being called to leave renderer-initiated fullscreen mode.
2998 // Make sure any existing fullscreen widget is shut down first.
2999 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373000 if (widget_view) {
3001 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3002 ->ShutdownAndDestroyWidget(true);
3003 }
mlamouri7a78d6fd2015-01-17 13:23:533004
Joe Downing13dd76b2018-04-09 18:32:153005 if (delegate_) {
mlamouri7a78d6fd2015-01-17 13:23:533006 delegate_->ExitFullscreenModeForTab(this);
[email protected]657c8e02014-03-19 19:18:373007
Joe Downing13dd76b2018-04-09 18:32:153008 if (keyboard_lock_widget_)
3009 delegate_->CancelKeyboardLockRequest(this);
3010 }
3011
bokanece34a82016-01-28 19:49:463012 // The fullscreen state is communicated to the renderer through a resize
3013 // message. If the change in fullscreen state doesn't cause a view resize
3014 // then we must ensure web contents exit the fullscreen state by explicitly
3015 // sending a resize message. This is required for the situation of the browser
3016 // moving the view into a "browser fullscreen" state and then the contents
3017 // entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
3018 // have the side effect of the view resizing, hence the explicit call here is
3019 // required.
3020 if (!will_cause_resize) {
3021 if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
3022 if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:163023 render_widget_host->SynchronizeVisualProperties();
bokanece34a82016-01-28 19:49:463024 }
scheib3dcb6c932015-02-23 10:55:583025 }
3026
Arthur Sonzogni929d29f2018-09-17 14:19:443027 current_fullscreen_frame_ = nullptr;
Becca Hughese9e27952018-06-25 17:08:273028
Alexander Timin90c20c32020-08-12 15:28:323029 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3030 observer->DidToggleFullscreenModeForTab(IsFullscreen(), will_cause_resize);
3031 });
Becca Hughesd11d6502018-07-31 17:01:283032
3033 if (display_cutout_host_impl_)
3034 display_cutout_host_impl_->DidExitFullscreen();
Avi Drissman33972942020-06-19 14:16:013035
3036 FullscreenContentsSet(GetBrowserContext())->erase(this);
[email protected]8a5e0ca2011-08-25 06:30:473037}
3038
Becca Hughesfd5d8f892018-06-14 18:23:363039void WebContentsImpl::FullscreenStateChanged(RenderFrameHost* rfh,
3040 bool is_fullscreen) {
Arthur Sonzogni929d29f2018-09-17 14:19:443041 RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>(rfh);
Becca Hughesfd5d8f892018-06-14 18:23:363042
3043 if (is_fullscreen) {
Jan Wilken Dörrie531be7ca2019-06-07 10:05:573044 if (!base::Contains(fullscreen_frames_, frame)) {
Arthur Sonzogni929d29f2018-09-17 14:19:443045 fullscreen_frames_.insert(frame);
3046 FullscreenFrameSetUpdated();
Becca Hughesfd5d8f892018-06-14 18:23:363047 }
Arthur Sonzogni929d29f2018-09-17 14:19:443048 return;
3049 }
Becca Hughesfd5d8f892018-06-14 18:23:363050
Arthur Sonzogni929d29f2018-09-17 14:19:443051 // If |frame| is no longer in fullscreen, remove it and any descendants.
3052 // See https://fullscreen.spec.whatwg.org.
Arthur Sonzogni969a794e2018-10-11 08:56:093053 size_t size_before_deletion = fullscreen_frames_.size();
3054 base::EraseIf(fullscreen_frames_, [&](RenderFrameHostImpl* current) {
3055 return (current == frame || current->IsDescendantOf(frame));
Arthur Sonzogni929d29f2018-09-17 14:19:443056 });
3057
Arthur Sonzogni969a794e2018-10-11 08:56:093058 if (size_before_deletion != fullscreen_frames_.size())
Arthur Sonzogni929d29f2018-09-17 14:19:443059 FullscreenFrameSetUpdated();
3060}
3061
3062void WebContentsImpl::FullscreenFrameSetUpdated() {
3063 if (fullscreen_frames_.empty()) {
3064 current_fullscreen_frame_ = nullptr;
3065 return;
Becca Hughesfd5d8f892018-06-14 18:23:363066 }
3067
Arthur Sonzogni929d29f2018-09-17 14:19:443068 // Find the current fullscreen frame and call the observers.
3069 // If frame A is fullscreen, then frame B goes into inner fullscreen, then B
3070 // exits fullscreen - that will result in A being fullscreen.
3071 RenderFrameHostImpl* new_fullscreen_frame = *std::max_element(
3072 fullscreen_frames_.begin(), fullscreen_frames_.end(), FrameCompareDepth);
Becca Hughesfd5d8f892018-06-14 18:23:363073
Arthur Sonzogni929d29f2018-09-17 14:19:443074 // If we have already notified observers about this frame then we should not
3075 // fire the observers again.
3076 if (new_fullscreen_frame == current_fullscreen_frame_)
3077 return;
3078 current_fullscreen_frame_ = new_fullscreen_frame;
Becca Hughesfd5d8f892018-06-14 18:23:363079
Alexander Timin90c20c32020-08-12 15:28:323080 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3081 observer->DidAcquireFullscreen(new_fullscreen_frame);
3082 });
Arthur Sonzogni929d29f2018-09-17 14:19:443083 if (display_cutout_host_impl_)
3084 display_cutout_host_impl_->DidAcquireFullscreen(new_fullscreen_frame);
Becca Hughesfd5d8f892018-06-14 18:23:363085}
3086
Collin Baker989e0882019-11-01 01:27:173087void WebContentsImpl::UpdateVisibilityAndNotifyPageAndView(
3088 Visibility new_visibility) {
Collin Baker989e0882019-11-01 01:27:173089 // Only hide the page if there are no entities capturing screenshots
Collin Bakerc5259962019-11-14 17:51:583090 // or video (e.g. mirroring). If there are, apply the correct state of
3091 // kHidden or kHiddenButPainting.
3092 PageVisibilityState page_visibility;
3093 if (new_visibility == Visibility::VISIBLE || visible_capturer_count_ > 0)
3094 page_visibility = PageVisibilityState::kVisible;
3095 else if (hidden_capturer_count_ > 0)
3096 page_visibility = PageVisibilityState::kHiddenButPainting;
3097 else
3098 page_visibility = PageVisibilityState::kHidden;
Collin Baker989e0882019-11-01 01:27:173099 // If there are entities in Picture-in-Picture mode, don't activate
3100 // the "disable rendering" optimization.
Collin Bakerc5259962019-11-14 17:51:583101 const bool view_is_visible =
3102 page_visibility != PageVisibilityState::kHidden ||
3103 HasPictureInPictureVideo();
Collin Baker989e0882019-11-01 01:27:173104
Collin Bakerc5259962019-11-14 17:51:583105 if (page_visibility != PageVisibilityState::kHidden) {
Dana Friedcf3bc8e2019-11-13 20:00:243106 // We cannot show a page or capture video unless there is a valid renderer
3107 // associated with this web contents. The navigation controller for this
3108 // page must be set to active (allowing navigation to complete, a renderer
3109 // and its associated views to be created, etc.) if any of these conditions
3110 // holds.
3111 //
3112 // Previously, it was possible for browser-side code to try to capture video
3113 // from a restored tab (for a variety of reasons, including the browser
3114 // creating preview thumbnails) and the tab would never actually load. By
Collin Bakerc5259962019-11-14 17:51:583115 // keying this behavior off of |page_visibility| instead of just
Dana Friedcf3bc8e2019-11-13 20:00:243116 // |new_visibility| we avoid this case. See crbug.com/1020782 for more
3117 // context.
3118 controller_.SetActive(true);
3119
3120 // This shows the Page before showing the individual RenderWidgets, as
3121 // RenderWidgets will work to produce compositor frames and handle input
3122 // as soon as they are shown. But the Page and other classes do not expect
3123 // to be producing frames when the Page is hidden. So we make sure the Page
3124 // is shown first.
Yuzu Saijo232076f2020-05-29 07:14:023125 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3126 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563127 }
Collin Baker98457b52019-11-06 21:34:293128 }
Collin Baker989e0882019-11-01 01:27:173129
3130 // |GetRenderWidgetHostView()| can be null if the user middle clicks a link to
3131 // open a tab in the background, then closes the tab before selecting it.
3132 // This is because closing the tab calls WebContentsImpl::Destroy(), which
3133 // removes the |GetRenderViewHost()|; then when we actually destroy the
3134 // window, OnWindowPosChanged() notices and calls WasHidden() (which
3135 // calls us).
3136 if (auto* view = GetRenderWidgetHostView()) {
3137 if (view_is_visible) {
3138 view->Show();
Collin Baker989e0882019-11-01 01:27:173139 } else if (new_visibility == Visibility::HIDDEN) {
3140 view->Hide();
3141 } else {
3142 view->WasOccluded();
3143 }
3144 }
3145
Carlos IL07f282f2020-05-15 22:58:293146 SetVisibilityForChildViews(view_is_visible);
Collin Baker989e0882019-11-01 01:27:173147
3148 // Make sure to call SetVisibilityAndNotifyObservers(VISIBLE) before notifying
3149 // the CrossProcessFrameConnector.
3150 if (new_visibility == Visibility::VISIBLE) {
3151 last_active_time_ = base::TimeTicks::Now();
3152 SetVisibilityAndNotifyObservers(new_visibility);
3153 }
3154
Collin Bakerc5259962019-11-14 17:51:583155 if (page_visibility == PageVisibilityState::kHidden) {
Collin Baker989e0882019-11-01 01:27:173156 // Similar to when showing the page, we only hide the page after
3157 // hiding the individual RenderWidgets.
Yuzu Saijo232076f2020-05-29 07:14:023158 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3159 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563160 }
3161
Collin Baker989e0882019-11-01 01:27:173162 } else {
3163 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3164 RenderFrameProxyHost* parent = node->render_manager()->GetProxyToParent();
3165 if (!parent)
3166 continue;
3167
3168 parent->cross_process_frame_connector()->DelegateWasShown();
3169 }
3170 }
3171
3172 if (new_visibility != Visibility::VISIBLE)
3173 SetVisibilityAndNotifyObservers(new_visibility);
3174}
3175
Clark DuValla0e42992018-09-17 17:00:113176#if defined(OS_ANDROID)
3177void WebContentsImpl::UpdateUserGestureCarryoverInfo() {
3178 if (delegate_)
3179 delegate_->UpdateUserGestureCarryoverInfo(this);
3180}
3181#endif
3182
Avi Drissman97aef042020-06-30 21:04:483183bool WebContentsImpl::IsFullscreen() {
[email protected]199bba6e2012-04-04 16:19:383184 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
[email protected]5d5f7af2011-10-01 01:38:123185}
3186
Malay Keshav87c42c02019-01-15 08:37:473187bool WebContentsImpl::ShouldShowStaleContentOnEviction() {
3188 return GetDelegate() && GetDelegate()->ShouldShowStaleContentOnEviction(this);
3189}
3190
danakj45d42452020-04-08 17:24:183191blink::mojom::DisplayMode WebContentsImpl::GetDisplayMode() const {
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123192 return delegate_ ? delegate_->GetDisplayMode(this)
Eric Willigers052f0432019-10-04 04:06:573193 : blink::mojom::DisplayMode::kBrowser;
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123194}
3195
avic3aa8422015-11-09 20:57:223196void WebContentsImpl::RequestToLockMouse(
3197 RenderWidgetHostImpl* render_widget_host,
3198 bool user_gesture,
lfgad8244352016-07-13 16:55:513199 bool last_unlocked_by_target,
3200 bool privileged) {
lfgf0cd46e2017-01-04 00:05:233201 for (WebContentsImpl* current = this; current;
3202 current = current->GetOuterWebContents()) {
3203 if (current->mouse_lock_widget_) {
James Hollyerd5c9de462020-03-10 19:02:453204 render_widget_host->GotResponseToLockMouseRequest(
3205 blink::mojom::PointerLockResult::kAlreadyLocked);
lfgf0cd46e2017-01-04 00:05:233206 return;
3207 }
[email protected]e9621112011-10-17 05:38:373208 }
avic3aa8422015-11-09 20:57:223209
lfgad8244352016-07-13 16:55:513210 if (privileged) {
lfgf0cd46e2017-01-04 00:05:233211 DCHECK(!GetOuterWebContents());
lfgad8244352016-07-13 16:55:513212 mouse_lock_widget_ = render_widget_host;
James Hollyerd5c9de462020-03-10 19:02:453213 render_widget_host->GotResponseToLockMouseRequest(
3214 blink::mojom::PointerLockResult::kSuccess);
lfgad8244352016-07-13 16:55:513215 return;
3216 }
3217
lfgbee1e0a2016-06-08 21:24:213218 bool widget_in_frame_tree = false;
3219 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3220 if (node->current_frame_host()->GetRenderWidgetHost() ==
3221 render_widget_host) {
3222 widget_in_frame_tree = true;
3223 break;
3224 }
3225 }
3226
3227 if (widget_in_frame_tree && delegate_) {
lfgf0cd46e2017-01-04 00:05:233228 for (WebContentsImpl* current = this; current;
3229 current = current->GetOuterWebContents()) {
3230 current->mouse_lock_widget_ = render_widget_host;
3231 }
3232
avic3aa8422015-11-09 20:57:223233 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
lfgbee1e0a2016-06-08 21:24:213234 } else {
James Hollyerd5c9de462020-03-10 19:02:453235 render_widget_host->GotResponseToLockMouseRequest(
3236 blink::mojom::PointerLockResult::kWrongDocument);
lfgbee1e0a2016-06-08 21:24:213237 }
[email protected]e9621112011-10-17 05:38:373238}
3239
avi3e4b8512015-11-11 01:55:493240void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
lfgbee1e0a2016-06-08 21:24:213241 CHECK(mouse_lock_widget_);
lfgf0cd46e2017-01-04 00:05:233242
3243 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
3244 return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
3245
lfgbee1e0a2016-06-08 21:24:213246 mouse_lock_widget_->SendMouseLockLost();
lfgf0cd46e2017-01-04 00:05:233247 for (WebContentsImpl* current = this; current;
3248 current = current->GetOuterWebContents()) {
3249 current->mouse_lock_widget_ = nullptr;
3250 }
avi3e4b8512015-11-11 01:55:493251
[email protected]e9621112011-10-17 05:38:373252 if (delegate_)
3253 delegate_->LostMouseLock();
3254}
3255
lfgad8244352016-07-13 16:55:513256bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
3257 // To verify if the mouse is locked, the mouse_lock_widget_ needs to be
3258 // assigned to the widget that requested the mouse lock, and the top-level
3259 // platform RenderWidgetHostView needs to hold the mouse lock from the OS.
Lucas Gadania0ea0172018-09-20 18:31:373260 auto* widget_host = GetTopLevelRenderWidgetHostView();
3261 return mouse_lock_widget_ == render_widget_host && widget_host &&
3262 widget_host->IsMouseLocked();
lfgad8244352016-07-13 16:55:513263}
3264
lfg84763c92017-02-16 18:55:153265RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
Lucas Gadania0ea0172018-09-20 18:31:373266 auto* widget_host = GetTopLevelRenderWidgetHostView();
3267 if ((widget_host && widget_host->IsMouseLocked()) ||
lfge2176fb2017-03-26 00:45:473268 (GetFullscreenRenderWidgetHostView() &&
Lucas Gadania0ea0172018-09-20 18:31:373269 GetFullscreenRenderWidgetHostView()->IsMouseLocked())) {
lfg84763c92017-02-16 18:55:153270 return mouse_lock_widget_;
Lucas Gadania0ea0172018-09-20 18:31:373271 }
lfg84763c92017-02-16 18:55:153272
3273 return nullptr;
3274}
3275
Joe Downing192998b22018-03-22 15:51:363276bool WebContentsImpl::RequestKeyboardLock(
Joe Downing13dd76b2018-04-09 18:32:153277 RenderWidgetHostImpl* render_widget_host,
3278 bool esc_key_locked) {
Joe Downing192998b22018-03-22 15:51:363279 DCHECK(render_widget_host);
Joe Downing192998b22018-03-22 15:51:363280 if (render_widget_host->delegate()->GetAsWebContents() != this) {
3281 NOTREACHED();
3282 return false;
3283 }
3284
3285 // KeyboardLock is only supported when called by the top-level browsing
3286 // context and is not supported in embedded content scenarios.
3287 if (GetOuterWebContents())
3288 return false;
3289
Joe Downing13dd76b2018-04-09 18:32:153290 esc_key_locked_ = esc_key_locked;
Joe Downing192998b22018-03-22 15:51:363291 keyboard_lock_widget_ = render_widget_host;
3292
Joe Downing13dd76b2018-04-09 18:32:153293 if (delegate_)
3294 delegate_->RequestKeyboardLock(this, esc_key_locked_);
Joe Downing192998b22018-03-22 15:51:363295 return true;
3296}
3297
3298void WebContentsImpl::CancelKeyboardLock(
3299 RenderWidgetHostImpl* render_widget_host) {
3300 if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
3301 return;
3302
3303 RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
3304 keyboard_lock_widget_ = nullptr;
3305
Joe Downing13dd76b2018-04-09 18:32:153306 if (delegate_)
3307 delegate_->CancelKeyboardLockRequest(this);
3308
Joe Downing192998b22018-03-22 15:51:363309 old_keyboard_lock_widget->CancelKeyboardLock();
3310}
3311
3312RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
3313 return keyboard_lock_widget_;
3314}
3315
Dave Tapuskac3344362019-02-20 17:54:283316void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(
3317 blink::mojom::FrameVisibility visibility) {
3318 switch (visibility) {
3319 case blink::mojom::FrameVisibility::kRenderedInViewport:
3320 WasShown();
3321 break;
3322 case blink::mojom::FrameVisibility::kNotRendered:
3323 WasHidden();
3324 break;
3325 case blink::mojom::FrameVisibility::kRenderedOutOfViewport:
3326 WasOccluded();
3327 break;
3328 }
ekaramada4f42692016-02-11 19:48:373329}
3330
Albert J. Wong65fe64d2019-09-20 02:48:143331RenderFrameHostDelegate* WebContentsImpl::CreateNewWindow(
csharrison95f01e922017-04-24 18:52:353332 RenderFrameHost* opener,
rockot5c478a72016-09-28 23:14:183333 const mojom::CreateNewWindowParams& params,
Albert J. Wong65fe64d2019-09-20 02:48:143334 bool is_new_browsing_instance,
Sergey Kuznetsov32257a22019-02-11 20:26:503335 bool has_user_gesture,
[email protected]97714c82012-06-06 10:15:133336 SessionStorageNamespace* session_storage_namespace) {
csharrison95f01e922017-04-24 18:52:353337 DCHECK(opener);
nick5ae4d2d2017-01-06 01:18:353338
csharrison95f01e922017-04-24 18:52:353339 int render_process_id = opener->GetProcess()->GetID();
csharrison95f01e922017-04-24 18:52:353340
Albert J. Wong65fe64d2019-09-20 02:48:143341 SiteInstance* source_site_instance = opener->GetSiteInstance();
nick5ae4d2d2017-01-06 01:18:353342
Aaron Colwelleb219982020-01-16 02:17:273343 const GURL source_site_url = source_site_instance->GetSiteURL();
[email protected]fdac6ade2013-07-20 01:06:303344 const std::string& partition_id =
Aaron Colwelleb219982020-01-16 02:17:273345 GetContentClient()->browser()->GetStoragePartitionIdForSite(
3346 GetBrowserContext(), source_site_url);
3347 {
3348 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
3349 GetBrowserContext(), source_site_url);
3350 DOMStorageContextWrapper* dom_storage_context =
3351 static_cast<DOMStorageContextWrapper*>(
3352 partition->GetDOMStorageContext());
3353 SessionStorageNamespaceImpl* session_storage_namespace_impl =
3354 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
3355 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
3356 }
[email protected]dd6730412013-08-14 15:03:373357
Albert J. Wong1ceccef92019-10-08 08:25:203358 if (delegate_ && delegate_->IsWebContentsCreationOverridden(
3359 source_site_instance, params.window_container_type,
3360 opener->GetLastCommittedURL(), params.frame_name,
3361 params.target_url)) {
3362 return static_cast<WebContentsImpl*>(delegate_->CreateCustomWebContents(
3363 opener, source_site_instance, is_new_browsing_instance,
3364 opener->GetLastCommittedURL(), params.frame_name, params.target_url,
3365 partition_id, session_storage_namespace));
[email protected]dd6730412013-08-14 15:03:373366 }
3367
danakj22b4e8b2019-08-01 23:14:393368 bool renderer_started_hidden =
3369 params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB;
3370
Aaron Colwelleb219982020-01-16 02:17:273371 // We usually create the new window in the same BrowsingInstance (group of
3372 // script-related windows), by passing in the current SiteInstance. However,
3373 // if the opener is being suppressed (in a non-guest), we do not provide
3374 // a SiteInstance which causes a new one to get created in its own
3375 // BrowsingInstance.
3376 bool is_guest = BrowserPluginGuest::IsGuest(this);
3377 scoped_refptr<SiteInstance> site_instance =
3378 params.opener_suppressed && !is_guest ? nullptr : source_site_instance;
3379
[email protected]dd6730412013-08-14 15:03:373380 // Create the new web contents. This will automatically create the new
3381 // WebContentsView. In the future, we may want to create the view separately.
[email protected]fc72bb12013-06-02 21:13:463382 CreateParams create_params(GetBrowserContext(), site_instance.get());
nasko48321ca32015-07-02 20:44:123383 create_params.main_frame_name = params.frame_name;
alexmos4cf2aa32015-07-15 23:40:433384 create_params.opener_render_process_id = render_process_id;
csharrison95f01e922017-04-24 18:52:353385 create_params.opener_render_frame_id = opener->GetRoutingID();
[email protected]50d326e2014-05-20 17:59:063386 create_params.opener_suppressed = params.opener_suppressed;
danakj22b4e8b2019-08-01 23:14:393387 create_params.initially_hidden = renderer_started_hidden;
[email protected]50d326e2014-05-20 17:59:063388
Albert J. Wong65fe64d2019-09-20 02:48:143389 // Even though all codepaths leading here are in response to a renderer
3390 // tryng to open a new window, if the new window ends up in a different
3391 // browsing instance, then the RenderViewHost, RenderWidgetHost,
3392 // RenderFrameHost constellation is effectively browser initiated
3393 // the opener's process will not given the routing IDs for the new
3394 // objects.
3395 create_params.renderer_initiated_creation = !is_new_browsing_instance;
Albert J. Wong1ceccef92019-10-08 08:25:203396
Albert J. Wong65fe64d2019-09-20 02:48:143397 std::unique_ptr<WebContentsImpl> new_contents;
[email protected]c4538072013-03-18 02:17:553398 if (!is_guest) {
3399 create_params.context = view_->GetNativeView();
Albert J. Wong65fe64d2019-09-20 02:48:143400 new_contents = WebContentsImpl::Create(create_params);
3401 } else {
3402 new_contents = base::WrapUnique(static_cast<WebContentsImpl*>(
3403 GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)));
[email protected]c4538072013-03-18 02:17:553404 }
Albert J. Wong65fe64d2019-09-20 02:48:143405 auto* new_contents_impl = new_contents.get();
danakje6c01622018-10-05 19:39:263406
3407 new_contents_impl->GetController().SetSessionStorageNamespace(
erikchenbee5c9622018-04-27 19:30:253408 partition_id, session_storage_namespace);
[email protected]d1198fd2012-08-13 22:50:193409
alexmos646fec02015-07-25 00:11:493410 // If the new frame has a name, make sure any SiteInstances that can find
3411 // this named frame have proxies for it. Must be called after
3412 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
3413 // GetSessionStorageNamespace.
3414 if (!params.frame_name.empty())
danakje6c01622018-10-05 19:39:263415 new_contents_impl->GetRenderManager()->CreateProxiesForNewNamedFrame();
alexmos646fec02015-07-25 00:11:493416
[email protected]c4538072013-03-18 02:17:553417 // Save the window for later if we're not suppressing the opener (since it
[email protected]d70bea92013-04-05 04:23:343418 // will be shown immediately).
3419 if (!params.opener_suppressed) {
3420 if (!is_guest) {
danakje6c01622018-10-05 19:39:263421 WebContentsView* new_view = new_contents_impl->view_.get();
[email protected]bafe6cd2012-05-23 23:09:503422
[email protected]d70bea92013-04-05 04:23:343423 // TODO(brettw): It seems bogus that we have to call this function on the
3424 // newly created object and give it one of its own member variables.
danakj22b4e8b2019-08-01 23:14:393425 RenderWidgetHostView* widget_view = new_view->CreateViewForWidget(
W. James MacLean13d834d2019-12-04 16:06:453426 new_contents_impl->GetRenderViewHost()->GetWidget());
danakj22b4e8b2019-08-01 23:14:393427 if (!renderer_started_hidden) {
3428 // RenderWidgets for frames always initialize as hidden. If the renderer
3429 // created this window as visible, then we show it here.
3430 widget_view->Show();
3431 }
[email protected]d70bea92013-04-05 04:23:343432 }
[email protected]bafe6cd2012-05-23 23:09:503433 // Save the created window associated with the route so we can show it
3434 // later.
Albert J. Wongcb004632018-07-10 22:58:253435 //
3436 // TODO(ajwong): This should be keyed off the RenderFrame routing id or the
3437 // FrameTreeNode id instead of the routing id of the Widget for the main
3438 // frame. https://crbug.com/545684
Fergal Daly052873a82020-03-11 14:45:493439 int32_t main_frame_routing_id = new_contents_impl->GetMainFrame()
3440 ->GetRenderWidgetHost()
3441 ->GetRoutingID();
3442 GlobalRoutingID id(render_process_id, main_frame_routing_id);
Joel Hockey8c2011b22020-04-30 05:07:193443 pending_contents_[id] =
3444 CreatedWindow(std::move(new_contents), params.target_url);
danakje6c01622018-10-05 19:39:263445 AddDestructionObserver(new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503446 }
3447
3448 if (delegate_) {
Bryan McQuaded2b93c02017-07-14 22:26:313449 delegate_->WebContentsCreated(this, render_process_id,
3450 opener->GetRoutingID(), params.frame_name,
danakje6c01622018-10-05 19:39:263451 params.target_url, new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503452 }
3453
Alexander Timin90c20c32020-08-12 15:28:323454 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3455 observer->DidOpenRequestedURL(new_contents_impl, opener, params.target_url,
3456 params.referrer.To<Referrer>(),
3457 params.disposition, ui::PAGE_TRANSITION_LINK,
3458 false, // started_from_context_menu
3459 true); // renderer_initiated
3460 });
pnolandaae574e2017-03-06 21:04:213461
[email protected]bafe6cd2012-05-23 23:09:503462 if (params.opener_suppressed) {
3463 // When the opener is suppressed, the original renderer cannot access the
3464 // new window. As a result, we need to show and navigate the window here.
[email protected]eda238a12012-09-07 23:44:003465 bool was_blocked = false;
erikchenbee5c9622018-04-27 19:30:253466
[email protected]eda238a12012-09-07 23:44:003467 if (delegate_) {
danakje6c01622018-10-05 19:39:263468 base::WeakPtr<WebContentsImpl> weak_new_contents =
3469 new_contents_impl->weak_factory_.GetWeakPtr();
nick0d558482017-02-13 22:27:223470
danakje6c01622018-10-05 19:39:263471 gfx::Rect initial_rect; // Report an empty initial rect.
Albert J. Wong65fe64d2019-09-20 02:48:143472 delegate_->AddNewContents(this, std::move(new_contents),
Joel Hockey891e88062020-04-30 05:38:443473 params.target_url, params.disposition,
3474 initial_rect, has_user_gesture, &was_blocked);
danakje6c01622018-10-05 19:39:263475 // The delegate may delete |new_contents_impl| during AddNewContents().
nick0d558482017-02-13 22:27:223476 if (!weak_new_contents)
Albert J. Wong65fe64d2019-09-20 02:48:143477 return nullptr;
[email protected]eda238a12012-09-07 23:44:003478 }
erikchenbee5c9622018-04-27 19:30:253479
[email protected]eda238a12012-09-07 23:44:003480 if (!was_blocked) {
Nasko Oskov83a8cf92018-10-19 14:58:563481 std::unique_ptr<NavigationController::LoadURLParams> load_params =
3482 std::make_unique<NavigationController::LoadURLParams>(
3483 params.target_url);
Nasko Oskov93e7c55c2018-12-19 01:59:293484 load_params->initiator_origin = opener->GetLastCommittedOrigin();
Lukasz Anforowiczd2629b42020-08-11 16:07:313485 // Avoiding setting |load_params->source_site_instance| when
3486 // |opener_suppressed| is true, because in that case we do not want to use
3487 // the old SiteInstance and/or BrowsingInstance. See also the test here:
3488 // NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener.
Leon Han963dc182018-11-06 05:41:483489 load_params->referrer = params.referrer.To<Referrer>();
Nasko Oskov83a8cf92018-10-19 14:58:563490 load_params->transition_type = ui::PAGE_TRANSITION_LINK;
3491 load_params->is_renderer_initiated = true;
Sergey Kuznetsov32257a22019-02-11 20:26:503492 load_params->has_user_gesture = has_user_gesture;
mariakhomenkoa4971c12015-07-21 19:04:373493
3494 if (delegate_ && !is_guest &&
3495 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
Nasko Oskov83a8cf92018-10-19 14:58:563496 // We are in asynchronous add new contents path, delay navigation.
3497 DCHECK(!new_contents_impl->delayed_open_url_params_);
3498 new_contents_impl->delayed_load_url_params_ = std::move(load_params);
mariakhomenkoa4971c12015-07-21 19:04:373499 } else {
Nasko Oskov83a8cf92018-10-19 14:58:563500 new_contents_impl->controller_.LoadURLWithParams(*load_params.get());
Nasko Oskov28ebd5b2018-12-07 22:29:333501 if (!is_guest)
3502 new_contents_impl->Focus();
mariakhomenkoa4971c12015-07-21 19:04:373503 }
[email protected]eda238a12012-09-07 23:44:003504 }
[email protected]bafe6cd2012-05-23 23:09:503505 }
Albert J. Wong65fe64d2019-09-20 02:48:143506 return new_contents_impl;
[email protected]bafe6cd2012-05-23 23:09:503507}
3508
Dave Tapuskad9835622020-03-10 17:32:313509void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053510 AgentSchedulingGroupHost& agent_scheduling_group,
3511 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303512 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3513 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053514 CreateNewWidget(agent_scheduling_group, route_id,
3515 /*is_fullscreen=*/false, std::move(blink_widget_host),
3516 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503517}
3518
Julie Jeongeun Kimcaacf9102019-09-12 02:13:053519void WebContentsImpl::CreateNewFullscreenWidget(
Tal Pressman5dcd2382020-08-26 07:13:053520 AgentSchedulingGroupHost& agent_scheduling_group,
3521 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303522 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3523 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053524 CreateNewWidget(agent_scheduling_group, route_id,
3525 /*is_fullscreen=*/true, std::move(blink_widget_host),
3526 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503527}
3528
Dave Tapuskad9835622020-03-10 17:32:313529void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053530 AgentSchedulingGroupHost& agent_scheduling_group,
Dave Tapuskad9835622020-03-10 17:32:313531 int32_t route_id,
3532 bool is_fullscreen,
Dave Tapuska8499eec2020-03-16 17:54:303533 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3534 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053535 RenderProcessHost* process = agent_scheduling_group.GetProcess();
kenrbb46f86a2015-12-07 07:53:233536 // A message to create a new widget can only come from an active process for
[email protected]a8504022013-12-04 20:23:513537 // this WebContentsImpl instance. If any other process sends the request,
3538 // it is invalid and the process must be terminated.
Tal Pressman5dcd2382020-08-26 07:13:053539 if (!HasMatchingProcess(&frame_tree_, process->GetID())) {
Lukasz Anforowicz6f746282018-01-04 23:24:513540 ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
[email protected]a8504022013-12-04 20:23:513541 return;
3542 }
3543
Tal Pressman5dcd2382020-08-26 07:13:053544 RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(
3545 this, agent_scheduling_group, route_id, IsHidden(),
3546 std::make_unique<FrameTokenMessageQueue>());
Dave Tapuska8499eec2020-03-16 17:54:303547
3548 widget_host->BindWidgetInterfaces(std::move(blink_widget_host),
3549 std::move(blink_widget));
[email protected]cfd80b02014-05-01 17:46:483550 RenderWidgetHostViewBase* widget_view =
3551 static_cast<RenderWidgetHostViewBase*>(
danakj0b246942018-09-17 21:30:273552 view_->CreateViewForChildWidget(widget_host));
[email protected]83918ec2013-01-10 15:37:193553 if (!widget_view)
3554 return;
danakj0b246942018-09-17 21:30:273555 // Fullscreen child widgets are frames, other child widgets are popups, and
3556 // popups should not get activated.
3557 if (!is_fullscreen)
3558 widget_view->SetWidgetType(WidgetType::kPopup);
[email protected]bafe6cd2012-05-23 23:09:503559 // Save the created widget associated with the route so we can show it later.
Tal Pressman5dcd2382020-08-26 07:13:053560 pending_widget_views_[GlobalRoutingID(process->GetID(), route_id)] =
alexmosc2a8cec2016-05-23 22:19:533561 widget_view;
[email protected]bafe6cd2012-05-23 23:09:503562}
3563
Mike Wassermandabad612020-08-13 04:26:273564void WebContentsImpl::ShowCreatedWindow(RenderFrameHost* opener,
nick5ae4d2d2017-01-06 01:18:353565 int main_frame_widget_route_id,
[email protected]bafe6cd2012-05-23 23:09:503566 WindowOpenDisposition disposition,
bokan107a47f2015-02-03 23:23:393567 const gfx::Rect& initial_rect,
[email protected]bafe6cd2012-05-23 23:09:503568 bool user_gesture) {
danakje6c01622018-10-05 19:39:263569 // This method is the renderer requesting an existing top level window to
3570 // show a new top level window that the renderer created. Each top level
3571 // window is associated with a WebContents. In this case it was created
3572 // earlier but showing it was deferred until the renderer requested for it
3573 // to be shown. We find that previously created WebContents here.
3574 // TODO(danakj): Why do we defer this show step until the renderer asks for it
3575 // when it will always do so. What needs to happen in the renderer before we
3576 // reach here?
Mike Wassermandabad612020-08-13 04:26:273577 base::Optional<CreatedWindow> owned_created = GetCreatedWindow(
3578 opener->GetProcess()->GetID(), main_frame_widget_route_id);
Joel Hockey8c2011b22020-04-30 05:07:193579
danakje6c01622018-10-05 19:39:263580 // The browser may have rejected the request to make a new window, or the
3581 // renderer could be sending an invalid route id. Ignore the request then.
Joel Hockey8c2011b22020-04-30 05:07:193582 if (!owned_created || !owned_created->contents)
danakje6c01622018-10-05 19:39:263583 return;
mariakhomenko44bdc4732015-04-29 01:55:383584
Joel Hockey8c2011b22020-04-30 05:07:193585 WebContentsImpl* created = owned_created->contents.get();
3586
danakje6c01622018-10-05 19:39:263587 // This uses the delegate for the WebContents where the window was created
3588 // from, to control how to show the newly created window.
3589 WebContentsDelegate* delegate = GetDelegate();
nick5ae4d2d2017-01-06 01:18:353590
Mike Wassermanb6bc0152020-08-25 22:46:203591 // Individual members of |initial_rect| may be 0 to indicate that the
3592 // window.open() feature string did not specify a value. This code does not
3593 // have the ability to distinguish between an unspecified value and 0.
3594 // Assume that if any single value is non-zero, all values should be used.
3595 // TODO(crbug.com/897300): Plumb values as specified; set defaults here?
3596 gfx::Rect adjusted_rect = initial_rect;
3597 int64_t display_id = display::kInvalidDisplayId;
3598 if (adjusted_rect != gfx::Rect())
3599 display_id = AdjustRequestedWindowBounds(&adjusted_rect, opener);
3600
3601 // Drop fullscreen when opening a WebContents to prohibit deceptive behavior.
3602 // Only drop fullscreen on the specific destination display, if it is known.
3603 // This supports sites using cross-screen window placement capabilities to
3604 // retain fullscreen and open a window on another screen.
3605 ForSecurityDropFullscreen(display_id).RunAndReset();
3606
danakje6c01622018-10-05 19:39:263607 // The delegate can be null in tests, so we must check for it :(.
3608 if (delegate) {
3609 // Mark the web contents as pending resume, then immediately do
3610 // the resume if the delegate wants it.
3611 created->is_resume_pending_ = true;
3612 if (delegate->ShouldResumeRequestsForCreatedWindow())
3613 created->ResumeLoadingCreatedWebContents();
3614
3615 base::WeakPtr<WebContentsImpl> weak_created =
3616 created->weak_factory_.GetWeakPtr();
Joel Hockey8c2011b22020-04-30 05:07:193617 delegate->AddNewContents(this, std::move(owned_created->contents),
Joel Hockey891e88062020-04-30 05:38:443618 std::move(owned_created->target_url), disposition,
Mike Wassermandabad612020-08-13 04:26:273619 adjusted_rect, user_gesture, nullptr);
danakje6c01622018-10-05 19:39:263620 // The delegate may delete |created| during AddNewContents().
3621 if (!weak_created)
3622 return;
[email protected]eda238a12012-09-07 23:44:003623 }
danakje6c01622018-10-05 19:39:263624
3625 RenderWidgetHostImpl* rwh = created->GetMainFrame()->GetRenderWidgetHost();
3626 DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
3627 rwh->Send(new WidgetMsg_SetBounds_ACK(rwh->GetRoutingID()));
[email protected]bafe6cd2012-05-23 23:09:503628}
3629
alexmosc2a8cec2016-05-23 22:19:533630void WebContentsImpl::ShowCreatedWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473631 int widget_route_id,
bokan107a47f2015-02-03 23:23:393632 const gfx::Rect& initial_rect) {
Albert J. Wongf6e13ed2018-09-18 15:25:473633 ShowCreatedWidget(process_id, widget_route_id, false, initial_rect);
[email protected]bafe6cd2012-05-23 23:09:503634}
3635
alexmosc2a8cec2016-05-23 22:19:533636void WebContentsImpl::ShowCreatedFullscreenWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473637 int widget_route_id) {
3638 ShowCreatedWidget(process_id, widget_route_id, true, gfx::Rect());
[email protected]bafe6cd2012-05-23 23:09:503639}
3640
alexmosc2a8cec2016-05-23 22:19:533641void WebContentsImpl::ShowCreatedWidget(int process_id,
3642 int route_id,
[email protected]bafe6cd2012-05-23 23:09:503643 bool is_fullscreen,
bokan107a47f2015-02-03 23:23:393644 const gfx::Rect& initial_rect) {
[email protected]cfd80b02014-05-01 17:46:483645 RenderWidgetHostViewBase* widget_host_view =
alexmosc2a8cec2016-05-23 22:19:533646 static_cast<RenderWidgetHostViewBase*>(
3647 GetCreatedWidget(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503648 if (!widget_host_view)
3649 return;
[email protected]cfd80b02014-05-01 17:46:483650
W. James MacLeanec4125c2019-09-27 18:56:003651 // GetOutermostWebContents() returns |this| if there are no outer WebContents.
W. James MacLean3c5f50462019-10-28 16:24:213652 auto* outer_web_contents = GetOuterWebContents();
3653 auto* outermost_web_contents = GetOutermostWebContents();
W. James MacLeanec4125c2019-09-27 18:56:003654 RenderWidgetHostView* view =
W. James MacLean3c5f50462019-10-28 16:24:213655 outermost_web_contents->GetRenderWidgetHostView();
3656 // It's not entirely obvious why we need the transform only in the case where
3657 // the outer webcontents is not the same as the outermost webcontents. It may
3658 // be due to the fact that oopifs that are children of the mainframe get
3659 // correct values for their screenrects, but deeper cross-process frames do
3660 // not. Hopefully this can be resolved with https://crbug.com/928825.
3661 // Handling these cases separately is needed for http://crbug.com/1015298.
3662 bool needs_transform = this != outermost_web_contents &&
3663 outermost_web_contents != outer_web_contents;
W. James MacLeanec4125c2019-09-27 18:56:003664
3665 gfx::Rect transformed_rect(initial_rect);
3666 RenderWidgetHostView* this_view = GetRenderWidgetHostView();
W. James MacLean3c5f50462019-10-28 16:24:213667 if (needs_transform) {
W. James MacLeanec4125c2019-09-27 18:56:003668 // We need to transform the coordinates of initial_rect.
3669 gfx::Point origin =
3670 this_view->TransformPointToRootCoordSpace(initial_rect.origin());
3671 gfx::Point bottom_right =
3672 this_view->TransformPointToRootCoordSpace(initial_rect.bottom_right());
3673 transformed_rect =
3674 gfx::Rect(origin.x(), origin.y(), bottom_right.x() - origin.x(),
3675 bottom_right.y() - origin.y());
[email protected]cfd80b02014-05-01 17:46:483676 }
3677
danakj0b246942018-09-17 21:30:273678 // Fullscreen child widgets are frames, other child widgets are popups.
[email protected]4aebbca2013-09-17 22:26:493679 if (is_fullscreen) {
[email protected]d7f80ba2013-10-12 07:42:313680 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
[email protected]0b431992014-06-24 00:08:033681 view_->StoreFocus();
alexmosc9e76ec2016-05-16 22:59:373682 fullscreen_widget_process_id_ =
3683 widget_host_view->GetRenderWidgetHost()->GetProcess()->GetID();
[email protected]d7f80ba2013-10-12 07:42:313684 fullscreen_widget_routing_id_ = route_id;
[email protected]4aebbca2013-09-17 22:26:493685 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
3686 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
Mike Wasserman4ca09792020-05-29 17:44:433687 delegate_->EnterFullscreenModeForTab(GetMainFrame(),
Dave Tapuskaa4189512019-10-15 20:27:343688 blink::mojom::FullscreenOptions());
[email protected]4aebbca2013-09-17 22:26:493689 } else {
[email protected]cfd80b02014-05-01 17:46:483690 widget_host_view->InitAsFullscreen(view);
[email protected]4aebbca2013-09-17 22:26:493691 }
Alexander Timin90c20c32020-08-12 15:28:323692 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3693 observer->DidShowFullscreenWidget();
3694 });
[email protected]4aebbca2013-09-17 22:26:493695 if (!widget_host_view->HasFocus())
3696 widget_host_view->Focus();
3697 } else {
W. James MacLeanec4125c2019-09-27 18:56:003698 widget_host_view->InitAsPopup(view, transformed_rect);
[email protected]4aebbca2013-09-17 22:26:493699 }
[email protected]89054502012-06-03 10:29:243700
yiyixcb1fbc4f2018-03-16 19:54:083701 RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
[email protected]89054502012-06-03 10:29:243702 render_widget_host_impl->Init();
[email protected]d7f80ba2013-10-12 07:42:313703 // Only allow privileged mouse lock for fullscreen render widget, which is
3704 // used to implement Pepper Flash fullscreen.
3705 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
[email protected]bafe6cd2012-05-23 23:09:503706}
3707
Joel Hockey8c2011b22020-04-30 05:07:193708base::Optional<CreatedWindow> WebContentsImpl::GetCreatedWindow(
nick5ae4d2d2017-01-06 01:18:353709 int process_id,
3710 int main_frame_widget_route_id) {
Lukasz Anforowicz09060bdf72018-08-23 15:53:173711 auto key = GlobalRoutingID(process_id, main_frame_widget_route_id);
nick5ae4d2d2017-01-06 01:18:353712 auto iter = pending_contents_.find(key);
[email protected]bafe6cd2012-05-23 23:09:503713
3714 // Certain systems can block the creation of new windows. If we didn't succeed
3715 // in creating one, just return NULL.
alexmosc2a8cec2016-05-23 22:19:533716 if (iter == pending_contents_.end())
Joel Hockey8c2011b22020-04-30 05:07:193717 return base::nullopt;
[email protected]bafe6cd2012-05-23 23:09:503718
Joel Hockey8c2011b22020-04-30 05:07:193719 CreatedWindow result = std::move(iter->second);
3720 WebContentsImpl* new_contents = result.contents.get();
nick5ae4d2d2017-01-06 01:18:353721 pending_contents_.erase(key);
Joel Hockey8c2011b22020-04-30 05:07:193722 RemoveDestructionObserver(new_contents);
[email protected]bafe6cd2012-05-23 23:09:503723
[email protected]d70bea92013-04-05 04:23:343724 // Don't initialize the guest WebContents immediately.
Joel Hockey8c2011b22020-04-30 05:07:193725 if (BrowserPluginGuest::IsGuest(new_contents))
3726 return result;
[email protected]d70bea92013-04-05 04:23:343727
Lukasz Anforowicz5510ed652018-06-06 16:16:193728 if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() ||
nick5ae4d2d2017-01-06 01:18:353729 !new_contents->GetMainFrame()->GetView()) {
Joel Hockey8c2011b22020-04-30 05:07:193730 return base::nullopt;
nick5ae4d2d2017-01-06 01:18:353731 }
[email protected]bafe6cd2012-05-23 23:09:503732
Joel Hockey8c2011b22020-04-30 05:07:193733 return result;
[email protected]bafe6cd2012-05-23 23:09:503734}
3735
alexmosc2a8cec2016-05-23 22:19:533736RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
3737 int route_id) {
Lukasz Anforowicz09060bdf72018-08-23 15:53:173738 auto iter = pending_widget_views_.find(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503739 if (iter == pending_widget_views_.end()) {
3740 DCHECK(false);
alexmosc2a8cec2016-05-23 22:19:533741 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503742 }
3743
3744 RenderWidgetHostView* widget_host_view = iter->second;
Lukasz Anforowicz09060bdf72018-08-23 15:53:173745 pending_widget_views_.erase(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503746
3747 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
Lukasz Anforowicz5510ed652018-06-06 16:16:193748 if (!widget_host->GetProcess()->IsInitializedAndNotDead()) {
[email protected]bafe6cd2012-05-23 23:09:503749 // The view has gone away or the renderer crashed. Nothing to do.
alexmosc2a8cec2016-05-23 22:19:533750 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:503751 }
3752
3753 return widget_host_view;
3754}
3755
[email protected]f13b4202012-06-12 23:53:233756void WebContentsImpl::RequestMediaAccessPermission(
[email protected]33662e52013-01-07 21:31:093757 const MediaStreamRequest& request,
Mark Pilgrim57499082018-06-12 12:38:303758 MediaResponseCallback callback) {
[email protected]d19b84b2014-03-14 11:52:373759 if (delegate_) {
Mark Pilgrim57499082018-06-12 12:38:303760 delegate_->RequestMediaAccessPermission(this, request, std::move(callback));
[email protected]d19b84b2014-03-14 11:52:373761 } else {
Antonio Gomes0d42960a2019-06-05 12:35:513762 std::move(callback).Run(
3763 blink::MediaStreamDevices(),
3764 blink::mojom::MediaStreamRequestResult::FAILED_DUE_TO_SHUTDOWN,
3765 std::unique_ptr<MediaStreamUI>());
[email protected]d19b84b2014-03-14 11:52:373766 }
[email protected]f13b4202012-06-12 23:53:233767}
3768
Chandan Padhia4b8bcb72017-09-12 16:41:043769bool WebContentsImpl::CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:583770 RenderFrameHost* render_frame_host,
Chandan Padhia4b8bcb72017-09-12 16:41:043771 const url::Origin& security_origin,
Antonio Gomesc8b734b2019-06-05 18:22:163772 blink::mojom::MediaStreamType type) {
3773 DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
3774 type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
Chandan Padhia4b8bcb72017-09-12 16:41:043775 return delegate_ && delegate_->CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:583776 render_frame_host, security_origin.GetURL(), type);
grunell657d4d82014-09-18 00:09:433777}
3778
Guido Urdaneta73fa6632019-01-14 18:46:263779std::string WebContentsImpl::GetDefaultMediaDeviceID(
Antonio Gomesc8b734b2019-06-05 18:22:163780 blink::mojom::MediaStreamType type) {
guidou8a440b842017-01-30 13:58:433781 if (!delegate_)
3782 return std::string();
3783 return delegate_->GetDefaultMediaDeviceID(this, type);
3784}
3785
[email protected]cc9200432013-07-23 23:02:403786SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
3787 SiteInstance* instance) {
3788 return controller_.GetSessionStorageNamespace(instance);
3789}
3790
[email protected]6de7fc482014-06-06 10:46:443791SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
3792 return controller_.GetSessionStorageNamespaceMap();
3793}
3794
[email protected]9b159a52013-10-03 17:24:553795FrameTree* WebContentsImpl::GetFrameTree() {
3796 return &frame_tree_;
3797}
3798
aelias5252baa2016-04-10 01:18:023799bool WebContentsImpl::IsOverridingUserAgent() {
3800 return GetController().GetVisibleEntry() &&
3801 GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
3802}
3803
avi85ee8362016-10-08 02:09:083804bool WebContentsImpl::IsJavaScriptDialogShowing() const {
3805 return is_showing_javascript_dialog_;
3806}
3807
avic031d392017-03-03 03:09:423808bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:003809 if (suppress_unresponsive_renderer_count_ > 0)
3810 return true;
3811
avic031d392017-03-03 03:09:423812 // Ignore unresponsive renderers if the debugger is attached to them since the
3813 // unresponsiveness might be a result of the renderer sitting on a breakpoint.
3814 //
David Bienvenu525f8a02019-02-15 02:02:423815#ifdef OS_WIN
3816 // Check if a windows debugger is attached to the renderer process.
3817 base::ProcessHandle process_handle =
3818 GetMainFrame()->GetProcess()->GetProcess().Handle();
3819 BOOL debugger_present = FALSE;
3820 if (CheckRemoteDebuggerPresent(process_handle, &debugger_present) &&
3821 debugger_present)
3822 return true;
3823#endif // OS_WIN
3824
avic031d392017-03-03 03:09:423825 // TODO(pfeldman): Fix this to only return true if the renderer is *actually*
3826 // sitting on a breakpoint. https://crbug.com/684202
3827 return DevToolsAgentHost::IsDebuggerAttached(this);
3828}
3829
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:413830ui::AXMode WebContentsImpl::GetAccessibilityMode() {
[email protected]95640212014-07-26 18:14:303831 return accessibility_mode_;
3832}
3833
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403834void WebContentsImpl::AXTreeIDForMainFrameHasChanged() {
3835 RenderWidgetHostViewBase* rwhv =
3836 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
3837 if (rwhv)
3838 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
3839
Alexander Timin90c20c32020-08-12 15:28:323840 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3841 observer->AXTreeIDForMainFrameHasChanged();
3842 });
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:403843}
3844
Dominic Mazzonia7b0edb22017-08-09 16:32:513845void WebContentsImpl::AccessibilityEventReceived(
Dominic Mazzoniccbaa9b2018-06-06 07:44:233846 const AXEventNotificationDetails& details) {
Alexander Timin90c20c32020-08-12 15:28:323847 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3848 observer->AccessibilityEventReceived(details);
3849 });
[email protected]31a71eaf2014-03-13 01:47:363850}
3851
dmazzoni2400c462016-08-23 15:07:133852void WebContentsImpl::AccessibilityLocationChangesReceived(
3853 const std::vector<AXLocationChangeNotificationDetails>& details) {
Alexander Timin90c20c32020-08-12 15:28:323854 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3855 observer->AccessibilityLocationChangesReceived(details);
3856 });
dmazzoni2400c462016-08-23 15:07:133857}
3858
Alexander Surkov2ab51622020-09-02 12:01:423859std::string WebContentsImpl::DumpAccessibilityTree(
Abigail Kleinabb428332019-09-13 18:26:213860 bool internal,
3861 std::vector<AccessibilityTreeFormatter::PropertyFilter> property_filters) {
James Wallace-Leeeafc94cb92018-07-23 21:35:093862 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
3863 DCHECK(ax_mgr);
Lei Zhangc98caa3822019-11-07 19:17:273864 return AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager(
Abigail Kleinabb428332019-09-13 18:26:213865 ax_mgr, internal, property_filters);
James Wallace-Leeeafc94cb92018-07-23 21:35:093866}
3867
Abigail Kleinaa898742019-11-01 02:31:253868void WebContentsImpl::RecordAccessibilityEvents(
Abigail Kleinbb8304bd2020-05-18 21:44:183869 bool start_recording,
3870 base::Optional<AccessibilityEventCallback> callback) {
3871 // Only pass a callback to RecordAccessibilityEvents when starting to record.
3872 DCHECK_EQ(start_recording, callback.has_value());
3873 if (start_recording) {
Abigail Kleinaa898742019-11-01 02:31:253874 SetAccessibilityMode(ui::AXMode::kWebContents);
3875 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
3876 DCHECK(ax_mgr);
3877 base::ProcessId pid = base::Process::Current().Pid();
3878 event_recorder_ = content::AccessibilityEventRecorder::Create(
3879 ax_mgr, pid, base::StringPiece{});
Abigail Kleinbb8304bd2020-05-18 21:44:183880 event_recorder_->ListenToEvents(*callback);
Abigail Kleinaa898742019-11-01 02:31:253881 } else {
Abigail Kleinbb8304bd2020-05-18 21:44:183882 if (event_recorder_) {
3883 event_recorder_->FlushAsyncEvents();
3884 event_recorder_.reset(nullptr);
3885 }
Abigail Kleinaa898742019-11-01 02:31:253886 }
3887}
3888
dmazzonia656928e2014-09-15 20:28:543889RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
fsamuel833ee7c2015-02-13 23:40:403890 RenderFrameHost* render_frame_host,
dmazzonia656928e2014-09-15 20:28:543891 int browser_plugin_instance_id) {
3892 BrowserPluginGuestManager* guest_manager =
3893 GetBrowserContext()->GetGuestManager();
fsamuel9cbc00a2015-04-17 20:30:203894 if (!guest_manager)
3895 return nullptr;
3896
dmazzonia656928e2014-09-15 20:28:543897 WebContents* guest = guest_manager->GetGuestByInstanceID(
fsamuel2e9413d2015-02-25 01:25:443898 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
dmazzonia656928e2014-09-15 20:28:543899 if (!guest)
fsamuel9cbc00a2015-04-17 20:30:203900 return nullptr;
3901
dmazzonia656928e2014-09-15 20:28:543902 return guest->GetMainFrame();
3903}
3904
Ke He7319dbe2017-11-09 05:54:443905device::mojom::GeolocationContext* WebContentsImpl::GetGeolocationContext() {
Ella Ge3e375b702020-06-05 15:57:163906 if (delegate_) {
3907 auto* installed_webapp_context =
3908 delegate_->GetInstalledWebappGeolocationContext();
3909 if (installed_webapp_context)
3910 return installed_webapp_context;
3911 }
3912
Ken Rockotce010f02019-12-12 23:32:323913 if (!geolocation_context_) {
3914 GetDeviceService().BindGeolocationContext(
3915 geolocation_context_.BindNewPipeAndPassReceiver());
3916 }
Conley Owens6894c4f2017-07-10 19:29:133917 return geolocation_context_.get();
blundellc57b93f2014-10-29 13:19:573918}
3919
ke.he98b761e2017-05-09 05:59:173920device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() {
blundelld8cd72b2017-03-28 07:18:383921 if (!wake_lock_context_host_)
3922 wake_lock_context_host_.reset(new WakeLockContextHost(this));
blundelle75a8f92017-03-27 08:11:173923 return wake_lock_context_host_->GetWakeLockContext();
alogvinovf50445a2015-10-30 13:00:123924}
3925
blundellf5316fc2017-05-15 11:49:033926#if defined(OS_ANDROID)
Miyoung Shin59f39ff2019-09-17 07:23:203927void WebContentsImpl::GetNFC(
Reilly Grantafbe2242020-02-20 21:14:553928 RenderFrameHost* render_frame_host,
Miyoung Shin59f39ff2019-09-17 07:23:203929 mojo::PendingReceiver<device::mojom::NFC> receiver) {
Reilly Grantafbe2242020-02-20 21:14:553930 if (!nfc_host_)
3931 nfc_host_ = std::make_unique<NFCHost>(this);
3932 nfc_host_->GetNFC(render_frame_host, std::move(receiver));
blundellf5316fc2017-05-15 11:49:033933}
3934#endif
3935
Evan Stade5e750ad02017-08-07 21:59:273936void WebContentsImpl::SetNotWaitingForResponse() {
3937 if (waiting_for_response_ == false)
3938 return;
3939
3940 waiting_for_response_ = false;
3941 if (delegate_)
3942 delegate_->LoadingStateChanged(this, is_load_to_different_document_);
Alexander Timin90c20c32020-08-12 15:28:323943 observers_.ForEachObserver(
3944 [&](WebContentsObserver* observer) { observer->DidReceiveResponse(); });
Evan Stade5e750ad02017-08-07 21:59:273945}
3946
lfgbb9c28a2016-03-01 03:19:493947void WebContentsImpl::SendScreenRects() {
kenrbc52e1b4e2016-03-20 01:03:373948 for (FrameTreeNode* node : frame_tree_.Nodes()) {
kenrb0e8dc202016-05-30 19:51:403949 if (node->current_frame_host()->is_local_root())
kenrbc52e1b4e2016-03-20 01:03:373950 node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
3951 }
[email protected]32deec62013-05-15 23:55:043952}
3953
ekaramadadd882292016-06-08 15:22:563954TextInputManager* WebContentsImpl::GetTextInputManager() {
3955 if (GetOuterWebContents())
3956 return GetOuterWebContents()->GetTextInputManager();
3957
Ehsan Karamadc179dc02018-12-15 03:09:293958 if (!text_input_manager_ && !browser_plugin_guest_) {
Darren Shenca53d5f2018-05-15 04:56:013959 text_input_manager_.reset(new TextInputManager(
3960 GetBrowserContext() &&
3961 !GetBrowserContext()->IsOffTheRecord()) /* should_do_learning */);
3962 }
ekaramadadd882292016-06-08 15:22:563963
3964 return text_input_manager_.get();
3965}
3966
paulmeyer7f6f1d4f2016-11-15 00:00:273967bool WebContentsImpl::OnUpdateDragCursor() {
Lei Zhang6410ec1a2019-01-31 21:38:583968 return browser_plugin_embedder_ &&
3969 browser_plugin_embedder_->OnUpdateDragCursor();
paulmeyer7f6f1d4f2016-11-15 00:00:273970}
3971
kenrb11f213a2017-03-24 18:12:063972bool WebContentsImpl::IsWidgetForMainFrame(
3973 RenderWidgetHostImpl* render_widget_host) {
3974 return render_widget_host == GetMainFrame()->GetRenderWidgetHost();
3975}
3976
[email protected]95640212014-07-26 18:14:303977BrowserAccessibilityManager*
3978 WebContentsImpl::GetRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:393979 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:453980 return rfh ? rfh->browser_accessibility_manager() : nullptr;
[email protected]95640212014-07-26 18:14:303981}
3982
3983BrowserAccessibilityManager*
3984 WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:393985 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:453986 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
[email protected]95640212014-07-26 18:14:303987}
3988
Dave Tapuskab336b922017-07-06 19:24:053989void WebContentsImpl::ExecuteEditCommand(
3990 const std::string& command,
3991 const base::Optional<base::string16>& value) {
Dave Tapuska58a099e2020-06-08 21:48:403992 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:513993 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:053994 return;
3995
Dave Tapuskae782bea2019-07-09 16:21:513996 input_handler->ExecuteEditCommand(command, value);
Dave Tapuskab336b922017-07-06 19:24:053997}
3998
mohsen7ab1ec16ec2015-07-02 18:26:233999void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:404000 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514001 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234002 return;
4003
Dave Tapuskae782bea2019-07-09 16:21:514004 input_handler->MoveRangeSelectionExtent(extent);
mohsen7ab1ec16ec2015-07-02 18:26:234005}
4006
4007void WebContentsImpl::SelectRange(const gfx::Point& base,
4008 const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:404009 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514010 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234011 return;
4012
Dave Tapuskae782bea2019-07-09 16:21:514013 input_handler->SelectRange(base, extent);
mohsen7ab1ec16ec2015-07-02 18:26:234014}
4015
Dave Tapuskab336b922017-07-06 19:24:054016void WebContentsImpl::MoveCaret(const gfx::Point& extent) {
Dave Tapuska58a099e2020-06-08 21:48:404017 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514018 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054019 return;
4020
Dave Tapuskae782bea2019-07-09 16:21:514021 input_handler->MoveCaret(extent);
Dave Tapuskab336b922017-07-06 19:24:054022}
4023
Shimi Zhang37deeb22017-09-28 00:59:014024void WebContentsImpl::AdjustSelectionByCharacterOffset(
4025 int start_adjust,
4026 int end_adjust,
4027 bool show_selection_menu) {
Dave Tapuska58a099e2020-06-08 21:48:404028 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514029 if (!input_handler)
aurimasab0319022015-07-10 21:57:384030 return;
4031
Shimi Zhang37deeb22017-09-28 00:59:014032 using blink::mojom::SelectionMenuBehavior;
Dave Tapuskae782bea2019-07-09 16:21:514033 input_handler->AdjustSelectionByCharacterOffset(
Shimi Zhang37deeb22017-09-28 00:59:014034 start_adjust, end_adjust,
4035 show_selection_menu ? SelectionMenuBehavior::kShow
4036 : SelectionMenuBehavior::kHide);
aurimasab0319022015-07-10 21:57:384037}
4038
[email protected]b172aee2012-04-10 17:05:264039void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
[email protected]222f5822014-02-05 23:40:494040 const gfx::Size old_size = GetPreferredSize();
[email protected]bcd2815602012-01-14 18:17:234041 preferred_size_ = pref_size;
[email protected]222f5822014-02-05 23:40:494042 OnPreferredSizeChanged(old_size);
[email protected]0548c5352011-09-07 00:33:334043}
4044
avic3aa8422015-11-09 20:57:224045void WebContentsImpl::ResizeDueToAutoResize(
4046 RenderWidgetHostImpl* render_widget_host,
Fady Samuel97947112018-05-05 16:24:544047 const gfx::Size& new_size) {
avic3aa8422015-11-09 20:57:224048 if (render_widget_host != GetRenderViewHost()->GetWidget())
4049 return;
4050
[email protected]61e2b3cc2012-03-02 16:13:344051 if (delegate_)
4052 delegate_->ResizeDueToAutoResize(this, new_size);
4053}
4054
[email protected]b172aee2012-04-10 17:05:264055WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
Aaron Colwell9dab1652019-12-09 18:29:494056#if DCHECK_IS_ON()
4057 DCHECK(params.Valid());
4058#endif
4059
Bo Liu300c6052018-06-12 04:46:074060 if (!delegate_) {
4061 // Embedder can delay setting a delegate on new WebContents with
4062 // WebContentsDelegate::ShouldResumeRequestsForCreatedWindow. In the mean
4063 // time, navigations, including the initial one, that goes through OpenURL
4064 // should be delayed until embedder is ready to resume loading.
4065 delayed_open_url_params_ = std::make_unique<OpenURLParams>(params);
Nasko Oskov83a8cf92018-10-19 14:58:564066
4067 // If there was a navigation deferred when creating the window through
4068 // CreateNewWindow, drop it in favor of this navigation.
4069 delayed_load_url_params_.reset();
4070
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284071 return nullptr;
Bo Liu300c6052018-06-12 04:46:074072 }
[email protected]00c37fc2011-08-02 00:22:504073
[email protected]e5d549d2011-12-28 01:29:204074 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
pnoland488944652017-02-22 18:58:544075
4076 RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
4077 params.source_render_process_id, params.source_render_frame_id);
4078
4079 if (source_render_frame_host && params.source_site_instance) {
4080 CHECK_EQ(source_render_frame_host->GetSiteInstance(),
4081 params.source_site_instance.get());
4082 }
4083
4084 if (new_contents && source_render_frame_host && new_contents != this) {
Alexander Timin90c20c32020-08-12 15:28:324085 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4086 observer->DidOpenRequestedURL(
Lukasz Anforowicz48c9f872018-08-01 00:58:414087 new_contents, source_render_frame_host, params.url, params.referrer,
4088 params.disposition, params.transition,
4089 params.started_from_context_menu, params.is_renderer_initiated);
Alexander Timin90c20c32020-08-12 15:28:324090 });
pnoland488944652017-02-22 18:58:544091 }
4092
[email protected]e5d549d2011-12-28 01:29:204093 return new_contents;
[email protected]d5f942ba2008-09-26 19:30:344094}
4095
avi2b177592014-12-10 02:08:024096void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
4097 int history_length) {
alexmos136fd6e62016-08-15 20:58:414098 SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
4099 MSG_ROUTING_NONE, history_offset, history_length));
avi2b177592014-12-10 02:08:024100}
4101
4102void WebContentsImpl::SetHistoryOffsetAndLengthForView(
4103 RenderViewHost* render_view_host,
4104 int history_offset,
4105 int history_length) {
alexmos136fd6e62016-08-15 20:58:414106 render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
avi2b177592014-12-10 02:08:024107 render_view_host->GetRoutingID(), history_offset, history_length));
[email protected]796931a92011-08-10 01:32:144108}
4109
arthursonzogni818c2642019-09-27 12:18:104110void WebContentsImpl::ReloadFocusedFrame() {
[email protected]1f3fc1d2014-04-03 14:50:174111 RenderFrameHost* focused_frame = GetFocusedFrame();
4112 if (!focused_frame)
4113 return;
4114
yilkal921048bd2019-10-09 23:51:044115 focused_frame->Reload();
[email protected]959be4c2014-04-08 15:01:334116}
4117
4118void WebContentsImpl::Undo() {
Dave Tapuska58a099e2020-06-08 21:48:404119 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514120 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334121 return;
4122
Dave Tapuskae782bea2019-07-09 16:21:514123 input_handler->Undo();
[email protected]959be4c2014-04-08 15:01:334124 RecordAction(base::UserMetricsAction("Undo"));
4125}
4126
4127void WebContentsImpl::Redo() {
Dave Tapuska58a099e2020-06-08 21:48:404128 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514129 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334130 return;
Dave Tapuskae782bea2019-07-09 16:21:514131
4132 input_handler->Redo();
[email protected]959be4c2014-04-08 15:01:334133 RecordAction(base::UserMetricsAction("Redo"));
4134}
4135
4136void WebContentsImpl::Cut() {
Dave Tapuska58a099e2020-06-08 21:48:404137 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514138 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334139 return;
4140
Dave Tapuskae782bea2019-07-09 16:21:514141 input_handler->Cut();
[email protected]959be4c2014-04-08 15:01:334142 RecordAction(base::UserMetricsAction("Cut"));
4143}
4144
4145void WebContentsImpl::Copy() {
Dave Tapuska58a099e2020-06-08 21:48:404146 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514147 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334148 return;
4149
Dave Tapuskae782bea2019-07-09 16:21:514150 input_handler->Copy();
[email protected]959be4c2014-04-08 15:01:334151 RecordAction(base::UserMetricsAction("Copy"));
4152}
4153
4154void WebContentsImpl::CopyToFindPboard() {
Avi Drissman7c57be72020-07-29 20:09:464155#if defined(OS_MAC)
Dave Tapuska58a099e2020-06-08 21:48:404156 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514157 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334158 return;
4159
4160 // Windows/Linux don't have the concept of a find pasteboard.
Dave Tapuskae782bea2019-07-09 16:21:514161 input_handler->CopyToFindPboard();
[email protected]959be4c2014-04-08 15:01:334162 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
4163#endif
4164}
4165
4166void WebContentsImpl::Paste() {
Dave Tapuska58a099e2020-06-08 21:48:404167 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514168 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334169 return;
4170
Dave Tapuskae782bea2019-07-09 16:21:514171 input_handler->Paste();
Alexander Timin90c20c32020-08-12 15:28:324172 observers_.ForEachObserver(
4173 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334174 RecordAction(base::UserMetricsAction("Paste"));
4175}
4176
4177void WebContentsImpl::PasteAndMatchStyle() {
Dave Tapuska58a099e2020-06-08 21:48:404178 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514179 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334180 return;
4181
Dave Tapuskae782bea2019-07-09 16:21:514182 input_handler->PasteAndMatchStyle();
Alexander Timin90c20c32020-08-12 15:28:324183 observers_.ForEachObserver(
4184 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334185 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
4186}
4187
4188void WebContentsImpl::Delete() {
Dave Tapuska58a099e2020-06-08 21:48:404189 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514190 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334191 return;
4192
Dave Tapuskae782bea2019-07-09 16:21:514193 input_handler->Delete();
[email protected]959be4c2014-04-08 15:01:334194 RecordAction(base::UserMetricsAction("DeleteSelection"));
4195}
4196
4197void WebContentsImpl::SelectAll() {
Dave Tapuska58a099e2020-06-08 21:48:404198 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514199 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334200 return;
4201
Dave Tapuskae782bea2019-07-09 16:21:514202 input_handler->SelectAll();
[email protected]959be4c2014-04-08 15:01:334203 RecordAction(base::UserMetricsAction("SelectAll"));
4204}
4205
yabinh351e7ec2017-03-10 02:43:244206void WebContentsImpl::CollapseSelection() {
Dave Tapuska58a099e2020-06-08 21:48:404207 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514208 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334209 return;
4210
Dave Tapuskae782bea2019-07-09 16:21:514211 input_handler->CollapseSelection();
[email protected]1f3fc1d2014-04-03 14:50:174212}
4213
4214void WebContentsImpl::Replace(const base::string16& word) {
Dave Tapuska58a099e2020-06-08 21:48:404215 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514216 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174217 return;
4218
Dave Tapuskae782bea2019-07-09 16:21:514219 input_handler->Replace(word);
[email protected]1f3fc1d2014-04-03 14:50:174220}
4221
4222void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
Dave Tapuska58a099e2020-06-08 21:48:404223 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514224 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174225 return;
4226
Dave Tapuskae782bea2019-07-09 16:21:514227 input_handler->ReplaceMisspelling(word);
[email protected]959be4c2014-04-08 15:01:334228}
4229
4230void WebContentsImpl::NotifyContextMenuClosed(
4231 const CustomContextMenuContext& context) {
4232 RenderFrameHost* focused_frame = GetFocusedFrame();
4233 if (!focused_frame)
4234 return;
4235
4236 focused_frame->Send(new FrameMsg_ContextMenuClosed(
4237 focused_frame->GetRoutingID(), context));
4238}
4239
4240void WebContentsImpl::ExecuteCustomContextMenuCommand(
4241 int action, const CustomContextMenuContext& context) {
4242 RenderFrameHost* focused_frame = GetFocusedFrame();
4243 if (!focused_frame)
4244 return;
4245
4246 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
4247 focused_frame->GetRoutingID(), context, action));
[email protected]4fed3702014-04-01 09:08:004248}
4249
[email protected]fc2b46b2014-05-03 16:33:454250gfx::NativeView WebContentsImpl::GetNativeView() {
4251 return view_->GetNativeView();
4252}
4253
4254gfx::NativeView WebContentsImpl::GetContentNativeView() {
4255 return view_->GetContentNativeView();
4256}
4257
4258gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
4259 return view_->GetTopLevelNativeWindow();
4260}
4261
4262gfx::Rect WebContentsImpl::GetViewBounds() {
4263 return view_->GetViewBounds();
4264}
4265
4266gfx::Rect WebContentsImpl::GetContainerBounds() {
Jeremy Roman352239c2020-05-21 16:31:324267 return view_->GetContainerBounds();
[email protected]fc2b46b2014-05-03 16:33:454268}
4269
4270DropData* WebContentsImpl::GetDropData() {
4271 return view_->GetDropData();
4272}
4273
4274void WebContentsImpl::Focus() {
miu9e14e492014-10-25 02:39:044275 view_->Focus();
[email protected]fc2b46b2014-05-03 16:33:454276}
4277
4278void WebContentsImpl::SetInitialFocus() {
miu9e14e492014-10-25 02:39:044279 view_->SetInitialFocus();
[email protected]fc2b46b2014-05-03 16:33:454280}
4281
4282void WebContentsImpl::StoreFocus() {
miu9e14e492014-10-25 02:39:044283 view_->StoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454284}
4285
4286void WebContentsImpl::RestoreFocus() {
miu9e14e492014-10-25 02:39:044287 view_->RestoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454288}
4289
[email protected]b172aee2012-04-10 17:05:264290void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
Maxim Podgorodskiya926c4ff2017-11-20 02:06:394291 view_->FocusThroughTabTraversal(reverse);
[email protected]96d185d2009-04-24 03:28:544292}
4293
[email protected]b172aee2012-04-10 17:05:264294bool WebContentsImpl::IsSavable() {
[email protected]a53209b2012-01-20 16:48:164295 // WebKit creates Document object when MIME type is application/xhtml+xml,
4296 // so we also support this MIME type.
Yuzu Saijoc23e9b72020-06-25 07:21:274297 std::string mime_type = GetContentsMimeType();
4298 return mime_type == "text/html" || mime_type == "text/xml" ||
4299 mime_type == "application/xhtml+xml" || mime_type == "text/plain" ||
4300 mime_type == "text/css" ||
4301 blink::IsSupportedJavascriptMimeType(mime_type);
[email protected]a53209b2012-01-20 16:48:164302}
4303
[email protected]b172aee2012-04-10 17:05:264304void WebContentsImpl::OnSavePage() {
[email protected]c7dd2f62011-07-18 15:57:594305 // If we can not save the page, try to download it.
[email protected]a53209b2012-01-20 16:48:164306 if (!IsSavable()) {
Min Qinda0ed2062018-02-23 22:00:534307 download::RecordSavePackageEvent(
4308 download::SAVE_PACKAGE_DOWNLOAD_ON_NON_HTML);
nasko89ad7742015-03-05 22:14:194309 SaveFrame(GetLastCommittedURL(), Referrer());
[email protected]27678b2a2012-02-04 22:09:144310 return;
[email protected]c7dd2f62011-07-18 15:57:594311 }
4312
4313 Stop();
4314
4315 // Create the save package and possibly prompt the user for the name to save
4316 // the page as. The user prompt is an asynchronous operation that runs on
4317 // another thread.
4318 save_package_ = new SavePackage(this);
4319 save_package_->GetSaveInfo();
4320}
4321
4322// Used in automated testing to bypass prompting the user for file names.
4323// Instead, the names and paths are hard coded rather than running them through
4324// file name sanitation and extension / mime checking.
[email protected]2dec8ec2013-02-07 19:20:344325bool WebContentsImpl::SavePage(const base::FilePath& main_file,
4326 const base::FilePath& dir_path,
[email protected]8ff00d72012-10-23 19:12:214327 SavePageType save_type) {
[email protected]c7dd2f62011-07-18 15:57:594328 // Stop the page from navigating.
4329 Stop();
4330
4331 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]8ff00d72012-10-23 19:12:214332 return save_package_->Init(SavePackageDownloadCreatedCallback());
[email protected]c7dd2f62011-07-18 15:57:594333}
4334
[email protected]3c71576ce2013-07-23 02:00:014335void WebContentsImpl::SaveFrame(const GURL& url,
4336 const Referrer& referrer) {
Xing Liu10329bf2018-03-20 19:22:144337 SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
kundaji6c7f9692015-03-09 18:00:374338}
4339
Xing Liu10329bf2018-03-20 19:22:144340void WebContentsImpl::SaveFrameWithHeaders(
4341 const GURL& url,
4342 const Referrer& referrer,
4343 const std::string& headers,
4344 const base::string16& suggested_filename) {
Lei Zhang13a42e42019-02-19 23:28:114345 // Check and see if the guest can handle this.
4346 if (delegate_) {
4347 WebContents* guest_web_contents = nullptr;
4348 if (browser_plugin_embedder_) {
4349 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
4350 if (guest)
4351 guest_web_contents = guest->GetWebContents();
4352 } else if (browser_plugin_guest_) {
4353 guest_web_contents = this;
4354 }
4355
4356 if (guest_web_contents && delegate_->GuestSaveFrame(guest_web_contents))
4357 return;
4358 }
4359
nasko89ad7742015-03-05 22:14:194360 if (!GetLastCommittedURL().is_valid())
[email protected]3c71576ce2013-07-23 02:00:014361 return;
sammc92af61552014-11-19 23:27:404362 if (delegate_ && delegate_->SaveFrame(url, referrer))
4363 return;
4364
nasko89ad7742015-03-05 22:14:194365 // TODO(nasko): This check for main frame is incorrect and should be fixed
brettw760f7442016-05-23 21:19:224366 // by explicitly passing in which frame this method should target. This would
4367 // indicate whether it's the main frame, and also tell us the frame pointer
4368 // to use for routing.
nasko89ad7742015-03-05 22:14:194369 bool is_main_frame = (url == GetLastCommittedURL());
brettw760f7442016-05-23 21:19:224370 RenderFrameHost* frame_host = GetMainFrame();
[email protected]3c71576ce2013-07-23 02:00:014371
avib7348942015-12-25 20:57:104372 int64_t post_id = -1;
[email protected]3c71576ce2013-07-23 02:00:014373 if (is_main_frame) {
Lucas Furukawa Gadani5553a152019-01-08 18:55:574374 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]3c71576ce2013-07-23 02:00:014375 if (entry)
4376 post_id = entry->GetPostID();
4377 }
Ramin Halavati24e21012017-07-10 12:56:064378 net::NetworkTrafficAnnotationTag traffic_annotation =
4379 net::DefineNetworkTrafficAnnotation("download_web_contents_frame", R"(
4380 semantics {
4381 sender: "Save Page Action"
4382 description:
4383 "Saves the given frame's URL to the local file system."
4384 trigger:
4385 "The user has triggered a save operation on the frame through a "
4386 "context menu or other mechanism."
4387 data: "None."
4388 destination: WEBSITE
4389 }
4390 policy {
Ramin Halavati3b979782017-07-21 11:40:264391 cookies_allowed: YES
Ramin Halavati24e21012017-07-10 12:56:064392 cookies_store: "user"
4393 setting:
4394 "This feature cannot be disabled by settings, but it's is only "
4395 "triggered by user request."
4396 policy_exception_justification: "Not implemented."
4397 })");
Min Qina904f3302018-02-13 23:33:344398 auto params = std::make_unique<download::DownloadUrlParameters>(
brettw760f7442016-05-23 21:19:224399 url, frame_host->GetProcess()->GetID(),
4400 frame_host->GetRenderViewHost()->GetRoutingID(),
Matt Menke0dcaebc32020-03-06 17:00:104401 frame_host->GetRoutingID(), traffic_annotation);
Min Qina904f3302018-02-13 23:33:344402 params->set_referrer(referrer.url);
4403 params->set_referrer_policy(
4404 Referrer::ReferrerPolicyForUrlRequest(referrer.policy));
[email protected]3c71576ce2013-07-23 02:00:014405 params->set_post_id(post_id);
[email protected]3c71576ce2013-07-23 02:00:014406 if (post_id >= 0)
4407 params->set_method("POST");
4408 params->set_prompt(true);
kundaji6c7f9692015-03-09 18:00:374409
4410 if (headers.empty()) {
4411 params->set_prefer_cache(true);
4412 } else {
Min Qina904f3302018-02-13 23:33:344413 for (download::DownloadUrlParameters::RequestHeadersNameValuePair
4414 key_value : ParseDownloadHeaders(headers)) {
Megan Jablonski2f6a4c52017-07-10 23:01:254415 params->add_request_header(key_value.first, key_value.second);
kundaji6c7f9692015-03-09 18:00:374416 }
4417 }
Xing Liu10329bf2018-03-20 19:22:144418 params->set_suggested_name(suggested_filename);
Min Qin0ca8e1ee2018-01-31 00:49:354419 params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
thestig859c78892017-05-15 21:17:064420 BrowserContext::GetDownloadManager(GetBrowserContext())
Ramin Halavati03efa732017-06-12 09:28:204421 ->DownloadUrl(std::move(params));
[email protected]3c71576ce2013-07-23 02:00:014422}
4423
[email protected]b172aee2012-04-10 17:05:264424void WebContentsImpl::GenerateMHTML(
dewittj6dc5747a2016-05-17 01:48:474425 const MHTMLGenerationParams& params,
Avi Drissman149b7832018-03-23 14:31:494426 base::OnceCallback<void(int64_t)> callback) {
Angel Alvarez902496682019-08-27 22:58:424427 base::OnceCallback<void(const MHTMLGenerationResult&)> wrapper_callback =
4428 base::BindOnce(
4429 [](base::OnceCallback<void(int64_t)> size_callback,
4430 const MHTMLGenerationResult& result) {
4431 std::move(size_callback).Run(result.file_size);
4432 },
4433 std::move(callback));
4434 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4435 std::move(wrapper_callback));
4436}
4437
4438void WebContentsImpl::GenerateMHTMLWithResult(
4439 const MHTMLGenerationParams& params,
4440 MHTMLGenerationResult::GenerateMHTMLCallback callback) {
Avi Drissman149b7832018-03-23 14:31:494441 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4442 std::move(callback));
[email protected]aa4f3972012-03-01 18:12:124443}
4444
Tsuyoshi Horob0d8d902020-03-12 00:09:394445void WebContentsImpl::GenerateWebBundle(
4446 const base::FilePath& file_path,
4447 base::OnceCallback<void(uint64_t /* file_size */,
4448 data_decoder::mojom::WebBundlerError)> callback) {
4449 SaveAsWebBundleJob::Start(this, file_path, std::move(callback));
4450}
4451
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414452const std::string& WebContentsImpl::GetContentsMimeType() {
Yuzu Saijoc23e9b72020-06-25 07:21:274453 return GetRenderViewHost()->contents_mime_type();
[email protected]0bfbf882011-12-22 18:19:274454}
4455
Leon Hanc819dc62019-01-28 04:30:194456blink::mojom::RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
[email protected]0bfbf882011-12-22 18:19:274457 return &renderer_preferences_;
4458}
4459
[email protected]e35ccd52012-05-23 16:22:474460void WebContentsImpl::Close() {
4461 Close(GetRenderViewHost());
4462}
4463
Ella Ge80a52dce2017-11-15 18:01:524464void WebContentsImpl::DragSourceEndedAt(float client_x,
4465 float client_y,
4466 float screen_x,
4467 float screen_y,
Paul Meyer0c58c3712016-11-17 22:59:514468 blink::WebDragOperation operation,
4469 RenderWidgetHost* source_rwh) {
Lei Zhang6410ec1a2019-01-31 21:38:584470 if (browser_plugin_embedder_) {
W. James MacLean9437b5bf2019-12-06 17:33:444471 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, screen_x,
4472 screen_y, operation);
Lei Zhang6410ec1a2019-01-31 21:38:584473 }
Paul Meyer0c58c3712016-11-17 22:59:514474 if (source_rwh) {
Ella Ge80a52dce2017-11-15 18:01:524475 source_rwh->DragSourceEndedAt(gfx::PointF(client_x, client_y),
4476 gfx::PointF(screen_x, screen_y), operation);
Paul Meyer0c58c3712016-11-17 22:59:514477 }
[email protected]cf200a562013-05-03 16:24:294478}
4479
jam73f892642016-09-11 06:04:064480void WebContentsImpl::LoadStateChanged(
Charles Harrison911fa062018-03-06 21:01:464481 const std::string& host,
jam73f892642016-09-11 06:04:064482 const net::LoadStateWithParam& load_state,
4483 uint64_t upload_position,
4484 uint64_t upload_size) {
Charles Harrison911fa062018-03-06 21:01:464485 base::string16 host16 = url_formatter::IDNToUnicode(host);
Elly Fong-Jonescad9c3d12018-01-31 17:26:104486 // Drop no-op updates.
4487 if (load_state_.state == load_state.state &&
4488 load_state_.param == load_state.param &&
4489 upload_position_ == upload_position && upload_size_ == upload_size &&
Charles Harrison911fa062018-03-06 21:01:464490 load_state_host_ == host16) {
Elly Fong-Jonescad9c3d12018-01-31 17:26:104491 return;
4492 }
jam73f892642016-09-11 06:04:064493 load_state_ = load_state;
4494 upload_position_ = upload_position;
4495 upload_size_ = upload_size;
Charles Harrison911fa062018-03-06 21:01:464496 load_state_host_ = host16;
jam73f892642016-09-11 06:04:064497 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4498 SetNotWaitingForResponse();
jam73f892642016-09-11 06:04:064499}
4500
Collin Baker989e0882019-11-01 01:27:174501void WebContentsImpl::SetVisibilityAndNotifyObservers(Visibility visibility) {
Francois Doraye6161152018-03-27 22:05:374502 const Visibility previous_visibility = visibility_;
4503 visibility_ = visibility;
4504
Francois Dorayfe4a1772018-02-17 04:17:094505 // Notify observers if the visibility changed or if WasShown() is being called
4506 // for the first time.
Francois Dorayfe4a1772018-02-17 04:17:094507 if (visibility != previous_visibility ||
4508 (visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
Alexander Timin90c20c32020-08-12 15:28:324509 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4510 observer->OnVisibilityChanged(visibility);
4511 });
Francois Dorayfe4a1772018-02-17 04:17:094512 }
4513}
4514
Michael Thiessen896405db2017-07-20 17:52:324515void WebContentsImpl::NotifyWebContentsFocused(
4516 RenderWidgetHost* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:324517 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4518 observer->OnWebContentsFocused(render_widget_host);
4519 });
calamity7fe55ce2015-04-10 03:59:374520}
4521
Michael Thiessen896405db2017-07-20 17:52:324522void WebContentsImpl::NotifyWebContentsLostFocus(
4523 RenderWidgetHost* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:324524 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4525 observer->OnWebContentsLostFocus(render_widget_host);
4526 });
zijiehe3bee08e22017-05-17 04:14:464527}
4528
Paul Meyer0c58c3712016-11-17 22:59:514529void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
4530 if (source_rwh)
4531 source_rwh->DragSourceSystemDragEnded();
Lei Zhang6410ec1a2019-01-31 21:38:584532 if (browser_plugin_embedder_)
[email protected]cf200a562013-05-03 16:24:294533 browser_plugin_embedder_->SystemDragEnded();
[email protected]7813bd72011-02-05 02:19:344534}
4535
[email protected]b172aee2012-04-10 17:05:264536void WebContentsImpl::SetClosedByUserGesture(bool value) {
[email protected]0bfbf882011-12-22 18:19:274537 closed_by_user_gesture_ = value;
4538}
4539
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414540bool WebContentsImpl::GetClosedByUserGesture() {
[email protected]0bfbf882011-12-22 18:19:274541 return closed_by_user_gesture_;
4542}
4543
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414544int WebContentsImpl::GetMinimumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274545 return minimum_zoom_percent_;
4546}
4547
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414548int WebContentsImpl::GetMaximumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274549 return maximum_zoom_percent_;
4550}
4551
Dave Tapuska8f7c3872020-02-07 01:16:384552void WebContentsImpl::SetPageScale(float scale_factor) {
4553 GetMainFrame()->GetAssociatedLocalMainFrame()->SetScaleFactor(scale_factor);
ccameronb7c1d6c2015-03-09 17:08:244554}
4555
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414556gfx::Size WebContentsImpl::GetPreferredSize() {
Francois Doray24fc62c2017-12-11 17:27:334557 return IsBeingCaptured() ? preferred_size_for_capture_ : preferred_size_;
[email protected]bcd2815602012-01-14 18:17:234558}
4559
James Hollyerd5c9de462020-03-10 19:02:454560bool WebContentsImpl::GotResponseToLockMouseRequest(
4561 blink::mojom::PointerLockResult result) {
lfgf0cd46e2017-01-04 00:05:234562 if (mouse_lock_widget_) {
4563 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this) {
4564 return mouse_lock_widget_->delegate()
4565 ->GetAsWebContents()
James Hollyerd5c9de462020-03-10 19:02:454566 ->GotResponseToLockMouseRequest(result);
lfgf0cd46e2017-01-04 00:05:234567 }
lfgad8244352016-07-13 16:55:514568
James Hollyerd5c9de462020-03-10 19:02:454569 if (mouse_lock_widget_->GotResponseToLockMouseRequest(result))
lfgf0cd46e2017-01-04 00:05:234570 return true;
4571 }
4572
4573 for (WebContentsImpl* current = this; current;
4574 current = current->GetOuterWebContents()) {
4575 current->mouse_lock_widget_ = nullptr;
4576 }
4577
lfgbee1e0a2016-06-08 21:24:214578 return false;
[email protected]0bfbf882011-12-22 18:19:274579}
4580
James Hollyerd5c9de462020-03-10 19:02:454581void WebContentsImpl::GotLockMousePermissionResponse(bool allowed) {
4582 GotResponseToLockMouseRequest(
4583 allowed ? blink::mojom::PointerLockResult::kSuccess
4584 : blink::mojom::PointerLockResult::kPermissionDenied);
4585}
4586
Joe Downing13dd76b2018-04-09 18:32:154587bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
4588 if (!keyboard_lock_widget_)
4589 return false;
4590
4591 if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
4592 NOTREACHED();
4593 return false;
4594 }
4595
4596 // KeyboardLock is only supported when called by the top-level browsing
4597 // context and is not supported in embedded content scenarios.
4598 if (GetOuterWebContents())
4599 return false;
4600
4601 keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
4602 return true;
4603}
4604
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414605bool WebContentsImpl::HasOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284606 return GetOpener() != nullptr;
[email protected]a0358d72012-03-09 14:06:504607}
4608
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414609RenderFrameHostImpl* WebContentsImpl::GetOpener() {
alexmose201c7cd2015-06-10 17:14:214610 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
lukasza6f8ac622017-06-06 03:10:204611 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen55ff3502014-12-18 20:52:574612}
4613
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414614bool WebContentsImpl::HasOriginalOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284615 return GetOriginalOpener() != nullptr;
jochen6004a362017-02-04 00:11:404616}
4617
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414618RenderFrameHostImpl* WebContentsImpl::GetOriginalOpener() {
jochen6004a362017-02-04 00:11:404619 FrameTreeNode* opener_ftn = frame_tree_.root()->original_opener();
lukasza6f8ac622017-06-06 03:10:204620 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen6004a362017-02-04 00:11:404621}
4622
[email protected]cb805452013-05-22 15:16:214623void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Joel Hockey85b379d2017-12-11 10:42:134624 color_chooser_->DidChooseColorInColorChooser(color);
[email protected]da8543762012-03-20 08:52:204625}
4626
[email protected]cb805452013-05-22 15:16:214627void WebContentsImpl::DidEndColorChooser() {
Joel Hockey85b379d2017-12-11 10:42:134628 color_chooser_.reset();
[email protected]da8543762012-03-20 08:52:204629}
4630
halton.huoca2eabd2015-07-06 08:17:404631int WebContentsImpl::DownloadImage(
4632 const GURL& url,
4633 bool is_favicon,
Fredrik Söderquistb2b39eb92019-11-18 16:16:504634 uint32_t preferred_size,
halton.huoca2eabd2015-07-06 08:17:404635 uint32_t max_bitmap_size,
4636 bool bypass_cache,
Avi Drissmana5a52dd2018-03-27 03:39:024637 WebContents::ImageDownloadCallback callback) {
Danyao Wanga78f3dd22020-03-05 05:31:274638 return DownloadImageInFrame(GlobalFrameRoutingId(), url, is_favicon,
4639 preferred_size, max_bitmap_size, bypass_cache,
4640 std::move(callback));
4641}
4642
4643int WebContentsImpl::DownloadImageInFrame(
4644 const GlobalFrameRoutingId& initiator_frame_routing_id,
4645 const GURL& url,
4646 bool is_favicon,
4647 uint32_t preferred_size,
4648 uint32_t max_bitmap_size,
4649 bool bypass_cache,
4650 WebContents::ImageDownloadCallback callback) {
amistry9f01b772015-07-29 01:54:554651 DCHECK_CURRENTLY_ON(BrowserThread::UI);
halton.huoca2eabd2015-07-06 08:17:404652 static int next_image_download_id = 0;
Danyao Wanga78f3dd22020-03-05 05:31:274653
4654 RenderFrameHostImpl* initiator_frame =
4655 initiator_frame_routing_id.child_id
4656 ? RenderFrameHostImpl::FromID(initiator_frame_routing_id)
4657 : GetMainFrame();
Julie Jeongeun Kimb1473572019-08-15 05:59:134658 const mojo::Remote<blink::mojom::ImageDownloader>& mojo_image_downloader =
Danyao Wanga78f3dd22020-03-05 05:31:274659 initiator_frame->GetMojoImageDownloader();
amistry9f01b772015-07-29 01:54:554660 const int download_id = ++next_image_download_id;
4661 if (!mojo_image_downloader) {
4662 // If the renderer process is dead (i.e. crash, or memory pressure on
4663 // Android), the downloader service will be invalid. Pre-Mojo, this would
Avi Drissmana5a52dd2018-03-27 03:39:024664 // hang the callback indefinitely since the IPC would be dropped. Now,
amistry9f01b772015-07-29 01:54:554665 // respond with a 400 HTTP error code to indicate that something went wrong.
Gabriel Charettee7cdc5cd2020-05-27 23:35:054666 GetUIThreadTaskRunner({})->PostTask(
4667 FROM_HERE,
tzike2aca992017-09-05 08:50:544668 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:024669 weak_factory_.GetWeakPtr(), std::move(callback),
4670 download_id, url, 400, std::vector<SkBitmap>(),
4671 std::vector<gfx::Size>()));
amistry9f01b772015-07-29 01:54:554672 return download_id;
4673 }
4674
halton.huoca2eabd2015-07-06 08:17:404675 mojo_image_downloader->DownloadImage(
Fredrik Söderquistb2b39eb92019-11-18 16:16:504676 url, is_favicon, preferred_size, max_bitmap_size, bypass_cache,
tzike2aca992017-09-05 08:50:544677 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:024678 weak_factory_.GetWeakPtr(), std::move(callback),
4679 download_id, url));
amistry9f01b772015-07-29 01:54:554680 return download_id;
[email protected]795c28972012-12-06 06:13:394681}
4682
[email protected]36ec24f2014-01-09 00:32:084683void WebContentsImpl::Find(int request_id,
4684 const base::string16& search_text,
Rakina Zata Amni3f77dff2018-09-08 16:19:434685 blink::mojom::FindOptionsPtr options) {
thestig6057a6b22015-11-12 23:01:334686 // Cowardly refuse to search for no text.
4687 if (search_text.empty()) {
4688 NOTREACHED();
4689 return;
4690 }
4691
Rakina Zata Amni3f77dff2018-09-08 16:19:434692 GetOrCreateFindRequestManager()->Find(request_id, search_text,
4693 std::move(options));
[email protected]36ec24f2014-01-09 00:32:084694}
4695
4696void WebContentsImpl::StopFinding(StopFindAction action) {
paulmeyerfeafc2d2017-04-25 21:46:404697 if (FindRequestManager* manager = GetFindRequestManager())
4698 manager->StopFinding(action);
[email protected]36ec24f2014-01-09 00:32:084699}
4700
Tommy Steimel18360512017-11-01 00:38:194701bool WebContentsImpl::WasEverAudible() {
4702 return was_ever_audible_;
4703}
4704
Avi Drissmana5a52dd2018-03-27 03:39:024705void WebContentsImpl::GetManifest(GetManifestCallback callback) {
Yuzu Saijofce18322020-05-14 05:02:094706 // TODO(yuzus, 1061899): Move this function to RenderFrameHostImpl.
4707 ManifestManagerHost* manifest_manager_host =
4708 ManifestManagerHost::GetOrCreateForCurrentDocument(GetMainFrame());
4709 manifest_manager_host->GetManifest(std::move(callback));
mlamouriefdca9d2014-09-16 16:55:404710}
4711
bokanece34a82016-01-28 19:49:464712void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
mlamouri7a78d6fd2015-01-17 13:23:534713 // Clean up related state and initiate the fullscreen exit.
James Hollyerd5c9de462020-03-10 19:02:454714 GetRenderViewHost()->GetWidget()->RejectMouseLockOrUnlockIfNecessary(
4715 blink::mojom::PointerLockResult::kUserRejected);
bokanece34a82016-01-28 19:49:464716 ExitFullscreenMode(will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:534717}
4718
Mike Wassermanb6bc0152020-08-25 22:46:204719base::ScopedClosureRunner WebContentsImpl::ForSecurityDropFullscreen(
4720 int64_t display_id) {
Avi Drissman33972942020-06-19 14:16:014721 // Kick WebContentses that are "related" to this WebContents out of
4722 // fullscreen. This needs to be done with two passes, because it is simple to
4723 // walk _up_ the chain of openers and outer contents, but it not simple to
4724 // walk _down_ the chain.
4725
4726 // First, determine if any WebContents that is in fullscreen has this
4727 // WebContents as an upstream contents. Drop that WebContents out of
4728 // fullscreen if it does. This is theoretically quadratic-ish (fullscreen
4729 // contentses x each one's opener length) but neither of those is expected to
4730 // ever be a large number.
4731
Mike Wassermanb6bc0152020-08-25 22:46:204732 auto* screen = display::Screen::GetScreen();
4733
Avi Drissman33972942020-06-19 14:16:014734 auto fullscreen_set_copy = *FullscreenContentsSet(GetBrowserContext());
4735 for (auto* fullscreen_contents : fullscreen_set_copy) {
Avi Drissman97aef042020-06-30 21:04:484736 // Checking IsFullscreen() for tabs in the fullscreen set may seem
4737 // redundant, but teeeeechnically fullscreen is run by the delegate, and
4738 // it's possible that the delegate's notion of fullscreen may have changed
4739 // outside of WebContents's notice.
Mike Wassermanb6bc0152020-08-25 22:46:204740 if (fullscreen_contents->IsFullscreen() &&
4741 (display_id == display::kInvalidDisplayId || !screen ||
4742 display_id ==
4743 screen->GetDisplayNearestView(fullscreen_contents->GetNativeView())
4744 .id())) {
Avi Drissman33972942020-06-19 14:16:014745 auto opener_contentses = GetAllOpeningWebContents(fullscreen_contents);
4746 if (opener_contentses.count(this))
4747 fullscreen_contents->ExitFullscreen(true);
4748 }
4749 }
4750
4751 // Second, walk upstream from this WebContents, and drop the fullscreen of
4752 // all WebContentses that are in fullscreen. Block all the WebContentses in
4753 // the chain from entering fullscreen while the returned closure runner is
4754 // alive. It's OK that this set doesn't contain downstream WebContentses, as
4755 // any request to enter fullscreen will have the upstream of the WebContents
4756 // checked. (See CanEnterFullscreenMode().)
Avi Drissmanced52b62019-08-14 21:25:464757
Avi Drissman1a55a9d62020-03-10 18:56:454758 std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses;
4759
Avi Drissman33972942020-06-19 14:16:014760 for (auto* opener : GetAllOpeningWebContents(this)) {
Avi Drissman1a55a9d62020-03-10 18:56:454761 // Drop fullscreen if the WebContents is in it, and...
Mike Wassermanb6bc0152020-08-25 22:46:204762 if (opener->IsFullscreen() &&
4763 (display_id == display::kInvalidDisplayId || !screen ||
4764 display_id ==
4765 screen->GetDisplayNearestView(opener->GetNativeView()).id()))
Avi Drissman33972942020-06-19 14:16:014766 opener->ExitFullscreen(true);
Avi Drissmanced52b62019-08-14 21:25:464767
Avi Drissman1a55a9d62020-03-10 18:56:454768 // ...block the WebContents from entering fullscreen until further notice.
Avi Drissman33972942020-06-19 14:16:014769 ++opener->fullscreen_blocker_count_;
4770 blocked_contentses.push_back(opener->weak_factory_.GetWeakPtr());
Avi Drissmanced52b62019-08-14 21:25:464771 }
Avi Drissman1a55a9d62020-03-10 18:56:454772
4773 return base::ScopedClosureRunner(base::BindOnce(
4774 [](std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses) {
4775 for (base::WeakPtr<WebContentsImpl>& web_contents :
4776 blocked_contentses) {
4777 if (web_contents) {
4778 DCHECK_GT(web_contents->fullscreen_blocker_count_, 0);
4779 --web_contents->fullscreen_blocker_count_;
4780 }
4781 }
4782 },
4783 std::move(blocked_contentses)));
Avi Drissmanced52b62019-08-14 21:25:464784}
4785
mariakhomenko44bdc4732015-04-29 01:55:384786void WebContentsImpl::ResumeLoadingCreatedWebContents() {
Nasko Oskov83a8cf92018-10-19 14:58:564787 if (delayed_load_url_params_.get()) {
4788 DCHECK(!delayed_open_url_params_);
4789 controller_.LoadURLWithParams(*delayed_load_url_params_.get());
4790 delayed_load_url_params_.reset(nullptr);
4791 return;
4792 }
4793
mariakhomenkoa4971c12015-07-21 19:04:374794 if (delayed_open_url_params_.get()) {
4795 OpenURL(*delayed_open_url_params_.get());
4796 delayed_open_url_params_.reset(nullptr);
4797 return;
4798 }
4799
mariakhomenko44bdc4732015-04-29 01:55:384800 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
4801 // TODO(brettw): It seems bogus to reach into here and initialize the host.
dfalcantarae6b7b46752015-07-10 18:14:164802 if (is_resume_pending_) {
4803 is_resume_pending_ = false;
avi0f1bbc9712015-11-17 02:58:134804 GetRenderViewHost()->GetWidget()->Init();
dfalcantarae6b7b46752015-07-10 18:14:164805 GetMainFrame()->Init();
4806 }
mariakhomenko44bdc4732015-04-29 01:55:384807}
4808
[email protected]b172aee2012-04-10 17:05:264809bool WebContentsImpl::FocusLocationBarByDefault() {
Xiyuan Xia2a66b112018-12-06 15:52:164810 if (should_focus_location_bar_by_default_)
[email protected]0c9406632013-02-08 01:13:334811 return true;
Xiyuan Xia2a66b112018-12-06 15:52:164812
[email protected]0c9406632013-02-08 01:13:334813 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
[email protected]0bfbf882011-12-22 18:19:274814}
4815
Tommy C. Li8bb5bf42019-01-18 18:45:514816void WebContentsImpl::SetFocusToLocationBar() {
[email protected]0bfbf882011-12-22 18:19:274817 if (delegate_)
Tommy C. Li8bb5bf42019-01-18 18:45:514818 delegate_->SetFocusToLocationBar();
[email protected]c40d6232011-03-25 00:16:214819}
4820
clamy0e119882015-07-31 16:12:334821void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484822 TRACE_EVENT1("navigation", "WebContentsImpl::DidStartNavigation",
4823 "navigation_handle", navigation_handle);
Alan Cutterab48fc02020-02-24 12:26:424824 if (navigation_handle->IsInMainFrame())
4825 favicon_urls_.clear();
Mounir Lamouri7b4a1f232019-12-23 16:32:104826
Alexander Timin90c20c32020-08-12 15:28:324827 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4828 observer->DidStartNavigation(navigation_handle);
4829 });
Xiyuan Xia2a66b112018-12-06 15:52:164830 if (navigation_handle->IsInMainFrame()) {
4831 // When the browser is started with about:blank as the startup URL, focus
4832 // the location bar (which will also select its contents) so people can
4833 // simply begin typing to navigate elsewhere.
4834 //
4835 // We need to be careful not to trigger this for anything other than the
4836 // startup navigation. In particular, if we allow an attacker to open a
4837 // popup to about:blank, then navigate, focusing the Omnibox will cause the
4838 // end of the new URL to be scrolled into view instead of the start,
4839 // allowing the attacker to spoof other URLs. The conditions checked here
4840 // are all aimed at ensuring no such attacker-controlled navigation can
4841 // trigger this.
4842 should_focus_location_bar_by_default_ =
4843 controller_.IsInitialNavigation() &&
4844 !navigation_handle->IsRendererInitiated() &&
4845 navigation_handle->GetURL() == url::kAboutBlankURL;
4846 }
clamy0e119882015-07-31 16:12:334847}
4848
4849void WebContentsImpl::DidRedirectNavigation(
4850 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484851 TRACE_EVENT1("navigation", "WebContentsImpl::DidRedirectNavigation",
4852 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:324853 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4854 observer->DidRedirectNavigation(navigation_handle);
4855 });
jam5f358e52017-02-13 16:37:034856 // Notify accessibility if this is a reload. This has to called on the
4857 // BrowserAccessibilityManager associated with the old RFHI.
4858 if (navigation_handle->GetReloadType() != ReloadType::NONE) {
Mohamed Abdelhalim95794962019-09-20 11:16:494859 NavigationRequest* request = NavigationRequest::From(navigation_handle);
jam5f358e52017-02-13 16:37:034860 BrowserAccessibilityManager* manager =
Mohamed Abdelhalim95794962019-09-20 11:16:494861 request->frame_tree_node()
jam5f358e52017-02-13 16:37:034862 ->current_frame_host()
4863 ->browser_accessibility_manager();
4864 if (manager)
4865 manager->UserIsReloading();
4866 }
clamy0e119882015-07-31 16:12:334867}
4868
clamyefca29e2015-09-17 00:22:114869void WebContentsImpl::ReadyToCommitNavigation(
4870 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484871 TRACE_EVENT1("navigation", "WebContentsImpl::ReadyToCommitNavigation",
4872 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:324873 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4874 observer->ReadyToCommitNavigation(navigation_handle);
4875 });
Kenneth Russell954ed9ce2018-04-12 23:07:014876 // If any domains are blocked from accessing 3D APIs because they may
4877 // have caused the GPU to reset recently, unblock them here if the user
4878 // initiated this navigation. This implies that the user was involved in
4879 // the decision to navigate, so there's no concern about
4880 // denial-of-service issues. Want to do this as early as
4881 // possible to avoid race conditions with pages attempting to access
4882 // WebGL early on.
4883 //
4884 // TODO(crbug.com/617904): currently navigations initiated by the browser
4885 // (reload button, reload menu option, pressing return in the Omnibox)
4886 // return false from HasUserGesture(). If or when that is addressed,
4887 // remove the check for IsRendererInitiated() below.
4888 //
4889 // TODO(crbug.com/832180): HasUserGesture comes from the renderer
4890 // process and isn't validated. Until it is, don't trust it.
4891 if (!navigation_handle->IsRendererInitiated()) {
4892 GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
4893 navigation_handle->GetURL());
4894 }
4895
John Abd-El-Malekfde08e6da2017-12-05 04:06:244896 if (navigation_handle->IsSameDocument())
4897 return;
4898
Livvie Lin139bf442018-08-10 00:18:544899 // SSLInfo is not needed on subframe navigations since the main-frame
4900 // certificate is the only one that can be inspected (using the info
4901 // bubble) without refreshing the page with DevTools open.
Carlos ILaed1e7b2019-03-12 19:27:214902 // We don't call DidStartResourceResponse on net errors, since that results on
4903 // existing cert exceptions being revoked, which leads to weird behavior with
4904 // committed interstitials or while offline. We only need the error check for
4905 // the main frame case because unlike this method, SubresourceResponseStarted
4906 // does not get called on network errors.
4907 if (navigation_handle->IsInMainFrame() &&
4908 navigation_handle->GetNetErrorCode() == net::OK) {
Livvie Lin139bf442018-08-10 00:18:544909 controller_.ssl_manager()->DidStartResourceResponse(
Lukasz Anforowiczd334bba2020-02-10 23:32:554910 navigation_handle->GetURL(),
Camille Lamy62b826012019-02-26 09:15:474911 navigation_handle->GetSSLInfo().has_value()
4912 ? net::IsCertStatusError(
4913 navigation_handle->GetSSLInfo()->cert_status)
4914 : false);
4915 }
John Abd-El-Malekfde08e6da2017-12-05 04:06:244916
4917 SetNotWaitingForResponse();
clamyefca29e2015-09-17 00:22:114918}
4919
clamy0e119882015-07-31 16:12:334920void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:484921 TRACE_EVENT1("navigation", "WebContentsImpl::DidFinishNavigation",
4922 "navigation_handle", navigation_handle);
Steven Holte38041342018-06-22 22:00:574923
Alexander Timin90c20c32020-08-12 15:28:324924 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4925 observer->DidFinishNavigation(navigation_handle);
4926 });
Becca Hughesd11d6502018-07-31 17:01:284927 if (display_cutout_host_impl_)
4928 display_cutout_host_impl_->DidFinishNavigation(navigation_handle);
4929
jam5f358e52017-02-13 16:37:034930 if (navigation_handle->HasCommitted()) {
Ian Prestcdd843d2020-01-28 18:59:584931 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
4932 // https://crbug.com/981271.
4933 BrowserAccessibilityManager* manager =
4934 static_cast<RenderFrameHostImpl*>(
4935 navigation_handle->GetRenderFrameHost())
4936 ->browser_accessibility_manager();
4937 if (manager) {
4938 if (navigation_handle->IsErrorPage()) {
4939 manager->NavigationFailed();
4940 } else {
4941 manager->NavigationSucceeded();
4942 }
4943 }
4944
Yue Ru Sun979c4b162019-11-06 16:11:044945 if (navigation_handle->IsInMainFrame()) {
4946 last_committed_source_id_including_same_document_ =
Steven Holte38041342018-06-22 22:00:574947 ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
4948 ukm::SourceIdType::NAVIGATION_ID);
Yue Ru Sun979c4b162019-11-06 16:11:044949
4950 if (!navigation_handle->IsSameDocument()) {
4951 was_ever_audible_ = false;
Yue Ru Sun979c4b162019-11-06 16:11:044952 }
Tommy Steimel18360512017-11-01 00:38:194953 }
Lan Weif81c6e7c2020-02-12 16:46:094954
4955 if (!navigation_handle->IsSameDocument())
4956 last_screen_orientation_change_time_ = base::TimeTicks();
dmazzonibf8cec42015-02-08 08:28:084957 }
Xiyuan Xia2a66b112018-12-06 15:52:164958
4959 // If we didn't end up on about:blank after setting this in DidStartNavigation
4960 // then don't focus the location bar.
4961 if (should_focus_location_bar_by_default_ &&
4962 navigation_handle->GetURL() != url::kAboutBlankURL) {
4963 should_focus_location_bar_by_default_ = false;
4964 }
yilkal796e89e2019-10-02 23:58:284965
yilkal172da772019-11-06 22:49:074966 if (navigation_handle->IsInMainFrame() && first_navigation_completed_)
4967 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:284968
yilkal172da772019-11-06 22:49:074969 // If navigation has successfully finished in the main frame, set
4970 // |first_navigation_completed_| to true so that we will record
4971 // |max_loaded_frame_count_| above when future main frame navigations finish.
4972 if (navigation_handle->IsInMainFrame() && !navigation_handle->IsErrorPage()) {
4973 first_navigation_completed_ = true;
4974
4975 // Navigation has completed in main frame. Reset |max_loaded_frame_count_|.
4976 // |max_loaded_frame_count_| is not necessarily 1 if the navigation was
4977 // served from BackForwardCache.
4978 max_loaded_frame_count_ =
4979 GetMainFrame()->frame_tree_node()->GetFrameTreeSize();
yilkal796e89e2019-10-02 23:58:284980 }
Rakina Zata Amni347b70902020-07-22 10:49:044981
4982 if (web_preferences_) {
4983 // Update the WebPreferences for this WebContents that depends on changes
4984 // that might occur during navigation. This will only update the preferences
4985 // that needs to be updated (and won't cause an update/overwrite preferences
4986 // that needs to stay the same after navigations).
4987 bool value_changed_due_to_override =
4988 GetContentClient()->browser()->OverrideWebPreferencesAfterNavigation(
4989 this, web_preferences_.get());
4990 // We need to update the WebPreferences value on the renderer if the value
4991 // is changed due to the override above, or if the navigation is served from
4992 // the back-forward cache, because the WebPreferences value stored in the
4993 // renderer might be stale (because we don't send WebPreferences updates to
4994 // bfcached renderers).
4995 // TODO(rakina): Maybe handle the back-forward cache case in
4996 // ReadyToCommitNavigation instead?
4997 if (value_changed_due_to_override ||
4998 NavigationRequest::From(navigation_handle)
4999 ->IsServedFromBackForwardCache()) {
5000 SetWebPreferences(*web_preferences_.get());
5001 }
5002 }
[email protected]400992b2012-06-14 00:03:545003}
5004
[email protected]b80624c2014-02-09 02:46:555005void WebContentsImpl::DidFailLoadWithError(
5006 RenderFrameHostImpl* render_frame_host,
[email protected]b80624c2014-02-09 02:46:555007 const GURL& url,
Dave Tapuska924ef3c2020-01-22 18:20:595008 int error_code) {
Alexander Timin90c20c32020-08-12 15:28:325009 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5010 observer->DidFailLoad(render_frame_host, url, error_code);
5011 });
[email protected]b80624c2014-02-09 02:46:555012}
5013
[email protected]52913802013-12-10 05:52:185014void WebContentsImpl::NotifyChangedNavigationState(
5015 InvalidateTypes changed_flags) {
5016 NotifyNavigationStateChanged(changed_flags);
5017}
5018
lukasza1d025732016-09-28 21:36:085019bool WebContentsImpl::ShouldTransferNavigation(bool is_main_frame_navigation) {
creis29460272015-12-16 04:38:225020 if (!delegate_)
5021 return true;
lukasza1d025732016-09-28 21:36:085022 return delegate_->ShouldTransferNavigation(is_main_frame_navigation);
creis29460272015-12-16 04:38:225023}
5024
[email protected]aa62afd2014-04-22 19:22:465025bool WebContentsImpl::ShouldPreserveAbortedURLs() {
5026 if (!delegate_)
5027 return false;
5028 return delegate_->ShouldPreserveAbortedURLs(this);
5029}
5030
[email protected]0d0f4c492014-04-02 06:42:575031void WebContentsImpl::DidNavigateMainFramePreCommit(
[email protected]5cfbddc2014-06-23 23:52:235032 bool navigation_is_within_page) {
[email protected]0d0f4c492014-04-02 06:42:575033 // Ensure fullscreen mode is exited before committing the navigation to a
5034 // different page. The next page will not start out assuming it is in
5035 // fullscreen mode.
[email protected]5cfbddc2014-06-23 23:52:235036 if (navigation_is_within_page) {
[email protected]dfc39cb2014-04-09 22:58:195037 // No page change? Then, the renderer and browser can remain in fullscreen.
[email protected]0d0f4c492014-04-02 06:42:575038 return;
5039 }
Avi Drissman97aef042020-06-30 21:04:485040 if (IsFullscreen())
bokanece34a82016-01-28 19:49:465041 ExitFullscreen(false);
Avi Drissman97aef042020-06-30 21:04:485042 DCHECK(!IsFullscreen());
Joe Downingc1a57efe2018-05-09 18:23:545043
5044 // Clean up keyboard lock state when navigating.
5045 CancelKeyboardLock(keyboard_lock_widget_);
[email protected]0d0f4c492014-04-02 06:42:575046}
5047
[email protected]37567b432014-02-12 01:12:225048void WebContentsImpl::DidNavigateMainFramePostCommit(
sky8b00392d2015-01-10 00:30:285049 RenderFrameHostImpl* render_frame_host,
[email protected]37567b432014-02-12 01:12:225050 const LoadCommittedDetails& details,
5051 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
5052 if (details.is_navigation_to_different_page()) {
5053 // Clear the status bubble. This is a workaround for a bug where WebKit
5054 // doesn't let us know that the cursor left an element during a
5055 // transition (this is also why the mouse cursor remains as a hand after
5056 // clicking on a link); see bugs 1184641 and 980803. We don't want to
5057 // clear the bubble when a user navigates to a named anchor in the same
5058 // page.
Lukasz Anforowiczfd707142018-02-07 19:46:135059 ClearTargetURL();
lanwei9d343ad22015-02-11 01:46:005060
5061 RenderWidgetHostViewBase* rwhvb =
5062 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
5063 if (rwhvb)
5064 rwhvb->OnDidNavigateMainFrameToNewPage();
[email protected]37567b432014-02-12 01:12:225065 }
5066
[email protected]e85165c642014-06-10 14:34:315067 if (delegate_)
[email protected]37567b432014-02-12 01:12:225068 delegate_->DidNavigateMainFramePostCommit(this);
[email protected]e85165c642014-06-10 14:34:315069 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Shivani Sharma985474f2019-05-23 21:36:475070
Alan Cutterd73a15d92020-08-21 07:12:455071 // The following events will not fire again if the page is restored from the
5072 // BackForwardCache. So fire them ourselves if needed.
Carlos Caballero91fffb22019-10-29 15:24:305073 if (details.is_navigation_to_different_page() &&
5074 GetRenderViewHost()->did_first_visually_non_empty_paint()) {
Carlos Caballero91fffb22019-10-29 15:24:305075 DidFirstVisuallyNonEmptyPaint(GetRenderViewHost());
5076 }
Alan Cutterd73a15d92020-08-21 07:12:455077 if (GetRenderViewHost()->theme_color() != last_sent_theme_color_)
Carlos Caballero1215f882019-10-29 15:58:435078 OnThemeColorChanged(GetRenderViewHost());
Alan Cutterd73a15d92020-08-21 07:12:455079 if (GetRenderViewHost()->background_color() != last_sent_background_color_)
5080 OnBackgroundColorChanged(GetRenderViewHost());
[email protected]37567b432014-02-12 01:12:225081}
5082
5083void WebContentsImpl::DidNavigateAnyFramePostCommit(
5084 RenderFrameHostImpl* render_frame_host,
5085 const LoadCommittedDetails& details,
5086 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
[email protected]b4c84012014-04-28 19:51:105087 // Now that something has committed, we don't need to track whether the
5088 // initial page has been accessed.
5089 has_accessed_initial_document_ = false;
5090
[email protected]37567b432014-02-12 01:12:225091 // If we navigate off the page, close all JavaScript dialogs.
eugenebutee08663a2017-04-27 17:43:125092 if (!details.is_same_document)
creis89a0f782015-05-27 16:13:175093 CancelActiveAndPendingDialogs();
[email protected]37567b432014-02-12 01:12:225094
avid53461d2016-02-25 17:15:045095 // If this is a user-initiated navigation, start allowing JavaScript dialogs
5096 // again.
avi5d3b8692016-10-12 22:00:465097 if (params.gesture == NavigationGestureUser && dialog_manager_) {
avi6879fcf2017-01-21 05:27:535098 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:465099 }
[email protected]37567b432014-02-12 01:12:225100}
5101
[email protected]277857a2014-06-03 10:38:015102bool WebContentsImpl::CanOverscrollContent() const {
[email protected]e85165c642014-06-10 14:34:315103 // Disable overscroll when touch emulation is on. See crbug.com/369938.
[email protected]34ff1cfc2014-08-20 06:16:055104 if (force_disable_overscroll_content_)
[email protected]e85165c642014-06-10 14:34:315105 return false;
5106
[email protected]37567b432014-02-12 01:12:225107 if (delegate_)
5108 return delegate_->CanOverscrollContent();
5109
5110 return false;
5111}
5112
Carlos Caballero1215f882019-10-29 15:58:435113void WebContentsImpl::OnThemeColorChanged(RenderViewHostImpl* source) {
5114 if (source->did_first_visually_non_empty_paint() &&
5115 last_sent_theme_color_ != source->theme_color()) {
Alexander Timin90c20c32020-08-12 15:28:325116 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5117 observer->DidChangeThemeColor();
5118 });
Matt Jones36fc2882020-08-25 14:25:125119 last_sent_theme_color_ = source->theme_color();
peter90afaba2015-06-01 12:05:295120 }
[email protected]e7104762014-06-20 19:17:255121}
5122
Alan Cutterd73a15d92020-08-21 07:12:455123void WebContentsImpl::OnBackgroundColorChanged(RenderViewHostImpl* source) {
5124 if (source->did_first_visually_non_empty_paint() &&
5125 last_sent_background_color_ != source->background_color()) {
5126 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5127 observer->OnBackgroundColorChanged();
5128 });
5129 last_sent_background_color_ = source->background_color();
5130 }
5131}
5132
Gyuyoung Kim1905f7c2020-05-02 00:00:245133void WebContentsImpl::DidLoadResourceFromMemoryCache(
nicka0ac8382016-12-15 23:59:235134 RenderFrameHostImpl* source,
[email protected]724159a2010-12-30 01:11:185135 const GURL& url,
[email protected]70435962011-08-02 20:13:285136 const std::string& http_method,
[email protected]6d6cfb3a2012-05-23 22:53:185137 const std::string& mime_type,
Kinuko Yasuda433f710a2020-02-14 02:11:585138 network::mojom::RequestDestination request_destination) {
Alexander Timin90c20c32020-08-12 15:28:325139 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5140 observer->DidLoadResourceFromMemoryCache(url, mime_type,
5141 request_destination);
5142 });
[email protected]b0f724c2013-09-05 04:21:135143
Steven Bingler674fb0822018-12-12 18:04:525144 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
nicka0ac8382016-12-15 23:59:235145 StoragePartition* partition = source->GetProcess()->GetStoragePartition();
John Abd-El-Malekf4fe9d82019-07-31 04:05:595146 partition->GetNetworkContext()->NotifyExternalCacheHit(
Matt Menke2a33dee2019-12-02 17:01:545147 url, http_method, source->GetNetworkIsolationKey());
[email protected]8bfc8272013-09-09 20:10:535148 }
[email protected]724159a2010-12-30 01:11:185149}
5150
carloskd9d97942017-02-16 08:58:095151void WebContentsImpl::DidDisplayInsecureContent() {
estarkc2273502016-10-12 22:03:025152 controller_.ssl_manager()->DidDisplayMixedContent();
[email protected]724159a2010-12-30 01:11:185153}
5154
Dave Tapuskaa657d872019-10-21 20:23:215155void WebContentsImpl::DidContainInsecureFormAction() {
elawrenceb2ac2a232017-03-27 21:46:255156 controller_.ssl_manager()->DidContainInsecureFormAction();
5157}
5158
Julie Jeongeun Kim0b103492020-01-29 05:30:515159void WebContentsImpl::DocumentAvailableInMainFrame() {
Alexander Timin90c20c32020-08-12 15:28:325160 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5161 observer->DocumentAvailableInMainFrame();
5162 });
Julie Jeongeun Kim0b103492020-01-29 05:30:515163}
5164
nicka0ac8382016-12-15 23:59:235165void WebContentsImpl::OnDidRunInsecureContent(RenderFrameHostImpl* source,
5166 const GURL& security_origin,
estark910b4572015-12-09 20:55:415167 const GURL& target_url) {
nicka0ac8382016-12-15 23:59:235168 // TODO(nick, estark): Should we call FilterURL using |source|'s process on
5169 // these parameters? |target_url| seems unused, except for a log message. And
5170 // |security_origin| might be replaceable with the origin of the main frame.
carloskd9d97942017-02-16 08:58:095171 DidRunInsecureContent(security_origin, target_url);
5172}
5173
5174void WebContentsImpl::DidRunInsecureContent(const GURL& security_origin,
5175 const GURL& target_url) {
[email protected]9450c462013-11-23 01:22:585176 LOG(WARNING) << security_origin << " ran insecure content from "
5177 << target_url.possibly_invalid_spec();
[email protected]e6e30ac2014-01-13 21:24:395178 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
estark910b4572015-12-09 20:55:415179 if (base::EndsWith(security_origin.spec(), kDotGoogleDotCom,
brettwa7ff1b292015-07-16 17:49:295180 base::CompareCase::INSENSITIVE_ASCII))
[email protected]e6e30ac2014-01-13 21:24:395181 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
estarkc2273502016-10-12 22:03:025182 controller_.ssl_manager()->DidRunMixedContent(security_origin);
[email protected]724159a2010-12-30 01:11:185183}
5184
carloskd9d97942017-02-16 08:58:095185void WebContentsImpl::PassiveInsecureContentFound(const GURL& resource_url) {
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365186 if (delegate_) {
5187 delegate_->PassiveInsecureContentFound(resource_url);
5188 }
carloskd9d97942017-02-16 08:58:095189}
5190
5191bool WebContentsImpl::ShouldAllowRunningInsecureContent(
carloskd9d97942017-02-16 08:58:095192 bool allowed_per_prefs,
5193 const url::Origin& origin,
5194 const GURL& resource_url) {
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365195 if (delegate_) {
Carlos IL29294a62020-05-15 00:21:165196 return delegate_->ShouldAllowRunningInsecureContent(this, allowed_per_prefs,
5197 origin, resource_url);
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365198 }
5199
5200 return allowed_per_prefs;
carloskd9d97942017-02-16 08:58:095201}
5202
Lukasz Anforowicze1b954d92017-10-30 21:28:065203void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
5204 DCHECK_EQ(this, WebContents::FromRenderFrameHost(frame));
5205
5206 // Don't do anything if there is no |delegate_| that could accept and show the
5207 // new WebContents containing the view-source.
5208 if (!delegate_)
5209 return;
5210
5211 // Use the last committed entry, since the pending entry hasn't loaded yet and
5212 // won't be copied into the cloned tab.
5213 NavigationEntryImpl* last_committed_entry =
Fergal Daly09d6c762020-05-29 02:05:185214 GetController().GetLastCommittedEntry();
Lukasz Anforowicze1b954d92017-10-30 21:28:065215 if (!last_committed_entry)
5216 return;
5217
5218 FrameNavigationEntry* frame_entry =
5219 last_committed_entry->GetFrameEntry(frame->frame_tree_node());
5220 if (!frame_entry)
5221 return;
5222
5223 // Any new WebContents opened while this WebContents is in fullscreen can be
5224 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:455225 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5226 // The new view source contents will be independent of this contents, so
5227 // release the fullscreen block.
5228 fullscreen_block.RunAndReset();
Lukasz Anforowicze1b954d92017-10-30 21:28:065229
5230 // We intentionally don't share the SiteInstance with the original frame so
5231 // that view source has a consistent process model and always ends up in a new
5232 // process (https://crbug.com/699493).
5233 scoped_refptr<SiteInstanceImpl> site_instance_for_view_source = nullptr;
Lukasz Anforowicz435bcb582019-07-12 20:50:065234 // Referrer and initiator are not important, because view-source should not
5235 // hit the network, but should be served from the cache instead.
Lukasz Anforowicze1b954d92017-10-30 21:28:065236 Referrer referrer_for_view_source;
Lukasz Anforowicz435bcb582019-07-12 20:50:065237 base::Optional<url::Origin> initiator_for_view_source = base::nullopt;
Lukasz Anforowicze1b954d92017-10-30 21:28:065238 // Do not restore title, derive it from the url.
5239 base::string16 title_for_view_source;
5240 auto navigation_entry = std::make_unique<NavigationEntryImpl>(
5241 site_instance_for_view_source, frame_entry->url(),
Lukasz Anforowicz435bcb582019-07-12 20:50:065242 referrer_for_view_source, initiator_for_view_source,
5243 title_for_view_source, ui::PAGE_TRANSITION_LINK,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:095244 /* is_renderer_initiated = */ false,
5245 /* blob_url_loader_factory = */ nullptr);
Joel Hockey891e88062020-04-30 05:38:445246 const GURL url(content::kViewSourceScheme + std::string(":") +
5247 frame_entry->url().spec());
5248 navigation_entry->SetVirtualURL(url);
Matt Menkea56c5992020-04-10 20:53:565249 navigation_entry->set_isolation_info(
5250 frame->GetIsolationInfoForSubresources());
Yao Xiaof68f57d2019-10-03 04:20:055251
Lukasz Anforowicze1b954d92017-10-30 21:28:065252 // Do not restore scroller position.
5253 // TODO(creis, lukasza, arthursonzogni): Do not reuse the original PageState,
5254 // but start from a new one and only copy the needed data.
5255 const PageState& new_page_state =
5256 frame_entry->page_state().RemoveScrollOffset();
5257
5258 scoped_refptr<FrameNavigationEntry> new_frame_entry =
5259 navigation_entry->root_node()->frame_entry;
5260 new_frame_entry->set_method(frame_entry->method());
5261 new_frame_entry->SetPageState(new_page_state);
5262
5263 // Create a new WebContents, which is used to display the source code.
erikchenbee5c9622018-04-27 19:30:255264 std::unique_ptr<WebContents> view_source_contents =
Erik Chenbb8e738e2018-04-28 14:10:435265 Create(CreateParams(GetBrowserContext()));
Lukasz Anforowicze1b954d92017-10-30 21:28:065266
5267 // Restore the previously created NavigationEntry.
5268 std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
5269 navigation_entries.push_back(std::move(navigation_entry));
5270 view_source_contents->GetController().Restore(0, RestoreType::CURRENT_SESSION,
5271 &navigation_entries);
5272
5273 // Add |view_source_contents| as a new tab.
5274 gfx::Rect initial_rect;
5275 constexpr bool kUserGesture = true;
5276 bool ignored_was_blocked;
Joel Hockey891e88062020-04-30 05:38:445277 delegate_->AddNewContents(this, std::move(view_source_contents), url,
Lukasz Anforowicze1b954d92017-10-30 21:28:065278 WindowOpenDisposition::NEW_FOREGROUND_TAB,
5279 initial_rect, kUserGesture, &ignored_was_blocked);
5280 // Note that the |delegate_| could have deleted |view_source_contents| during
5281 // AddNewContents method call.
5282}
5283
Lukasz Anforowiczd334bba2020-02-10 23:32:555284void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
5285 net::CertStatus cert_status) {
5286 controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
Jay Civellid5904f02018-03-23 19:43:575287 SetNotWaitingForResponse();
5288}
5289
Jay Civelli116683f2018-03-27 19:56:235290void WebContentsImpl::ResourceLoadComplete(
Jay Civelli52a63302018-04-30 22:39:555291 RenderFrameHost* render_frame_host,
Clark DuVall36164bd2018-08-09 22:49:085292 const GlobalRequestID& request_id,
Minggang Wangee5af392020-02-05 02:55:285293 blink::mojom::ResourceLoadInfoPtr resource_load_info) {
Alexander Timin90c20c32020-08-12 15:28:325294 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5295 observer->ResourceLoadComplete(render_frame_host, request_id,
5296 *resource_load_info);
5297 });
John Abd-El-Malekd4882642017-12-04 21:45:195298}
5299
Rakina Zata Amni347b70902020-07-22 10:49:045300const WebPreferences& WebContentsImpl::GetOrCreateWebPreferences() {
5301 // Compute WebPreferences based on the current state if it's null.
5302 if (!web_preferences_)
Rakina Zata Amni4029b6d2020-07-28 02:36:205303 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045304 return *web_preferences_.get();
5305}
5306
5307bool WebContentsImpl::IsWebPreferencesSet() const {
5308 return web_preferences_.get();
5309}
5310
5311void WebContentsImpl::SetWebPreferences(const WebPreferences& prefs) {
5312 web_preferences_ = std::make_unique<WebPreferences>(prefs);
5313 // Get all the RenderViewHosts (except the ones for currently back-forward
5314 // cached pages), and make them send the current WebPreferences
5315 // to the renderer. WebPreferences updates for back-forward cached pages will
5316 // be sent when we restore those pages from the back-forward cache.
5317 for (auto& rvh : frame_tree_.render_view_hosts()) {
5318 rvh.second->SendWebPreferencesToRenderer();
5319 }
5320}
5321
5322void WebContentsImpl::RecomputeWebPreferencesSlow() {
Rakina Zata Amni4029b6d2020-07-28 02:36:205323 // OnWebPreferencesChanged is a no-op when this is true.
5324 if (updating_web_preferences_)
5325 return;
Rakina Zata Amni347b70902020-07-22 10:49:045326 // Resets |web_preferences_| so that we won't have any cached value for slow
5327 // attributes (which won't get recomputed if we have pre-existing values for
5328 // them).
5329 web_preferences_.reset();
Rakina Zata Amni4029b6d2020-07-28 02:36:205330 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045331}
5332
Wei Li5bb659742018-02-14 03:07:585333void WebContentsImpl::PrintCrossProcessSubframe(
5334 const gfx::Rect& rect,
5335 int document_cookie,
5336 RenderFrameHost* subframe_host) {
Wei Li5c0b4d12018-03-22 15:05:225337 auto* outer_contents = GetOuterWebContents();
5338 if (outer_contents) {
5339 // When an extension or app page is printed, the content should be
5340 // composited with outer content, so the outer contents should handle the
5341 // print request.
5342 outer_contents->PrintCrossProcessSubframe(rect, document_cookie,
5343 subframe_host);
5344 return;
5345 }
5346
Wei Li5bb659742018-02-14 03:07:585347 // If there is no delegate such as in tests or during deletion, do nothing.
5348 if (!delegate_)
5349 return;
5350
5351 delegate_->PrintCrossProcessSubframe(this, rect, document_cookie,
5352 subframe_host);
5353}
5354
ckitagawa8695799b2020-02-05 16:08:495355void WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe(
5356 const gfx::Rect& rect,
5357 const base::UnguessableToken& guid,
5358 RenderFrameHost* render_frame_host) {
5359 if (!delegate_)
5360 return;
ckitagawac43ac982020-07-07 17:41:175361 delegate_->CapturePaintPreviewOfSubframe(this, rect, guid, render_frame_host);
ckitagawa8695799b2020-02-05 16:08:495362}
5363
rob.buis300b0872017-03-10 20:43:585364#if defined(OS_ANDROID)
5365base::android::ScopedJavaLocalRef<jobject>
5366WebContentsImpl::GetJavaRenderFrameHostDelegate() {
5367 return GetJavaWebContents();
5368}
5369#endif
5370
Hiroki Nakagawa39d1bbe2020-07-14 16:15:525371void WebContentsImpl::OnDidDisplayContentWithCertificateErrors() {
estarkc2273502016-10-12 22:03:025372 controller_.ssl_manager()->DidDisplayContentWithCertErrors();
estark910b4572015-12-09 20:55:415373}
5374
5375void WebContentsImpl::OnDidRunContentWithCertificateErrors(
Zhuoyu Qian4353f7f2018-01-08 05:33:005376 RenderFrameHostImpl* source) {
Emily Starkabbdd662020-06-05 02:40:135377 // For RenderFrameHosts that are inactive and going to be discarded, we can
5378 // disregard this message; there's no need to update the UI if the UI will
5379 // never be shown again.
5380 //
5381 // We still process this message for speculative RenderFrameHosts. This can
5382 // happen when a subframe's main resource has a certificate error. The
5383 // currently committed navigation entry will get marked as having run insecure
5384 // content and that will carry over to the navigation entry for the
5385 // speculative RFH when it commits.
5386 if (source->lifecycle_state() !=
5387 RenderFrameHostImpl::LifecycleState::kSpeculative &&
5388 source->IsInactiveAndDisallowReactivation()) {
estarkaeda1422016-05-10 02:31:125389 return;
Emily Starkabbdd662020-06-05 02:40:135390 }
estarkcd2e30c2016-08-12 06:51:155391 controller_.ssl_manager()->DidRunContentWithCertErrors(
Emily Starkabbdd662020-06-05 02:40:135392 source->GetMainFrame()->GetLastCommittedOrigin().GetURL());
estark910b4572015-12-09 20:55:415393}
5394
Kouhei Ueno97e0990d2019-09-25 02:57:275395void WebContentsImpl::DOMContentLoaded(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:325396 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5397 observer->DOMContentLoaded(render_frame_host);
5398 });
[email protected]724159a2010-12-30 01:11:185399}
5400
Gyuyoung Kim525e0c5d2020-03-09 15:04:195401void WebContentsImpl::OnDidFinishLoad(RenderFrameHost* render_frame_host,
nicka0ac8382016-12-15 23:59:235402 const GURL& url) {
[email protected]8b3af1e2014-01-24 13:29:125403 GURL validated_url(url);
Gyuyoung Kim525e0c5d2020-03-09 15:04:195404 render_frame_host->GetProcess()->FilterURL(false, &validated_url);
[email protected]028053d42014-03-05 22:20:375405
Alexander Timin90c20c32020-08-12 15:28:325406 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5407 observer->DidFinishLoad(render_frame_host, validated_url);
5408 });
yilkal172da772019-11-06 22:49:075409 size_t tree_size = frame_tree_.root()->GetFrameTreeSize();
5410 if (max_loaded_frame_count_ < tree_size)
5411 max_loaded_frame_count_ = tree_size;
5412
Gyuyoung Kim525e0c5d2020-03-09 15:04:195413 if (!render_frame_host->GetParent())
yilkal172da772019-11-06 22:49:075414 UMA_HISTOGRAM_COUNTS_1000("Navigation.MainFrame.FrameCount", tree_size);
[email protected]1a55c5be2011-11-29 11:36:315415}
5416
Dave Tapuska549baab2019-03-19 15:52:405417void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source,
Julie Jeongeun Kim144f8192020-01-18 06:59:035418 int32_t offset,
Dave Tapuska043b94a2019-09-10 14:14:355419 bool has_user_gesture) {
Arthur Sonzognia7d715a2018-09-20 16:11:135420 // Non-user initiated navigations coming from the renderer should be ignored
5421 // if there is an ongoing browser-initiated navigation.
5422 // See https://crbug.com/879965.
5423 // TODO(arthursonzogni): See if this should check for ongoing navigations in
5424 // the frame(s) affected by the session history navigation, rather than just
5425 // the main frame.
Kevin McNee96851e12020-07-16 03:43:225426 if (Navigator::ShouldIgnoreIncomingRendererRequest(
5427 frame_tree_.root()->navigation_request(), has_user_gesture))
5428 return;
Arthur Sonzognia7d715a2018-09-20 16:11:135429
nicka0ac8382016-12-15 23:59:235430 // All frames are allowed to navigate the global history.
Dave Tapuska8bfd84c2019-03-26 20:47:165431 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
arthursonzognib93a4472020-04-10 07:38:005432 if (source->IsSandboxed(network::mojom::WebSandboxFlags::kTopNavigation)) {
Dave Tapuska8bfd84c2019-03-26 20:47:165433 // Keep track of whether this is a session history from a sandboxed iframe
5434 // with top level navigation disallowed.
5435 controller_.GoToOffsetInSandboxedFrame(offset,
5436 source->GetFrameTreeNodeId());
5437 } else {
5438 controller_.GoToOffset(offset);
5439 }
5440 }
[email protected]216813952011-05-19 22:21:265441}
5442
Dave Tapuska4c02911b2020-02-14 22:52:075443void WebContentsImpl::OnPageScaleFactorChanged(RenderFrameHostImpl* source,
nicka0ac8382016-12-15 23:59:235444 float page_scale_factor) {
mcnee336ea2c2017-05-23 22:50:595445#if !defined(OS_ANDROID)
5446 // While page scale factor is used on mobile, this PageScaleFactorIsOne logic
5447 // is only needed on desktop.
mcnee432e47d2015-11-09 19:37:465448 bool is_one = page_scale_factor == 1.f;
5449 if (is_one != page_scale_factor_is_one_) {
5450 page_scale_factor_is_one_ = is_one;
5451
5452 HostZoomMapImpl* host_zoom_map =
5453 static_cast<HostZoomMapImpl*>(HostZoomMap::GetForWebContents(this));
5454
nicka0ac8382016-12-15 23:59:235455 if (host_zoom_map) {
mcnee432e47d2015-11-09 19:37:465456 host_zoom_map->SetPageScaleFactorIsOneForView(
Dave Tapuska4c02911b2020-02-14 22:52:075457 source->GetProcess()->GetID(),
5458 source->GetRenderViewHost()->GetRoutingID(),
mcnee432e47d2015-11-09 19:37:465459 page_scale_factor_is_one_);
5460 }
5461 }
mcnee336ea2c2017-05-23 22:50:595462#endif // !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:465463
Alexander Timin90c20c32020-08-12 15:28:325464 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5465 observer->OnPageScaleFactorChanged(page_scale_factor);
5466 });
mcnee432e47d2015-11-09 19:37:465467}
5468
W. James MacLean62198672019-06-04 16:46:105469void WebContentsImpl::OnTextAutosizerPageInfoChanged(
Henrique Ferreiroba535472020-04-21 11:38:365470 RenderFrameHostImpl* source,
5471 blink::mojom::TextAutosizerPageInfoPtr page_info) {
W. James MacLean62198672019-06-04 16:46:105472 // Keep a copy of |page_info| in case we create a new RenderView before
5473 // the next update.
Henrique Ferreiroba535472020-04-21 11:38:365474 text_autosizer_page_info_.main_frame_width = page_info->main_frame_width;
5475 text_autosizer_page_info_.main_frame_layout_width =
5476 page_info->main_frame_layout_width;
5477 text_autosizer_page_info_.device_scale_adjustment =
5478 page_info->device_scale_adjustment;
Antonio Gomesda7e03d2020-08-05 15:03:085479
5480 auto remote_frames_broadcast_callback = base::BindRepeating(
5481 [](const blink::mojom::TextAutosizerPageInfo& page_info,
5482 RenderFrameProxyHost* proxy_host) {
5483 DCHECK(proxy_host);
5484 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
5485 page_info.Clone());
5486 },
5487 text_autosizer_page_info_);
5488
5489 frame_tree_.root()->render_manager()->ExecuteRemoteFramesBroadcastMethod(
5490 std::move(remote_frames_broadcast_callback), source->GetSiteInstance());
W. James MacLean62198672019-06-04 16:46:105491}
5492
Kent Tamura8c9e0562018-11-06 07:02:195493void WebContentsImpl::EnumerateDirectory(
5494 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:015495 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamura8c9e0562018-11-06 07:02:195496 const base::FilePath& directory_path) {
Avi Drissman1a55a9d62020-03-10 18:56:455497 // Any explicit focusing of another window while this WebContents is in
5498 // fullscreen can be used to confuse the user, so drop fullscreen.
5499 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5500 listener->SetFullscreenBlock(std::move(fullscreen_block));
5501
Kent Tamura8c9e0562018-11-06 07:02:195502 if (delegate_)
5503 delegate_->EnumerateDirectory(this, std::move(listener), directory_path);
5504 else
5505 listener->FileSelectionCanceled();
[email protected]3a29a6e2011-08-24 18:26:215506}
5507
Dave Tapuskaf9fc3122019-10-18 19:42:555508void WebContentsImpl::RegisterProtocolHandler(RenderFrameHostImpl* source,
5509 const std::string& protocol,
5510 const GURL& url,
5511 const base::string16& title,
5512 bool user_gesture) {
nicka0ac8382016-12-15 23:59:235513 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]e5f2de02012-07-20 22:15:435514 if (!delegate_)
5515 return;
5516
Raymes Khoury58373df2019-08-06 06:29:205517 if (!AreValidRegisterProtocolHandlerArguments(
5518 protocol, url, source->GetLastCommittedOrigin())) {
5519 ReceivedBadMessage(source->GetProcess(),
5520 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]b9535422012-02-09 01:47:595521 return;
Raymes Khoury58373df2019-08-06 06:29:205522 }
[email protected]8f810632013-06-06 22:33:325523
Carlos Caballero8a6c6b72020-07-20 16:56:225524 delegate_->RegisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]7d189022011-08-25 22:54:205525}
5526
Dave Tapuskaf9fc3122019-10-18 19:42:555527void WebContentsImpl::UnregisterProtocolHandler(RenderFrameHostImpl* source,
5528 const std::string& protocol,
5529 const GURL& url,
5530 bool user_gesture) {
nicka0ac8382016-12-15 23:59:235531 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]f5273e52014-07-14 16:30:205532 if (!delegate_)
5533 return;
5534
Raymes Khoury58373df2019-08-06 06:29:205535 if (!AreValidRegisterProtocolHandlerArguments(
5536 protocol, url, source->GetLastCommittedOrigin())) {
5537 ReceivedBadMessage(source->GetProcess(),
5538 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]f5273e52014-07-14 16:30:205539 return;
Raymes Khoury58373df2019-08-06 06:29:205540 }
[email protected]f5273e52014-07-14 16:30:205541
Carlos Caballero8a6c6b72020-07-20 16:56:225542 delegate_->UnregisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]f5273e52014-07-14 16:30:205543}
5544
Marijn Kruisselbrink7f519672019-02-05 19:12:505545void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
[email protected]b172aee2012-04-10 17:05:265546 bool blocked_by_policy) {
nicka0ac8382016-12-15 23:59:235547 // TODO(nick): Should we consider |source| here? Should we call FilterURL on
5548 // |manifest_url|?
5549
[email protected]7fc4bbb2011-09-08 21:23:105550 // Notify observers about navigation.
Alexander Timin90c20c32020-08-12 15:28:325551 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5552 observer->AppCacheAccessed(manifest_url, blocked_by_policy);
5553 });
[email protected]7fc4bbb2011-09-08 21:23:105554}
5555
Gyuyoung Kimc5f4ac12020-05-08 10:59:395556void WebContentsImpl::DomOperationResponse(const std::string& json_string) {
5557 // TODO(lukasza): The notification below should probably indicate which
5558 // RenderFrameHostImpl the message is coming from. This can enable tests to
5559 // talk to 2 frames at the same time, without being confused which frame a
5560 // given response comes from. See also a corresponding TODO in the
5561 // ExecuteScriptHelper in //content/public/test/browser_test_utils.cc
5562 NotificationService::current()->Notify(
5563 NOTIFICATION_DOM_OPERATION_RESPONSE, Source<WebContents>(this),
5564 Details<const std::string>(&json_string));
5565}
5566
Gyuyoung Kim4c50517842020-06-04 17:50:445567void WebContentsImpl::SavableResourceLinksResponse(
5568 RenderFrameHostImpl* source,
5569 const std::vector<GURL>& resources_list,
5570 blink::mojom::ReferrerPtr referrer,
5571 const std::vector<blink::mojom::SavableSubframePtr>& subframes) {
5572 save_package_->SavableResourceLinksResponse(source, resources_list,
5573 std::move(referrer), subframes);
5574}
5575
5576void WebContentsImpl::SavableResourceLinksError(RenderFrameHostImpl* source) {
5577 save_package_->SavableResourceLinksError(source);
5578}
5579
Alexander Timin17edc742020-04-23 18:22:185580void WebContentsImpl::OnServiceWorkerAccessed(
5581 RenderFrameHost* render_frame_host,
5582 const GURL& scope,
5583 AllowServiceWorkerResult allowed) {
Alexander Timin90c20c32020-08-12 15:28:325584 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5585 observer->OnServiceWorkerAccessed(render_frame_host, scope, allowed);
5586 });
Alexander Timin17edc742020-04-23 18:22:185587}
5588
5589void WebContentsImpl::OnServiceWorkerAccessed(
5590 NavigationHandle* navigation,
5591 const GURL& scope,
5592 AllowServiceWorkerResult allowed) {
Alexander Timin90c20c32020-08-12 15:28:325593 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5594 observer->OnServiceWorkerAccessed(navigation, scope, allowed);
5595 });
Alexander Timin17edc742020-04-23 18:22:185596}
5597
Miyoung Shincb6475a2019-11-09 10:49:455598void WebContentsImpl::OnColorChooserFactoryReceiver(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205599 mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver) {
5600 color_chooser_factory_receivers_.Add(this, std::move(receiver));
Joel Hockey85b379d2017-12-11 10:42:135601}
5602
5603void WebContentsImpl::OpenColorChooser(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205604 mojo::PendingReceiver<blink::mojom::ColorChooser> chooser_receiver,
5605 mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
[email protected]8ed16472014-04-11 19:02:485606 SkColor color,
Joel Hockey163835a2017-12-20 11:51:575607 std::vector<blink::mojom::ColorSuggestionPtr> suggestions) {
Joel Hockey85b379d2017-12-11 10:42:135608 content::ColorChooser* new_color_chooser =
Ivan Kotenkov2c0d2bb32017-11-01 15:41:285609 delegate_ ? delegate_->OpenColorChooser(this, color, suggestions)
5610 : nullptr;
[email protected]820957a2014-01-14 14:56:305611 if (!new_color_chooser)
[email protected]cb805452013-05-22 15:16:215612 return;
[email protected]8ed16472014-04-11 19:02:485613
Joel Hockey85b379d2017-12-11 10:42:135614 color_chooser_.reset();
5615 color_chooser_ = std::make_unique<ColorChooser>(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:205616 new_color_chooser, std::move(chooser_receiver), std::move(client));
[email protected]da8543762012-03-20 08:52:205617}
5618
brettw4b461082016-11-19 18:55:165619#if BUILDFLAG(ENABLE_PLUGINS)
nicka0ac8382016-12-15 23:59:235620void WebContentsImpl::OnPepperInstanceCreated(RenderFrameHostImpl* source,
5621 int32_t pp_instance) {
Alexander Timin90c20c32020-08-12 15:28:325622 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5623 observer->PepperInstanceCreated();
5624 });
nicka0ac8382016-12-15 23:59:235625 pepper_playback_observer_->PepperInstanceCreated(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:005626}
5627
nicka0ac8382016-12-15 23:59:235628void WebContentsImpl::OnPepperInstanceDeleted(RenderFrameHostImpl* source,
5629 int32_t pp_instance) {
Alexander Timin90c20c32020-08-12 15:28:325630 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5631 observer->PepperInstanceDeleted();
5632 });
nicka0ac8382016-12-15 23:59:235633 pepper_playback_observer_->PepperInstanceDeleted(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:005634}
5635
nicka0ac8382016-12-15 23:59:235636void WebContentsImpl::OnPepperPluginHung(RenderFrameHostImpl* source,
5637 int plugin_child_id,
tommyclie6633ca72014-10-31 00:40:425638 const base::FilePath& path,
5639 bool is_hung) {
Steven Holte95922222018-09-14 20:06:235640 UMA_HISTOGRAM_COUNTS_1M("Pepper.PluginHung", 1);
tommyclie6633ca72014-10-31 00:40:425641
Alexander Timin90c20c32020-08-12 15:28:325642 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5643 observer->PluginHungStatusChanged(plugin_child_id, path, is_hung);
5644 });
tommyclie6633ca72014-10-31 00:40:425645}
5646
nicka0ac8382016-12-15 23:59:235647void WebContentsImpl::OnPepperStartsPlayback(RenderFrameHostImpl* source,
5648 int32_t pp_instance) {
5649 pepper_playback_observer_->PepperStartsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:175650}
5651
nicka0ac8382016-12-15 23:59:235652void WebContentsImpl::OnPepperStopsPlayback(RenderFrameHostImpl* source,
5653 int32_t pp_instance) {
5654 pepper_playback_observer_->PepperStopsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:175655}
5656
nicka0ac8382016-12-15 23:59:235657void WebContentsImpl::OnPluginCrashed(RenderFrameHostImpl* source,
5658 const base::FilePath& plugin_path,
tommyclie6633ca72014-10-31 00:40:425659 base::ProcessId plugin_pid) {
nicka0ac8382016-12-15 23:59:235660 // TODO(nick): Eliminate the |plugin_pid| parameter, which can't be trusted,
Gyuyoung Kim26c7bc92020-04-29 00:53:005661 // and is only used by WebTestControlHost.
Alexander Timin90c20c32020-08-12 15:28:325662 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5663 observer->PluginCrashed(plugin_path, plugin_pid);
5664 });
tommyclie6633ca72014-10-31 00:40:425665}
5666
[email protected]d8415ad92012-08-23 14:40:505667void WebContentsImpl::OnRequestPpapiBrokerPermission(
nicka0ac8382016-12-15 23:59:235668 RenderViewHostImpl* source,
5669 int ppb_broker_route_id,
[email protected]d8415ad92012-08-23 14:40:505670 const GURL& url,
[email protected]2dec8ec2013-02-07 19:20:345671 const base::FilePath& plugin_path) {
Avi Drissman0a2a967d2019-04-01 19:33:525672 base::OnceCallback<void(bool)> permission_result_callback = base::BindOnce(
nicka0ac8382016-12-15 23:59:235673 &WebContentsImpl::SendPpapiBrokerPermissionResult, base::Unretained(this),
5674 source->GetProcess()->GetID(), ppb_broker_route_id);
[email protected]8c8fc292012-11-23 18:57:165675 if (!delegate_) {
Tommy Nyquist4b749d02018-03-20 21:46:295676 std::move(permission_result_callback).Run(false);
[email protected]8c8fc292012-11-23 18:57:165677 return;
[email protected]d8415ad92012-08-23 14:40:505678 }
5679
Avi Drissman0a2a967d2019-04-01 19:33:525680 delegate_->RequestPpapiBrokerPermission(
5681 this, url, plugin_path, std::move(permission_result_callback));
[email protected]d8415ad92012-08-23 14:40:505682}
5683
nicka0ac8382016-12-15 23:59:235684void WebContentsImpl::SendPpapiBrokerPermissionResult(int process_id,
5685 int ppb_broker_route_id,
5686 bool result) {
5687 RenderProcessHost* rph = RenderProcessHost::FromID(process_id);
5688 if (rph) {
5689 // TODO(nick): Convert this from ViewMsg_ to a Ppapi msg, since it
5690 // is not routed to a RenderView.
5691 rph->Send(
5692 new ViewMsg_PpapiBrokerPermissionResult(ppb_broker_route_id, result));
5693 }
[email protected]d8415ad92012-08-23 14:40:505694}
brettw4b461082016-11-19 18:55:165695#endif // BUILDFLAG(ENABLE_PLUGINS)
[email protected]19be7a62012-10-01 23:03:375696
Miyoung Shin5709ab02020-02-19 06:50:415697void WebContentsImpl::UpdateFaviconURL(
5698 RenderFrameHost* source,
5699 std::vector<blink::mojom::FaviconURLPtr> candidates) {
lukasza178ff092017-06-07 23:39:505700 // Ignore favicons for non-main frame.
5701 if (source->GetParent()) {
5702 NOTREACHED();
5703 return;
5704 }
5705
pkotwiczf9bc20592015-04-21 18:57:065706 // We get updated favicon URLs after the page stops loading. If a cross-site
5707 // navigation occurs while a page is still loading, the initial page
5708 // may stop loading and send us updated favicon URLs after the navigation
5709 // for the new page has committed.
lukasza178ff092017-06-07 23:39:505710 if (!source->IsCurrent())
pkotwiczf9bc20592015-04-21 18:57:065711 return;
5712
Miyoung Shin5709ab02020-02-19 06:50:415713 favicon_urls_ = std::move(candidates);
Mounir Lamouri7b4a1f232019-12-23 16:32:105714
Alexander Timin90c20c32020-08-12 15:28:325715 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5716 observer->DidUpdateFaviconURL(source, favicon_urls_);
5717 });
[email protected]795c28972012-12-06 06:13:395718}
5719
qinmin72e8bd02016-10-21 19:35:375720void WebContentsImpl::SetIsOverlayContent(bool is_overlay_content) {
5721 is_overlay_content_ = is_overlay_content;
5722}
5723
Albert J. Wongfb64e142018-10-16 01:10:455724void WebContentsImpl::DidFirstVisuallyNonEmptyPaint(
5725 RenderViewHostImpl* source) {
nicka0ac8382016-12-15 23:59:235726 // TODO(nick): When this is ported to FrameHostMsg_, we should only listen if
5727 // |source| is the main frame.
Alexander Timin90c20c32020-08-12 15:28:325728 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5729 observer->DidFirstVisuallyNonEmptyPaint();
5730 });
Carlos Caballero1215f882019-10-29 15:58:435731 if (source->theme_color() != last_sent_theme_color_) {
yusufod41c5f92015-03-06 00:14:285732 // Theme color should have updated by now if there was one.
Alexander Timin90c20c32020-08-12 15:28:325733 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5734 observer->DidChangeThemeColor();
5735 });
Carlos Caballero1215f882019-10-29 15:58:435736 last_sent_theme_color_ = source->theme_color();
yusufod41c5f92015-03-06 00:14:285737 }
Alan Cutterd73a15d92020-08-21 07:12:455738
5739 if (source->background_color() != last_sent_background_color_) {
5740 // Background color should have updated by now if there was one.
5741 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5742 observer->OnBackgroundColorChanged();
5743 });
5744 last_sent_background_color_ = source->background_color();
5745 }
[email protected]9f268072013-11-07 00:02:155746}
[email protected]d9030b82013-07-19 08:26:065747
Kevin McNee068c3eb2020-04-03 18:24:195748bool WebContentsImpl::IsPortal() {
Adithya Srinivasan46b8a792019-02-01 14:47:235749 return portal();
5750}
5751
Kevin McNee94ea52f52020-06-23 17:42:065752WebContentsImpl* WebContentsImpl::GetPortalHostWebContents() {
5753 return portal() ? portal()->GetPortalHostContents() : nullptr;
5754}
5755
[email protected]17e286e2013-03-01 23:29:395756void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
Alexander Timin90c20c32020-08-12 15:28:325757 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5758 observer->BeforeFormRepostWarningShow();
5759 });
[email protected]17e286e2013-03-01 23:29:395760}
5761
[email protected]ec6c05f2013-10-23 18:41:575762void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
5763 Activate();
5764 if (delegate_)
5765 delegate_->ShowRepostFormWarningDialog(this);
5766}
5767
[email protected]b4c84012014-04-28 19:51:105768bool WebContentsImpl::HasAccessedInitialDocument() {
5769 return has_accessed_initial_document_;
5770}
5771
afakhry6f0c1ec22016-07-14 13:55:135772void WebContentsImpl::UpdateTitleForEntry(NavigationEntry* entry,
[email protected]fcf75d42013-12-03 20:11:265773 const base::string16& title) {
[email protected]fcf75d42013-12-03 20:11:265774 base::string16 final_title;
Avi Drissman93002212017-09-27 03:20:525775 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
[email protected]420ae012009-04-24 05:16:325776
[email protected]987fc3a2011-05-26 14:18:095777 // If a page is created via window.open and never navigated,
5778 // there will be no navigation entry. In this situation,
[email protected]73eb2602012-02-09 19:50:555779 // |page_title_when_no_navigation_entry_| will be used for page title.
[email protected]987fc3a2011-05-26 14:18:095780 if (entry) {
[email protected]36fc0392011-12-25 03:59:515781 if (final_title == entry->GetTitle())
afakhry6f0c1ec22016-07-14 13:55:135782 return; // Nothing changed, don't bother.
[email protected]420ae012009-04-24 05:16:325783
[email protected]36fc0392011-12-25 03:59:515784 entry->SetTitle(final_title);
Avi Drissman93002212017-09-27 03:20:525785
5786 // The title for display may differ from the title just set; grab it.
5787 final_title = entry->GetTitleForDisplay();
[email protected]987fc3a2011-05-26 14:18:095788 } else {
5789 if (page_title_when_no_navigation_entry_ == final_title)
afakhry6f0c1ec22016-07-14 13:55:135790 return; // Nothing changed, don't bother.
[email protected]987fc3a2011-05-26 14:18:095791
5792 page_title_when_no_navigation_entry_ = final_title;
5793 }
[email protected]420ae012009-04-24 05:16:325794
[email protected]420ae012009-04-24 05:16:325795 // Lastly, set the title for the view.
[email protected]790e2fd2011-09-21 20:28:235796 view_->SetPageTitle(final_title);
[email protected]420ae012009-04-24 05:16:325797
Alexander Timin90c20c32020-08-12 15:28:325798 observers_.ForEachObserver(
5799 [&](WebContentsObserver* observer) { observer->TitleWasSet(entry); });
afakhry6f0c1ec22016-07-14 13:55:135800 // Broadcast notifications when the UI should be updated.
5801 if (entry == controller_.GetEntryAtOffset(0))
5802 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
[email protected]420ae012009-04-24 05:16:325803}
5804
fdegansa696e5112015-04-17 01:57:595805void WebContentsImpl::SendChangeLoadProgress() {
[email protected]960b0372014-05-19 18:01:005806 loading_last_progress_update_ = base::TimeTicks::Now();
Alexander Timin90c20c32020-08-12 15:28:325807 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5808 observer->LoadProgressChanged(frame_tree_.load_progress());
5809 });
[email protected]960b0372014-05-19 18:01:005810}
5811
5812void WebContentsImpl::ResetLoadProgressState() {
fdegans1d16355162015-03-26 11:58:345813 frame_tree_.ResetLoadProgress();
[email protected]960b0372014-05-19 18:01:005814 loading_weak_factory_.InvalidateWeakPtrs();
5815 loading_last_progress_update_ = base::TimeTicks();
5816}
5817
clamy44e84ce2016-02-22 15:38:255818// Notifies the RenderWidgetHost instance about the fact that the page is
5819// loading, or done loading.
5820void WebContentsImpl::LoadingStateChanged(bool to_different_document,
clamy44e84ce2016-02-22 15:38:255821 LoadNotificationDetails* details) {
Nate Chapin22ea6592019-03-05 22:29:025822 if (is_being_destroyed_)
5823 return;
clamy44e84ce2016-02-22 15:38:255824
5825 bool is_loading = IsLoading();
5826
5827 if (!is_loading) {
5828 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
5829 base::string16());
5830 load_state_host_.clear();
5831 upload_size_ = 0;
5832 upload_position_ = 0;
5833 }
5834
5835 GetRenderManager()->SetIsLoading(is_loading);
5836
5837 waiting_for_response_ = is_loading;
5838 is_load_to_different_document_ = to_different_document;
5839
5840 if (delegate_)
5841 delegate_->LoadingStateChanged(this, to_different_document);
5842 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
5843
5844 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
5845 if (is_loading) {
5846 TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
5847 this, "URL", url, "Main FrameTreeNode id",
5848 GetFrameTree()->root()->frame_tree_node_id());
Alexander Timin90c20c32020-08-12 15:28:325849 observers_.ForEachObserver(
5850 [&](WebContentsObserver* observer) { observer->DidStartLoading(); });
clamy44e84ce2016-02-22 15:38:255851 } else {
5852 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
5853 this, "URL", url);
Alexander Timin90c20c32020-08-12 15:28:325854 observers_.ForEachObserver(
5855 [&](WebContentsObserver* observer) { observer->DidStopLoading(); });
clamy44e84ce2016-02-22 15:38:255856 }
5857
5858 // TODO(avi): Remove. http://crbug.com/170921
5859 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
5860 NotificationDetails det = NotificationService::NoDetails();
5861 if (details)
5862 det = Details<LoadNotificationDetails>(details);
5863 NotificationService::current()->Notify(
5864 type, Source<NavigationController>(&controller_), det);
5865}
5866
danakja0bce4c952020-05-12 20:40:285867void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_view,
5868 RenderViewHost* new_view) {
5869 DCHECK_NE(old_view, new_view);
[email protected]420ae012009-04-24 05:16:325870 // After sending out a swap notification, we need to send a disconnect
5871 // notification so that clients that pick up a pointer to |this| can NULL the
5872 // pointer. See Bug 1230284.
5873 notify_disconnection_ = true;
Alexander Timin90c20c32020-08-12 15:28:325874 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5875 observer->RenderViewHostChanged(old_view, new_view);
5876 });
danakja0bce4c952020-05-12 20:40:285877 view_->RenderViewHostChanged(old_view, new_view);
Jinsuk Kimdc5284c22018-07-11 02:22:065878
Lucas Furukawa Gadanif9ea4fc2018-08-03 23:57:135879 // If this is an inner WebContents that has swapped views, we need to reattach
5880 // it to its outer WebContents.
5881 if (node_.outer_web_contents())
5882 ReattachToOuterWebContentsFrame();
5883
[email protected]7a846df2012-09-20 19:17:395884 // Ensure that the associated embedder gets cleared after a RenderViewHost
5885 // gets swapped, so we don't reuse the same embedder next time a
5886 // RenderViewHost is attached to this WebContents.
5887 RemoveBrowserPluginEmbedder();
[email protected]420ae012009-04-24 05:16:325888}
5889
danakja0bce4c952020-05-12 20:40:285890void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_frame,
5891 RenderFrameHost* new_frame,
Jinsuk Kim895b2c52018-07-03 06:49:165892 bool is_main_frame) {
Bo Liu168c8642017-08-28 18:26:025893#if defined(OS_ANDROID)
danakja0bce4c952020-05-12 20:40:285894 // Copy importance from |old_frame| if |new_frame| is a main frame.
5895 if (old_frame && !new_frame->GetParent()) {
5896 RenderWidgetHostImpl* old_widget =
5897 static_cast<RenderFrameHostImpl*>(old_frame)->GetRenderWidgetHost();
5898 RenderWidgetHostImpl* new_widget =
5899 static_cast<RenderFrameHostImpl*>(new_frame)->GetRenderWidgetHost();
5900 new_widget->SetImportance(old_widget->importance());
Bo Liu7c6779e92017-08-16 02:02:285901 }
Bo Liu168c8642017-08-28 18:26:025902#endif
Alexander Timin90c20c32020-08-12 15:28:325903 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5904 observer->RenderFrameHostChanged(old_frame, new_frame);
5905 });
[email protected]02d7b6e2014-06-24 21:01:505906}
5907
[email protected]da7a7182013-09-06 08:11:115908// TODO(avi): Remove this entire function because this notification is already
5909// covered by two observer functions. http://crbug.com/170921
[email protected]b172aee2012-04-10 17:05:265910void WebContentsImpl::NotifyDisconnected() {
[email protected]420ae012009-04-24 05:16:325911 if (!notify_disconnection_)
5912 return;
5913
5914 notify_disconnection_ = false;
[email protected]8ff00d72012-10-23 19:12:215915 NotificationService::current()->Notify(
5916 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
5917 Source<WebContents>(this),
5918 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:325919}
5920
[email protected]cbb1ef592013-06-05 19:49:465921void WebContentsImpl::NotifyNavigationEntryCommitted(
5922 const LoadCommittedDetails& load_details) {
Alexander Timin90c20c32020-08-12 15:28:325923 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5924 observer->NavigationEntryCommitted(load_details);
5925 });
[email protected]cbb1ef592013-06-05 19:49:465926}
5927
Sam McNally5c087a32017-08-25 01:46:145928void WebContentsImpl::NotifyNavigationEntryChanged(
5929 const EntryChangedDetails& change_details) {
Alexander Timin90c20c32020-08-12 15:28:325930 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5931 observer->NavigationEntryChanged(change_details);
5932 });
Sam McNally5c087a32017-08-25 01:46:145933}
5934
5935void WebContentsImpl::NotifyNavigationListPruned(
5936 const PrunedDetails& pruned_details) {
Alexander Timin90c20c32020-08-12 15:28:325937 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5938 observer->NavigationListPruned(pruned_details);
5939 });
Sam McNally5c087a32017-08-25 01:46:145940}
5941
Christian Dullweber1af31e62018-02-22 11:49:485942void WebContentsImpl::NotifyNavigationEntriesDeleted() {
Alexander Timin90c20c32020-08-12 15:28:325943 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5944 observer->NavigationEntriesDeleted();
5945 });
Christian Dullweber1af31e62018-02-22 11:49:485946}
5947
rockotf62002a2016-09-15 00:08:595948void WebContentsImpl::OnAssociatedInterfaceRequest(
5949 RenderFrameHost* render_frame_host,
5950 const std::string& interface_name,
5951 mojo::ScopedInterfaceEndpointHandle handle) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:255952 auto it = receiver_sets_.find(interface_name);
5953 if (it != receiver_sets_.end())
5954 it->second->OnReceiverForFrame(render_frame_host, std::move(handle));
rockotf62002a2016-09-15 00:08:595955}
5956
Ben Goodger9e24929e2017-07-21 03:13:405957void WebContentsImpl::OnInterfaceRequest(
5958 RenderFrameHost* render_frame_host,
5959 const std::string& interface_name,
5960 mojo::ScopedMessagePipeHandle* interface_pipe) {
Alexander Timin90c20c32020-08-12 15:28:325961 for (auto& observer : observers_.observer_list()) {
Ben Goodger9e24929e2017-07-21 03:13:405962 observer.OnInterfaceRequestFromFrame(render_frame_host, interface_name,
5963 interface_pipe);
5964 if (!interface_pipe->is_valid())
5965 break;
5966 }
5967}
5968
Varun Khaneja5da94302019-06-25 04:48:105969void WebContentsImpl::OnDidBlockNavigation(
5970 const GURL& blocked_url,
5971 const GURL& initiator_url,
Abhijeet Kandalkarde7348e2020-01-13 06:06:545972 blink::mojom::NavigationBlockedReason reason) {
Nicolas Dossou-gbetebcab2472017-09-09 12:28:405973 if (delegate_)
Varun Khaneja5da94302019-06-25 04:48:105974 delegate_->OnDidBlockNavigation(this, blocked_url, initiator_url, reason);
Nicolas Dossou-gbetebcab2472017-09-09 12:28:405975}
5976
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:415977const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() {
[email protected]c31a84802014-04-03 15:55:495978 return GetLastCommittedURL();
5979}
5980
[email protected]b849847b2013-12-10 21:57:585981void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:325982 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5983 observer->RenderFrameCreated(render_frame_host);
5984 });
dmazzonif8a31042016-12-03 00:52:135985 UpdateAccessibilityModeOnFrame(render_frame_host);
clamy91b7abf2016-03-24 15:17:455986
Becca Hughesd11d6502018-07-31 17:01:285987 if (display_cutout_host_impl_)
5988 display_cutout_host_impl_->RenderFrameCreated(render_frame_host);
5989
clamy91b7abf2016-03-24 15:17:455990 if (!render_frame_host->IsRenderFrameLive() || render_frame_host->GetParent())
5991 return;
5992
5993 NavigationEntry* entry = controller_.GetPendingEntry();
5994 if (entry && entry->IsViewSourceMode()) {
5995 // Put the renderer in view source mode.
Dave Tapuska3c05e1c2019-11-27 18:34:185996 static_cast<RenderFrameHostImpl*>(render_frame_host)
5997 ->GetAssociatedLocalFrame()
5998 ->EnableViewSourceMode();
clamy91b7abf2016-03-24 15:17:455999 }
[email protected]b849847b2013-12-10 21:57:586000}
6001
6002void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
yilkal172da772019-11-06 22:49:076003 if (IsBeingDestroyed() && !render_frame_host->GetParent() &&
6004 first_navigation_completed_ &&
Hajime Hoshibbc509c2020-04-06 08:55:086005 !render_frame_host->IsInBackForwardCache()) {
yilkal796e89e2019-10-02 23:58:286006 // Main frame has been deleted because WebContents is being destroyed.
Rakina Zata Amni74627df2019-10-15 02:03:176007 // Note that we aren't recording this here when the main frame is in the
6008 // back-forward cache because that means we've actually already navigated
6009 // away from it (and we got to this point because the WebContents is
yilkal172da772019-11-06 22:49:076010 // deleted), which means |max_loaded_frame_count_| is already overwritten.
6011 // The |max_loaded_frame_count_| value will instead be recorded from within
6012 // |WebContentsImpl::DidFinishNavigation()|.
6013 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:286014 }
6015
Alexander Timin90c20c32020-08-12 15:28:326016 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6017 observer->RenderFrameDeleted(render_frame_host);
6018 });
zqzhang7b6f4f02016-12-07 22:10:226019#if BUILDFLAG(ENABLE_PLUGINS)
6020 pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
6021#endif
Becca Hughesfd5d8f892018-06-14 18:23:366022
Becca Hughesd11d6502018-07-31 17:01:286023 if (display_cutout_host_impl_)
6024 display_cutout_host_impl_->RenderFrameDeleted(render_frame_host);
6025
Becca Hughesfd5d8f892018-06-14 18:23:366026 // Remove any fullscreen state that the frame has stored.
6027 FullscreenStateChanged(render_frame_host, false /* is_fullscreen */);
[email protected]b849847b2013-12-10 21:57:586028}
6029
[email protected]a09d53ce2014-01-31 00:46:426030void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
6031 const ContextMenuParams& params) {
avie9fd8722017-04-10 16:17:586032 // If a renderer fires off a second command to show a context menu before the
6033 // first context menu is closed, just ignore it. https://crbug.com/707534
ekaramadf6750aa2017-06-06 18:29:426034 if (showing_context_menu_)
avie9fd8722017-04-10 16:17:586035 return;
6036
[email protected]077e704b2014-05-23 19:24:106037 ContextMenuParams context_menu_params(params);
[email protected]a09d53ce2014-01-31 00:46:426038 // Allow WebContentsDelegates to handle the context menu operation first.
Joel Klinghed0ea22ea2019-02-20 22:04:226039 if (delegate_ &&
6040 delegate_->HandleContextMenu(render_frame_host, context_menu_params))
[email protected]a09d53ce2014-01-31 00:46:426041 return;
6042
[email protected]077e704b2014-05-23 19:24:106043 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
6044 context_menu_params);
[email protected]a09d53ce2014-01-31 00:46:426045}
6046
Avi Drissman4891b852018-09-25 18:12:586047namespace {
6048// Normalizes the line endings: \r\n -> \n, lone \r -> \n.
6049base::string16 NormalizeLineBreaks(const base::string16& source) {
6050 static const base::NoDestructor<base::string16> kReturnNewline(
6051 base::ASCIIToUTF16("\r\n"));
6052 static const base::NoDestructor<base::string16> kReturn(
6053 base::ASCIIToUTF16("\r"));
6054 static const base::NoDestructor<base::string16> kNewline(
6055 base::ASCIIToUTF16("\n"));
6056
6057 std::vector<base::StringPiece16> pieces;
6058
6059 for (const auto& rn_line : base::SplitStringPieceUsingSubstr(
6060 source, *kReturnNewline, base::KEEP_WHITESPACE,
6061 base::SPLIT_WANT_ALL)) {
6062 auto r_lines = base::SplitStringPieceUsingSubstr(
6063 rn_line, *kReturn, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
6064 std::move(std::begin(r_lines), std::end(r_lines),
6065 std::back_inserter(pieces));
6066 }
6067
6068 return base::JoinString(pieces, *kNewline);
6069}
6070} // namespace
6071
Dave Tapuskacdf545cc2020-01-23 18:38:526072void WebContentsImpl::RunJavaScriptDialog(
6073 RenderFrameHost* render_frame_host,
6074 const base::string16& message,
6075 const base::string16& default_prompt,
6076 JavaScriptDialogType dialog_type,
6077 JavaScriptDialogCallback response_callback) {
Avi Drissman2ccbb402018-03-20 21:11:366078 // Ensure that if showing a dialog is the first thing that a page does, that
6079 // the contents of the previous page aren't shown behind it. This is required
6080 // because showing a dialog freezes the renderer, so no frames will be coming
6081 // from it. https://crbug.com/823353
6082 auto* render_widget_host_impl =
6083 static_cast<RenderFrameHostImpl*>(render_frame_host)
6084 ->GetRenderWidgetHost();
6085 if (render_widget_host_impl)
6086 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6087
avi0720b02e2017-06-13 03:22:136088 // Running a dialog causes an exit to webpage-initiated fullscreen.
6089 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456090 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136091
Avi Drissman1a55a9d62020-03-10 18:56:456092 auto callback =
6093 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6094 render_frame_host->GetProcess()->GetID(),
6095 render_frame_host->GetRoutingID(),
6096 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166097
Pavel Feldman3c1842b2017-08-02 05:00:166098 std::vector<protocol::PageHandler*> page_handlers =
6099 protocol::PageHandler::EnabledForWebContents(this);
6100
Pavel Feldmanfab3cb62017-10-05 01:02:016101 if (delegate_)
6102 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6103
Charlie Reis96077362019-07-04 00:34:046104 // While a JS message dialog is showing, defer commits in this WebContents.
6105 javascript_dialog_navigation_deferrer_ =
6106 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6107
Carlos IL07f282f2020-05-15 22:58:296108 // Suppress JavaScript dialogs when requested.
6109 bool should_suppress = delegate_ && delegate_->ShouldSuppressDialogs(this);
Pavel Feldman1c587bc52018-04-04 21:16:056110 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6111 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016112 bool suppress_this_message = should_suppress || !has_handlers;
6113
6114 if (suppress_this_message) {
Avi Drissmane04d3992017-10-05 15:11:366115 std::move(callback).Run(true, false, base::string16());
Pavel Feldman3c1842b2017-08-02 05:00:166116 return;
6117 }
6118
6119 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366120 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166121
6122 is_showing_javascript_dialog_ = true;
6123
Avi Drissman4891b852018-09-25 18:12:586124 base::string16 normalized_message = NormalizeLineBreaks(message);
6125
Pavel Feldman3c1842b2017-08-02 05:00:166126 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366127 handler->DidRunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586128 render_frame_host->GetLastCommittedURL(), normalized_message,
6129 default_prompt, dialog_type, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366130 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166131 }
6132
6133 if (dialog_manager_) {
[email protected]87de04b02014-04-08 22:14:496134 dialog_manager_->RunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586135 this, render_frame_host, dialog_type, normalized_message,
6136 default_prompt,
Avi Drissmane04d3992017-10-05 15:11:366137 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false),
6138 &suppress_this_message);
[email protected]87de04b02014-04-08 22:14:496139 }
6140
6141 if (suppress_this_message) {
6142 // If we are suppressing messages, just reply as if the user immediately
6143 // pressed "Cancel", passing true to |dialog_was_suppressed|.
Avi Drissmane04d3992017-10-05 15:11:366144 wrapper->Run(true, false, base::string16());
[email protected]87de04b02014-04-08 22:14:496145 }
[email protected]87de04b02014-04-08 22:14:496146}
6147
6148void WebContentsImpl::RunBeforeUnloadConfirm(
[email protected]39f2f9252014-05-03 00:54:016149 RenderFrameHost* render_frame_host,
[email protected]87de04b02014-04-08 22:14:496150 bool is_reload,
Dave Tapuskacdf545cc2020-01-23 18:38:526151 JavaScriptDialogCallback response_callback) {
Avi Drissman2ccbb402018-03-20 21:11:366152 // Ensure that if showing a dialog is the first thing that a page does, that
6153 // the contents of the previous page aren't shown behind it. This is required
6154 // because showing a dialog freezes the renderer, so no frames will be coming
6155 // from it. https://crbug.com/823353
6156 auto* render_widget_host_impl =
6157 static_cast<RenderFrameHostImpl*>(render_frame_host)
6158 ->GetRenderWidgetHost();
6159 if (render_widget_host_impl)
6160 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6161
avi0720b02e2017-06-13 03:22:136162 // Running a dialog causes an exit to webpage-initiated fullscreen.
6163 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456164 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136165
[email protected]39f2f9252014-05-03 00:54:016166 RenderFrameHostImpl* rfhi =
6167 static_cast<RenderFrameHostImpl*>(render_frame_host);
[email protected]87de04b02014-04-08 22:14:496168 if (delegate_)
6169 delegate_->WillRunBeforeUnloadConfirm();
6170
Avi Drissman1a55a9d62020-03-10 18:56:456171 auto callback =
6172 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6173 render_frame_host->GetProcess()->GetID(),
6174 render_frame_host->GetRoutingID(),
6175 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166176
Pavel Feldman3c1842b2017-08-02 05:00:166177 std::vector<protocol::PageHandler*> page_handlers =
6178 protocol::PageHandler::EnabledForWebContents(this);
6179
Pavel Feldmanfab3cb62017-10-05 01:02:016180 if (delegate_)
6181 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6182
Charlie Reis96077362019-07-04 00:34:046183 // While a JS beforeunload dialog is showing, defer commits in this
6184 // WebContents.
6185 javascript_dialog_navigation_deferrer_ =
6186 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6187
Sreeja Kamishettyf352e302020-06-10 13:21:246188 bool should_suppress = !rfhi->IsCurrent() ||
Tarun Bansalc209b742019-12-24 06:53:256189 (delegate_ && delegate_->ShouldSuppressDialogs(this));
Pavel Feldman1c587bc52018-04-04 21:16:056190 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6191 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016192 if (should_suppress || !has_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366193 std::move(callback).Run(false, true, base::string16());
[email protected]87de04b02014-04-08 22:14:496194 return;
6195 }
6196
6197 is_showing_before_unload_dialog_ = true;
Pavel Feldman3c1842b2017-08-02 05:00:166198
6199 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366200 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166201
6202 GURL frame_url = rfhi->GetLastCommittedURL();
6203 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366204 handler->DidRunBeforeUnloadConfirm(
Pavel Feldman1c587bc52018-04-04 21:16:056205 frame_url, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366206 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166207 }
6208
6209 if (dialog_manager_) {
Avi Drissmane04d3992017-10-05 15:11:366210 dialog_manager_->RunBeforeUnloadDialog(
Avi Drissmanff9ed752017-11-28 21:18:126211 this, render_frame_host, is_reload,
Avi Drissmane04d3992017-10-05 15:11:366212 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166213 }
[email protected]87de04b02014-04-08 22:14:496214}
6215
Kent Tamurac260c9a2018-09-14 09:10:566216void WebContentsImpl::RunFileChooser(
6217 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:016218 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamurac260c9a2018-09-14 09:10:566219 const blink::mojom::FileChooserParams& params) {
Avi Drissman3d41e7712018-08-27 21:18:086220 // Any explicit focusing of another window while this WebContents is in
6221 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456222 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6223 listener->SetFullscreenBlock(std::move(fullscreen_block));
Avi Drissman3d41e7712018-08-27 21:18:086224
naskoada75b22016-06-11 16:09:466225 if (delegate_)
Kent Tamura512a27e2018-10-04 00:49:326226 delegate_->RunFileChooser(render_frame_host, std::move(listener), params);
6227 else
6228 listener->FileSelectionCanceled();
naskoada75b22016-06-11 16:09:466229}
6230
[email protected]a86c0e962013-12-17 17:10:396231WebContents* WebContentsImpl::GetAsWebContents() {
6232 return this;
6233}
6234
mcnee336ea2c2017-05-23 22:50:596235#if !defined(OS_ANDROID)
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416236double WebContentsImpl::GetPendingPageZoomLevel() {
wjmaclean64951902016-04-29 20:59:126237 NavigationEntry* pending_entry = GetController().GetPendingEntry();
6238 if (!pending_entry)
6239 return HostZoomMap::GetZoomLevel(this);
6240
6241 GURL url = pending_entry->GetURL();
6242 return HostZoomMap::GetForWebContents(this)->GetZoomLevelForHostAndScheme(
6243 url.scheme(), net::GetHostOrSpecFromURL(url));
6244}
mcnee336ea2c2017-05-23 22:50:596245#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:126246
qinmin72e8bd02016-10-21 19:35:376247bool WebContentsImpl::HideDownloadUI() const {
6248 return is_overlay_content_;
6249}
6250
mlamouri5cd9ae82017-02-18 11:05:096251bool WebContentsImpl::HasPersistentVideo() const {
6252 return has_persistent_video_;
6253}
6254
Ian Vollick5d5c37f2019-06-19 22:50:576255bool WebContentsImpl::IsSpatialNavigationDisabled() const {
6256 return is_spatial_navigation_disabled_;
6257}
6258
Albert J. Wong65fe64d2019-09-20 02:48:146259RenderFrameHostImpl* WebContentsImpl::GetPendingMainFrame() {
clamy610c63b32017-12-22 15:05:186260 return GetRenderManager()->speculative_frame_host();
Alex Moshchuk27caae82017-09-11 23:11:186261}
6262
mlamourie52c1b542017-02-23 14:57:506263bool WebContentsImpl::HasActiveEffectivelyFullscreenVideo() const {
6264 return media_web_contents_observer_->HasActiveEffectivelyFullscreenVideo();
6265}
6266
François Beaufortad6c5232018-02-26 11:00:446267bool WebContentsImpl::IsPictureInPictureAllowedForFullscreenVideo() const {
6268 return media_web_contents_observer_
6269 ->IsPictureInPictureAllowedForFullscreenVideo();
6270}
6271
ekaramada110f642016-12-21 19:47:286272bool WebContentsImpl::IsFocusedElementEditable() {
6273 RenderFrameHostImpl* frame = GetFocusedFrame();
6274 return frame && frame->has_focused_editable_element();
6275}
6276
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416277bool WebContentsImpl::IsShowingContextMenu() {
ekaramadf6750aa2017-06-06 18:29:426278 return showing_context_menu_;
6279}
6280
6281void WebContentsImpl::SetShowingContextMenu(bool showing) {
6282 DCHECK_NE(showing_context_menu_, showing);
6283 showing_context_menu_ = showing;
6284
6285 if (auto* view = GetRenderWidgetHostView()) {
6286 // Notify the main frame's RWHV to run the platform-specific code, if any.
6287 static_cast<RenderWidgetHostViewBase*>(view)->SetShowingContextMenu(
6288 showing);
6289 }
6290}
6291
ekaramada110f642016-12-21 19:47:286292void WebContentsImpl::ClearFocusedElement() {
6293 if (auto* frame = GetFocusedFrame())
6294 frame->ClearFocusedElement();
6295}
6296
danakj77eb7e82020-01-09 19:38:466297bool WebContentsImpl::IsNeverComposited() {
[email protected]7912e822014-04-16 02:37:036298 if (!delegate_)
6299 return false;
danakj77eb7e82020-01-09 19:38:466300 return delegate_->IsNeverComposited(this);
[email protected]7912e822014-04-16 02:37:036301}
6302
[email protected]5a3bdf52012-05-24 15:12:576303RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
6304 return render_view_host_delegate_view_;
[email protected]420ae012009-04-24 05:16:326305}
6306
Peter Marshall2dc74e92020-07-29 20:02:306307blink::mojom::RendererPreferences WebContentsImpl::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:466308 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:516309}
6310
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166311RenderFrameHostImpl* WebContentsImpl::GetOuterWebContentsFrame() {
6312 if (GetOuterDelegateFrameTreeNodeId() ==
6313 FrameTreeNode::kFrameTreeNodeInvalidId) {
6314 return nullptr;
6315 }
6316
6317 FrameTreeNode* outer_node =
6318 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6319 // The outer node should be in the outer WebContents.
6320 DCHECK_EQ(outer_node->frame_tree(), GetOuterWebContents()->GetFrameTree());
Alexander Timin381e7e182020-04-28 19:04:036321 return outer_node->parent();
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166322}
6323
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416324WebContentsImpl* WebContentsImpl::GetOuterWebContents() {
Lucas Furukawa Gadani105de1e812018-05-31 19:38:396325 return node_.outer_web_contents();
avallee0206f782016-07-28 18:55:336326}
6327
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166328std::vector<WebContents*> WebContentsImpl::GetInnerWebContents() {
6329 std::vector<WebContents*> all_inner_contents;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166330 const auto& inner_contents = node_.GetInnerWebContents();
6331 all_inner_contents.insert(all_inner_contents.end(), inner_contents.begin(),
6332 inner_contents.end());
6333 return all_inner_contents;
6334}
6335
Jeremy Roman7e70bf92020-01-07 23:23:586336WebContentsImpl* WebContentsImpl::GetResponsibleWebContents() {
6337 // Iteratively ask delegates which other contents is responsible until a fixed
6338 // point is found.
6339 WebContentsImpl* contents = this;
6340 while (WebContentsDelegate* delegate = contents->GetDelegate()) {
6341 auto* responsible_contents = static_cast<WebContentsImpl*>(
6342 delegate->GetResponsibleWebContents(contents));
6343 if (responsible_contents == contents)
6344 break;
6345 contents = responsible_contents;
6346 }
6347 return contents;
6348}
6349
avallee0206f782016-07-28 18:55:336350WebContentsImpl* WebContentsImpl::GetFocusedWebContents() {
lfg601233692017-03-06 22:45:446351 return GetOutermostWebContents()->node_.focused_web_contents();
avallee0206f782016-07-28 18:55:336352}
6353
avallee9993fca2016-11-17 06:16:506354bool WebContentsImpl::ContainsOrIsFocusedWebContents() {
6355 for (WebContentsImpl* focused_contents = GetFocusedWebContents();
6356 focused_contents;
6357 focused_contents = focused_contents->GetOuterWebContents()) {
6358 if (focused_contents == this)
6359 return true;
6360 }
6361
6362 return false;
6363}
6364
W. James MacLean9437b5bf2019-12-06 17:33:446365void WebContentsImpl::RemoveBrowserPluginEmbedder() {
6366 browser_plugin_embedder_.reset();
6367}
6368
avallee0206f782016-07-28 18:55:336369WebContentsImpl* WebContentsImpl::GetOutermostWebContents() {
6370 WebContentsImpl* root = this;
6371 while (root->GetOuterWebContents())
6372 root = root->GetOuterWebContents();
6373 return root;
6374}
6375
avalleed68cdd12017-06-21 22:07:276376void WebContentsImpl::FocusOuterAttachmentFrameChain() {
6377 WebContentsImpl* outer_contents = GetOuterWebContents();
6378 if (!outer_contents)
6379 return;
6380
6381 FrameTreeNode* outer_node =
6382 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6383 outer_contents->frame_tree_.SetFocusedFrame(outer_node, nullptr);
6384
6385 // For a browser initiated focus change, let embedding renderer know of the
6386 // change. Otherwise, if the currently focused element is just across a
6387 // process boundary in focus order, it will not be possible to move across
6388 // that boundary. This is because the target element will already be focused
6389 // (that renderer was not notified) and drop the event.
6390 if (GetRenderManager()->GetProxyToOuterDelegate())
6391 GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
6392
6393 outer_contents->FocusOuterAttachmentFrameChain();
6394}
6395
Sean Toppingbbc4a2bd2019-01-30 02:16:146396void WebContentsImpl::InnerWebContentsCreated(WebContents* inner_web_contents) {
Alexander Timin90c20c32020-08-12 15:28:326397 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6398 observer->InnerWebContentsCreated(inner_web_contents);
6399 });
Sean Toppingbbc4a2bd2019-01-30 02:16:146400}
6401
Jeremy Roman03ce13ce2020-05-29 22:16:576402void WebContentsImpl::InnerWebContentsAttached(
6403 WebContents* inner_web_contents) {
6404 if (inner_web_contents->IsCurrentlyAudible())
6405 OnAudioStateChanged();
6406}
6407
6408void WebContentsImpl::InnerWebContentsDetached(
6409 WebContents* inner_web_contents) {
6410 if (!is_being_destroyed_)
6411 OnAudioStateChanged();
6412}
6413
[email protected]b172aee2012-04-10 17:05:266414void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
[email protected]86f98a22013-03-20 14:35:006415 if (delegate_)
[email protected]e85165c642014-06-10 14:34:316416 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]a6b73c62013-02-11 23:05:086417
[email protected]8ff00d72012-10-23 19:12:216418 NotificationService::current()->Notify(
6419 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
6420 Source<WebContents>(this),
6421 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:326422
Alexander Timin90c20c32020-08-12 15:28:326423 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6424 observer->RenderViewCreated(render_view_host);
6425 });
Joel Einbinder848001c2017-09-19 21:39:316426 if (delegate_)
6427 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]420ae012009-04-24 05:16:326428}
6429
[email protected]b172aee2012-04-10 17:05:266430void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
[email protected]151a63d2011-12-20 22:32:526431 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:326432 // Don't notify the world, since this came from a renderer in the
6433 // background.
6434 return;
6435 }
6436
dmazzoni62111452017-04-28 23:46:556437 RenderWidgetHostViewBase* rwhv =
6438 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
6439 if (rwhv)
6440 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
6441
[email protected]da7a7182013-09-06 08:11:116442 notify_disconnection_ = true;
[email protected]da7a7182013-09-06 08:11:116443
[email protected]be1f56ab2011-12-22 06:55:316444 bool was_crashed = IsCrashed();
[email protected]443b80e2010-12-14 00:42:236445 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
[email protected]9d8a4642009-07-29 17:25:306446
6447 // Restore the focus to the tab (otherwise the focus will be on the top
6448 // window).
[email protected]484ae5912010-09-29 19:16:146449 if (was_crashed && !FocusLocationBarByDefault() &&
6450 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
[email protected]f3615f02013-02-26 06:09:066451 view_->Focus();
[email protected]484ae5912010-09-29 19:16:146452 }
[email protected]32ded2212011-11-10 18:51:436453
Alexander Timin90c20c32020-08-12 15:28:326454 observers_.ForEachObserver(
6455 [&](WebContentsObserver* observer) { observer->RenderViewReady(); });
Jinsuk Kim895b2c52018-07-03 06:49:166456 view_->RenderViewReady();
[email protected]420ae012009-04-24 05:16:326457}
6458
[email protected]ec6a7eb2013-04-22 17:34:226459void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
6460 base::TerminationStatus status,
6461 int error_code) {
[email protected]151a63d2011-12-20 22:32:526462 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:326463 // The pending page's RenderViewHost is gone.
6464 return;
6465 }
6466
[email protected]2fcdcc32014-03-05 02:14:076467 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
6468 // renderer may not have made a clean exit.
Avi Drissman97aef042020-06-30 21:04:486469 if (IsFullscreen())
bokanece34a82016-01-28 19:49:466470 ExitFullscreenMode(false);
[email protected]2fcdcc32014-03-05 02:14:076471
Jennifer Apacibleb4b972a2018-06-07 04:41:026472 // Ensure any video in Picture-in-Picture is exited in the |delegate_| since
6473 // a crashed renderer may not have made a clean exit.
6474 if (HasPictureInPictureVideo())
6475 ExitPictureInPicture();
6476
[email protected]698191dc2014-02-25 01:06:136477 // Cancel any visible dialogs so they are not left dangling over the sad tab.
creis89a0f782015-05-27 16:13:176478 CancelActiveAndPendingDialogs();
[email protected]698191dc2014-02-25 01:06:136479
dalecurtis3d1e1302017-02-20 22:33:256480 audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());
6481
[email protected]960b0372014-05-19 18:01:006482 // Reset the loading progress. TODO(avi): What does it mean to have a
6483 // "renderer crash" when there is more than one renderer process serving a
6484 // webpage? Once this function is called at a more granular frame level, we
6485 // probably will need to more granularly reset the state here.
6486 ResetLoadProgressState();
clamy44e84ce2016-02-22 15:38:256487 NotifyDisconnected();
6488 SetIsCrashed(status, error_code);
[email protected]960b0372014-05-19 18:01:006489
Alexander Timin90c20c32020-08-12 15:28:326490 TRACE_EVENT0("content", "Dispatching WebContentsObserver::RenderProcessGone");
6491 // Some observers might destroy WebContents in RenderViewTerminated.
6492 base::WeakPtr<WebContentsImpl> weak_ptr = weak_factory_.GetWeakPtr();
6493 auto crashed_status = GetCrashedStatus();
6494 for (auto& observer : observers_.observer_list()) {
6495 observer.RenderProcessGone(crashed_status);
6496 if (!weak_ptr)
6497 return;
6498 }
6499
6500 // |this| might have been deleted. Do not add code here.
[email protected]420ae012009-04-24 05:16:326501}
6502
[email protected]b172aee2012-04-10 17:05:266503void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Alexander Timin90c20c32020-08-12 15:28:326504 observers_.ForEachObserver(
6505 [&](WebContentsObserver* observer) { observer->RenderViewDeleted(rvh); });
[email protected]2e4633c2009-07-09 16:58:066506}
6507
sky8b00392d2015-01-10 00:30:286508void WebContentsImpl::UpdateTargetURL(RenderViewHost* render_view_host,
6509 const GURL& url) {
6510 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
Lukasz Anforowiczfd707142018-02-07 19:46:136511 // If we're in flash fullscreen (i.e. Pepper plugin fullscreen) only update
6512 // the url if it's from the fullscreen renderer.
sky8b00392d2015-01-10 00:30:286513 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
avif9ab5d942015-10-15 14:05:446514 if (fs && fs->GetRenderWidgetHost() != render_view_host->GetWidget())
sky8b00392d2015-01-10 00:30:286515 return;
6516 }
Lukasz Anforowiczfd707142018-02-07 19:46:136517
6518 // In case of racey updates from multiple RenderViewHosts, the last URL should
6519 // be shown - see also some discussion in https://crbug.com/807776.
6520 if (!url.is_valid() && render_view_host != view_that_set_last_target_url_)
6521 return;
6522 view_that_set_last_target_url_ = url.is_valid() ? render_view_host : nullptr;
6523
[email protected]6934a702011-12-20 00:04:516524 if (delegate_)
avi450ce00e2014-09-24 01:58:526525 delegate_->UpdateTargetURL(this, url);
[email protected]420ae012009-04-24 05:16:326526}
6527
Lukasz Anforowiczfd707142018-02-07 19:46:136528void WebContentsImpl::ClearTargetURL() {
6529 view_that_set_last_target_url_ = nullptr;
6530 if (delegate_)
6531 delegate_->UpdateTargetURL(this, GURL());
6532}
6533
[email protected]b172aee2012-04-10 17:05:266534void WebContentsImpl::Close(RenderViewHost* rvh) {
Avi Drissman7c57be72020-07-29 20:09:466535#if defined(OS_MAC)
[email protected]07707302009-11-06 00:50:296536 // The UI may be in an event-tracking loop, such as between the
6537 // mouse-down and mouse-up in text selection or a button click.
6538 // Defer the close until after tracking is complete, so that we
6539 // don't free objects out from under the UI.
[email protected]07707302009-11-06 00:50:296540 // TODO(shess): This could get more fine-grained. For instance,
6541 // closing a tab in another window while selecting text in the
6542 // current window's Omnibox should be just fine.
Christopher Cameron9ae31e0d2019-03-01 20:01:196543 if (view_->CloseTabAfterEventTrackingIfNeeded())
[email protected]07707302009-11-06 00:50:296544 return;
[email protected]60780f412013-02-25 16:34:106545#endif
[email protected]07707302009-11-06 00:50:296546
[email protected]420ae012009-04-24 05:16:326547 // Ignore this if it comes from a RenderViewHost that we aren't showing.
[email protected]151a63d2011-12-20 22:32:526548 if (delegate_ && rvh == GetRenderViewHost())
[email protected]6934a702011-12-20 00:04:516549 delegate_->CloseContents(this);
[email protected]420ae012009-04-24 05:16:326550}
6551
Avi Drissman014dec72018-06-07 02:34:016552void WebContentsImpl::RequestSetBounds(const gfx::Rect& new_bounds) {
Mike Wassermandabad612020-08-13 04:26:276553 if (!delegate_)
6554 return;
6555
6556 // Members of |new_bounds| may be 0 to indicate uninitialized values for newly
6557 // opened windows, even if the |GetContainerBounds()| inner rect is correct.
6558 // TODO(crbug.com/897300): Plumb values as specified; fallback on outer rect.
6559 auto bounds = new_bounds;
6560 if (bounds.IsEmpty())
6561 bounds.set_size(GetContainerBounds().size());
6562
6563 // Only requests from the main frame, not subframes, should reach this code.
Mike Wassermanb6bc0152020-08-25 22:46:206564 int64_t display_id = AdjustRequestedWindowBounds(&bounds, GetMainFrame());
6565
6566 // Drop fullscreen when placing a WebContents to prohibit deceptive behavior.
6567 // Only drop fullscreen on the specific destination display, which is known.
6568 // This supports sites using cross-screen window placement capabilities to
6569 // retain fullscreen and place a window on another screen.
6570 ForSecurityDropFullscreen(display_id).RunAndReset();
6571
Mike Wassermandabad612020-08-13 04:26:276572 delegate_->SetContentsBounds(this, bounds);
[email protected]420ae012009-04-24 05:16:326573}
6574
fdegansa696e5112015-04-17 01:57:596575void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
[email protected]e3b10d12014-03-28 16:06:096576 bool to_different_document) {
Evan Stadec3b26022017-07-14 19:50:246577 LoadingStateChanged(frame_tree_node->IsMainFrame() && to_different_document,
Carlos IL07f282f2020-05-15 22:58:296578 nullptr);
dmazzonibf8cec42015-02-08 08:28:086579
Xiyuan Xia2a66b112018-12-06 15:52:166580 // Reset the focus state from DidStartNavigation to false if a new load starts
6581 // afterward, in case loading logic triggers a FocusLocationBarByDefault call.
6582 should_focus_location_bar_by_default_ = false;
Ian Prestcdd843d2020-01-28 18:59:586583
6584 // Notify accessibility that the user is navigating away from the
6585 // current document.
6586 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
6587 // https://crbug.com/981271.
6588 BrowserAccessibilityManager* manager =
6589 frame_tree_node->current_frame_host()->browser_accessibility_manager();
6590 if (manager)
6591 manager->UserIsNavigatingAway();
[email protected]420ae012009-04-24 05:16:326592}
6593
fdegansc73eec22015-03-19 14:47:546594void WebContentsImpl::DidStopLoading() {
dcheng59716272016-04-09 05:19:086595 std::unique_ptr<LoadNotificationDetails> details;
[email protected]420ae012009-04-24 05:16:326596
[email protected]9595fd82013-04-19 21:28:496597 // Use the last committed entry rather than the active one, in case a
6598 // pending entry has been created.
6599 NavigationEntry* entry = controller_.GetLastCommittedEntry();
6600
[email protected]420ae012009-04-24 05:16:326601 // An entry may not exist for a stop when loading an initial blank page or
6602 // if an iframe injected by script into a blank page finishes loading.
6603 if (entry) {
[email protected]420ae012009-04-24 05:16:326604 details.reset(new LoadNotificationDetails(
[email protected]36fc0392011-12-25 03:59:516605 entry->GetVirtualURL(),
[email protected]420ae012009-04-24 05:16:326606 &controller_,
6607 controller_.GetCurrentEntryIndex()));
6608 }
6609
Carlos IL07f282f2020-05-15 22:58:296610 LoadingStateChanged(true, details.get());
[email protected]420ae012009-04-24 05:16:326611}
6612
fdegansa696e5112015-04-17 01:57:596613void WebContentsImpl::DidChangeLoadProgress() {
Nate Chapin22ea6592019-03-05 22:29:026614 if (is_being_destroyed_)
6615 return;
fdegansa696e5112015-04-17 01:57:596616 double load_progress = frame_tree_.load_progress();
6617
6618 // The delegate is notified immediately for the first and last updates. Also,
6619 // since the message loop may be pretty busy when a page is loaded, it might
6620 // not execute a posted task in a timely manner so the progress report is sent
6621 // immediately if enough time has passed.
6622 base::TimeDelta min_delay =
6623 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
6624 bool delay_elapsed = loading_last_progress_update_.is_null() ||
6625 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
6626
6627 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
6628 // If there is a pending task to send progress, it is now obsolete.
6629 loading_weak_factory_.InvalidateWeakPtrs();
6630
6631 // Notify the load progress change.
6632 SendChangeLoadProgress();
6633
6634 // Clean-up the states if needed.
6635 if (load_progress == 1.0)
6636 ResetLoadProgressState();
6637 return;
6638 }
6639
6640 if (loading_weak_factory_.HasWeakPtrs())
6641 return;
6642
skyostil95082a62015-06-05 19:53:076643 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzike2aca992017-09-05 08:50:546644 FROM_HERE,
6645 base::BindOnce(&WebContentsImpl::SendChangeLoadProgress,
6646 loading_weak_factory_.GetWeakPtr()),
fdegansa696e5112015-04-17 01:57:596647 min_delay);
6648}
6649
avid6d88b912017-01-13 00:16:006650std::vector<std::unique_ptr<NavigationThrottle>>
6651WebContentsImpl::CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:356652 NavigationHandle* navigation_handle) {
Charlie Reis96077362019-07-04 00:34:046653 auto throttles = GetContentClient()->browser()->CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:356654 navigation_handle);
Charlie Reis96077362019-07-04 00:34:046655
6656 // This is not a normal place to be adding a throttle. However, in the case
6657 // javascript dialogs, related logic is present in the web_contents/ layer,
6658 // and the purpose of the throttle is to ensure that navigation commits are
6659 // deferred for the entire WebContents. Most throttles are either added by
6660 // the embederrer outside of content/, or are per-frame and added by
6661 // NavigationThrottleRunner.
6662 std::unique_ptr<content::NavigationThrottle> dialog_throttle =
6663 JavaScriptDialogNavigationThrottle::MaybeCreateThrottleFor(
6664 navigation_handle);
6665 if (dialog_throttle)
6666 throttles.push_back(std::move(dialog_throttle));
6667
6668 return throttles;
clamycbf524d42016-09-27 12:48:356669}
6670
clamy1e5574e2016-09-29 16:48:446671std::unique_ptr<NavigationUIData> WebContentsImpl::GetNavigationUIData(
6672 NavigationHandle* navigation_handle) {
clamy1e5574e2016-09-29 16:48:446673 return GetContentClient()->browser()->GetNavigationUIData(navigation_handle);
6674}
6675
W. James MacLean1c40862c2020-04-27 21:05:576676void WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation(
W. James MacLeanb70fab82020-05-01 18:51:146677 const url::Origin& origin,
6678 NavigationRequest* navigation_request_to_exclude) {
W. James MacLean1c40862c2020-04-27 21:05:576679 // Note: This function can be made static if we ever need call it without
6680 // a WebContentsImpl instance, in which case we can use a wrapper to
6681 // implement the override from NavigatorDelegate.
6682 for (WebContentsImpl* web_contents : GetAllWebContents()) {
6683 web_contents->controller_.RegisterExistingOriginToPreventOptInIsolation(
6684 origin);
W. James MacLeanb70fab82020-05-01 18:51:146685 // Walk the frame tree to pick up any frames without FrameNavigationEntries.
6686 // * Some frames won't have FrameNavigationEntries (Issues 524208, 608402).
6687 // * Some pending navigations won't have NavigationEntries.
6688 web_contents->GetFrameTree()->RegisterExistingOriginToPreventOptInIsolation(
6689 origin, navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:576690 }
6691}
6692
pdr15f5b5b2017-06-20 00:58:006693void WebContentsImpl::DidCancelLoading() {
6694 controller_.DiscardNonCommittedEntries();
6695
6696 // Update the URL display.
6697 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
6698}
6699
[email protected]59167c22013-06-03 18:07:326700void WebContentsImpl::DidAccessInitialDocument() {
[email protected]b4c84012014-04-28 19:51:106701 has_accessed_initial_document_ = true;
6702
[email protected]d1371bf8e2014-04-19 03:26:246703 // We may have left a failed browser-initiated navigation in the address bar
6704 // to let the user edit it and try again. Clear it now that content might
6705 // show up underneath it.
6706 if (!IsLoading() && controller_.GetPendingEntry())
avi45a72532015-04-07 21:01:456707 controller_.DiscardPendingEntry(false);
[email protected]d1371bf8e2014-04-19 03:26:246708
[email protected]59167c22013-06-03 18:07:326709 // Update the URL display.
thestigc4cac8f2014-09-04 21:17:506710 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
[email protected]59167c22013-06-03 18:07:326711}
6712
alexmosbe2f4c32015-03-10 02:30:236713void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
6714 const std::string& name) {
Alexander Timin90c20c32020-08-12 15:28:326715 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6716 observer->FrameNameChanged(render_frame_host, name);
6717 });
alexmosbe2f4c32015-03-10 02:30:236718}
6719
John Delaneyedd8d6c2019-01-25 00:23:576720void WebContentsImpl::DidReceiveFirstUserActivation(
6721 RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:326722 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6723 observer->FrameReceivedFirstUserActivation(render_frame_host);
6724 });
John Delaneyedd8d6c2019-01-25 00:23:576725}
6726
John Delaney0146a742019-01-25 19:25:286727void WebContentsImpl::DidChangeDisplayState(RenderFrameHost* render_frame_host,
6728 bool is_display_none) {
Alexander Timin90c20c32020-08-12 15:28:326729 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6730 observer->FrameDisplayStateChanged(render_frame_host, is_display_none);
6731 });
John Delaney0146a742019-01-25 19:25:286732}
6733
6734void WebContentsImpl::FrameSizeChanged(RenderFrameHost* render_frame_host,
6735 const gfx::Size& frame_size) {
Alexander Timin90c20c32020-08-12 15:28:326736 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6737 observer->FrameSizeChanged(render_frame_host, frame_size);
6738 });
John Delaney0146a742019-01-25 19:25:286739}
6740
[email protected]39f2f9252014-05-03 00:54:016741void WebContentsImpl::DocumentOnLoadCompleted(
[email protected]50279492014-05-05 23:24:296742 RenderFrameHost* render_frame_host) {
falken52a56e32016-12-08 05:02:406743 ShowInsecureLocalhostWarningIfNeeded();
6744
Alexander Timindd0fa0c52019-11-06 13:03:376745 GetRenderViewHost()->DocumentOnLoadCompletedInMainFrame();
6746
Alexander Timin90c20c32020-08-12 15:28:326747 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6748 observer->DocumentOnLoadCompletedInMainFrame();
6749 });
[email protected]6578fef2013-10-14 02:35:096750
6751 // TODO(avi): Remove. http://crbug.com/170921
[email protected]8ff00d72012-10-23 19:12:216752 NotificationService::current()->Notify(
6753 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
6754 Source<WebContents>(this),
[email protected]50279492014-05-05 23:24:296755 NotificationService::NoDetails());
[email protected]25497492010-09-11 15:15:086756}
6757
creis8eb8ef22015-11-04 22:51:386758void WebContentsImpl::UpdateStateForFrame(RenderFrameHost* render_frame_host,
6759 const PageState& page_state) {
creis8eb8ef22015-11-04 22:51:386760 // The state update affects the last NavigationEntry associated with the given
6761 // |render_frame_host|. This may not be the last committed NavigationEntry (as
6762 // in the case of an UpdateState from a frame being swapped out). We track
6763 // which entry this is in the RenderFrameHost's nav_entry_id.
6764 RenderFrameHostImpl* rfhi =
6765 static_cast<RenderFrameHostImpl*>(render_frame_host);
6766 NavigationEntryImpl* entry =
6767 controller_.GetEntryWithUniqueID(rfhi->nav_entry_id());
6768 if (!entry)
6769 return;
6770
6771 FrameNavigationEntry* frame_entry =
6772 entry->GetFrameEntry(rfhi->frame_tree_node());
6773 if (!frame_entry)
6774 return;
6775
creisd06a9422015-11-11 03:08:456776 // The SiteInstance might not match if we do a cross-process navigation with
6777 // replacement (e.g., auto-subframe), in which case the swap out of the old
6778 // RenderFrameHost runs in the background after the old FrameNavigationEntry
6779 // has already been replaced and destroyed.
6780 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
6781 return;
6782
creis8eb8ef22015-11-04 22:51:386783 if (page_state == frame_entry->page_state())
6784 return; // Nothing to update.
6785
creis0cade2e2017-02-28 06:37:476786 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
nasko34634672016-07-29 18:46:066787
6788 // The document_sequence_number and item_sequence_number recorded in the
6789 // FrameNavigationEntry should not differ from the one coming with the update,
6790 // since it must come from the same document. Do not update it if a difference
6791 // is detected, as this indicates that |frame_entry| is not the correct one.
6792 ExplodedPageState exploded_state;
6793 if (!DecodePageState(page_state.ToEncodedData(), &exploded_state))
6794 return;
6795
6796 if (exploded_state.top.document_sequence_number !=
6797 frame_entry->document_sequence_number() ||
6798 exploded_state.top.item_sequence_number !=
6799 frame_entry->item_sequence_number()) {
6800 return;
6801 }
6802
nasko04a322f25a2016-09-01 00:00:346803 frame_entry->SetPageState(page_state);
creis8eb8ef22015-11-04 22:51:386804 controller_.NotifyEntryChanged(entry);
6805}
6806
[email protected]ef3adfc2014-05-11 00:04:546807void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
[email protected]ef3adfc2014-05-11 00:04:546808 const base::string16& title,
6809 base::i18n::TextDirection title_direction) {
[email protected]ef3adfc2014-05-11 00:04:546810 // Try to find the navigation entry, which might not be the current one.
avi286019ce2015-07-29 01:26:586811 // For example, it might be from a recently swapped out RFH.
avi1edc8552016-10-13 21:37:166812 NavigationEntryImpl* entry = controller_.GetEntryWithUniqueID(
creisad8c31a2016-05-24 17:07:046813 static_cast<RenderFrameHostImpl*>(render_frame_host)->nav_entry_id());
[email protected]ef3adfc2014-05-11 00:04:546814
6815 // We can handle title updates when we don't have an entry in
6816 // UpdateTitleForEntry, but only if the update is from the current RVH.
6817 // TODO(avi): Change to make decisions based on the RenderFrameHost.
avi286019ce2015-07-29 01:26:586818 if (!entry && render_frame_host != GetMainFrame())
[email protected]ef3adfc2014-05-11 00:04:546819 return;
6820
6821 // TODO(evan): make use of title_direction.
6822 // http://code.google.com/p/chromium/issues/detail?id=27094
afakhry6f0c1ec22016-07-14 13:55:136823 UpdateTitleForEntry(entry, title);
[email protected]ef3adfc2014-05-11 00:04:546824}
6825
alexmose7da5a12015-04-09 02:22:166826bool WebContentsImpl::ShouldRouteMessageEvent(
6827 RenderFrameHost* target_rfh,
6828 SiteInstance* source_site_instance) const {
6829 // Allow the message if this WebContents is dedicated to a browser plugin
6830 // guest.
[email protected]0eba810b2012-10-18 03:19:366831 // Note: This check means that an embedder could theoretically receive a
6832 // postMessage from anyone (not just its own guests). However, this is
6833 // probably not a risk for apps since other pages won't have references
6834 // to App windows.
alexmose7da5a12015-04-09 02:22:166835 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
6836}
[email protected]f546640b2012-05-15 00:03:496837
alexmos58729042015-06-18 23:20:006838void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
alexmose7da5a12015-04-09 02:22:166839 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
6840 WebContents::FromRenderFrameHost(source_rfh));
[email protected]f546640b2012-05-15 00:03:496841
alexmose7da5a12015-04-09 02:22:166842 if (source_web_contents) {
lazyboy6ec48b2a2015-06-29 15:18:146843 // If this message is going to outer WebContents from inner WebContents,
6844 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
6845 // already created a RenderFrameProxyHost for that purpose.
6846 if (GetBrowserPluginEmbedder() &&
W. James MacLean2539adb32019-12-13 00:40:446847 source_web_contents->browser_plugin_guest_) {
lazyboy6ec48b2a2015-06-29 15:18:146848 return;
W. James MacLean2539adb32019-12-13 00:40:446849 }
lazyboy6ec48b2a2015-06-29 15:18:146850
lfg812874d2016-02-09 22:26:136851 if (this != source_web_contents && GetBrowserPluginGuest()) {
naskob3041b98a42016-03-12 04:43:066852 // We create a RenderFrameProxyHost for the embedder in the guest's render
6853 // process but we intentionally do not expose the embedder's opener chain
6854 // to it.
6855 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
6856 GetSiteInstance());
[email protected]f546640b2012-05-15 00:03:496857 } else {
alexmos58729042015-06-18 23:20:006858 RenderFrameHostImpl* source_rfhi =
6859 static_cast<RenderFrameHostImpl*>(source_rfh);
6860 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
alexmos90325cf2015-09-02 17:18:396861 GetSiteInstance(), nullptr);
[email protected]f546640b2012-05-15 00:03:496862 }
6863 }
[email protected]f546640b2012-05-15 00:03:496864}
6865
avallee9993fca2016-11-17 06:16:506866void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
Adithya Srinivasan11af2c52019-12-16 22:52:556867 DCHECK(!portal());
avallee9993fca2016-11-17 06:16:506868 // Only change focus if we are not currently focused.
6869 WebContentsImpl* old_contents = GetFocusedWebContents();
6870 if (old_contents == this)
6871 return;
6872
paulmeyerfeafc2d2017-04-25 21:46:406873 GetOutermostWebContents()->node_.SetFocusedWebContents(this);
6874
avallee9993fca2016-11-17 06:16:506875 // Send a page level blur to the old contents so that it displays inactive UI
6876 // and focus this contents to activate it.
6877 if (old_contents)
6878 old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
avalleec2ff1ef2017-01-21 00:12:306879
6880 // Make sure the outer web contents knows our frame is focused. Otherwise, the
6881 // outer renderer could have the element before or after the frame element
6882 // focused which would return early without actually advancing focus.
avalleed68cdd12017-06-21 22:07:276883 FocusOuterAttachmentFrameChain();
avalleec2ff1ef2017-01-21 00:12:306884
Carlos ILd51e7702020-05-07 18:51:396885 GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
avallee9993fca2016-11-17 06:16:506886}
6887
avallee0206f782016-07-28 18:55:336888void WebContentsImpl::SetFocusedFrame(FrameTreeNode* node,
6889 SiteInstance* source) {
Adithya Srinivasan11af2c52019-12-16 22:52:556890 DCHECK(!portal());
avallee0206f782016-07-28 18:55:336891 frame_tree_.SetFocusedFrame(node, source);
avalleed68cdd12017-06-21 22:07:276892
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576893 if (auto* inner_contents = node_.GetInnerWebContentsInFrame(node)) {
6894 // |this| is an outer WebContents and |node| represents an inner
6895 // WebContents. Transfer the focus to the inner contents if |this| is
6896 // focused.
6897 if (GetFocusedWebContents() == this)
6898 inner_contents->SetAsFocusedWebContentsIfNecessary();
6899 } else if (node_.OuterContentsFrameTreeNode() &&
6900 node_.OuterContentsFrameTreeNode()
6901 ->current_frame_host()
6902 ->GetSiteInstance() == source) {
6903 // |this| is an inner WebContents, |node| is its main FrameTreeNode and
6904 // the outer WebContents FrameTreeNode is at |source|'s SiteInstance.
6905 // Transfer the focus to the inner WebContents if the outer WebContents is
6906 // focused. This branch is used when an inner WebContents is focused through
Lowell Mannersa9530382019-08-01 09:46:576907 // its RenderFrameProxyHost (via FrameFocused mojo call, used to
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576908 // implement the window.focus() API).
6909 if (GetFocusedWebContents() == GetOuterWebContents())
6910 SetAsFocusedWebContentsIfNecessary();
6911 } else if (!GetOuterWebContents()) {
6912 // This is an outermost WebContents.
6913 SetAsFocusedWebContentsIfNecessary();
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576914 }
avalleed68cdd12017-06-21 22:07:276915}
6916
Avi Drissman36f801f2018-02-01 20:06:046917void WebContentsImpl::DidCallFocus() {
6918 // Any explicit focusing of another window while this WebContents is in
6919 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456920 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6921 // The other contents is independent of this contents, so release the
6922 // fullscreen block.
6923 fullscreen_block.RunAndReset();
Avi Drissman36f801f2018-02-01 20:06:046924}
6925
avalleed68cdd12017-06-21 22:07:276926RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() {
6927 WebContentsImpl* contents = this;
6928 FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame();
6929
6930 // If there is no focused frame in the outer WebContents, we need to return
6931 // null.
6932 if (!focused_node)
6933 return nullptr;
6934
6935 // If the focused frame is embedding an inner WebContents, we must descend
6936 // into that contents. If the current WebContents does not have a focused
6937 // frame, return the main frame of this contents instead of the focused empty
6938 // frame embedding this contents.
6939 while (true) {
6940 contents = contents->node_.GetInnerWebContentsInFrame(focused_node);
6941 if (!contents)
6942 return focused_node->current_frame_host();
6943
6944 focused_node = contents->frame_tree_.GetFocusedFrame();
6945 if (!focused_node)
6946 return contents->GetMainFrame();
6947 }
avallee0206f782016-07-28 18:55:336948}
6949
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:576950void WebContentsImpl::OnAdvanceFocus(RenderFrameHostImpl* source_rfh) {
6951 // When a RenderFrame needs to advance focus to a RenderFrameProxy (by hitting
6952 // TAB), the RenderFrameProxy sends an IPC to RenderFrameProxyHost. When this
6953 // RenderFrameProxyHost represents an inner WebContents, the outer WebContents
6954 // needs to focus the inner WebContents.
6955 if (GetOuterWebContents() &&
6956 GetOuterWebContents() == source_rfh->delegate()->GetAsWebContents() &&
6957 GetFocusedWebContents() == GetOuterWebContents()) {
6958 SetAsFocusedWebContentsIfNecessary();
6959 }
6960}
6961
ekaramada110f642016-12-21 19:47:286962void WebContentsImpl::OnFocusedElementChangedInFrame(
6963 RenderFrameHostImpl* frame,
Emily Stark023dbacc2020-08-27 22:31:406964 const gfx::Rect& bounds_in_root_view,
6965 blink::mojom::FocusType focus_type) {
ekaramada110f642016-12-21 19:47:286966 RenderWidgetHostViewBase* root_view =
6967 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
6968 if (!root_view || !frame->GetView())
6969 return;
Katie De0131372020-07-09 23:03:106970 // Convert to screen coordinates from window coordinates by adding the
6971 // window's origin.
ekaramada110f642016-12-21 19:47:286972 gfx::Point origin = bounds_in_root_view.origin();
6973 origin += root_view->GetViewBounds().OffsetFromOrigin();
6974 gfx::Rect bounds_in_screen(origin, bounds_in_root_view.size());
6975
6976 root_view->FocusedNodeChanged(frame->has_focused_editable_element(),
6977 bounds_in_screen);
6978
6979 FocusedNodeDetails details = {frame->has_focused_editable_element(),
Emily Stark023dbacc2020-08-27 22:31:406980 bounds_in_screen, focus_type};
ekaramada110f642016-12-21 19:47:286981
6982 // TODO(ekaramad): We should replace this with an observer notification
6983 // (https://crbug.com/675975).
6984 NotificationService::current()->Notify(
6985 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
6986 Source<RenderViewHost>(GetRenderViewHost()),
6987 Details<FocusedNodeDetails>(&details));
Jeff Fisher709b4c52019-07-29 20:07:346988
Alexander Timin90c20c32020-08-12 15:28:326989 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6990 observer->OnFocusChangedInPage(&details);
6991 });
ekaramada110f642016-12-21 19:47:286992}
6993
Lowell Manners1de5242e2019-04-25 10:18:466994bool WebContentsImpl::DidAddMessageToConsole(
6995 blink::mojom::ConsoleMessageLevel log_level,
6996 const base::string16& message,
6997 int32_t line_no,
6998 const base::string16& source_id) {
Alexander Timin90c20c32020-08-12 15:28:326999 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7000 observer->OnDidAddMessageToConsole(log_level, message, line_no, source_id);
7001 });
[email protected]a796f202012-05-30 14:14:257002 if (!delegate_)
7003 return false;
Lowell Manners1de5242e2019-04-25 10:18:467004 return delegate_->DidAddMessageToConsole(this, log_level, message, line_no,
avia90ae4e2016-11-11 20:49:337005 source_id);
[email protected]a796f202012-05-30 14:14:257006}
7007
Daniel Cheng90196c82018-04-25 21:49:147008void WebContentsImpl::DidReceiveInputEvent(
dominickn9c7ceaa32016-02-27 01:52:537009 RenderWidgetHostImpl* render_widget_host,
Emily Starkc7bd40c42020-07-21 19:12:557010 const blink::WebInputEvent& event) {
7011 if (!IsUserInteractionInputType(event.GetType()))
Daniel Cheng90196c82018-04-25 21:49:147012 return;
7013
kenrb19221852016-04-29 17:21:407014 // Ignore unless the widget is currently in the frame tree.
7015 if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
avic3aa8422015-11-09 20:57:227016 return;
7017
Emily Starkc7bd40c42020-07-21 19:12:557018 if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin)
Daniel Cheng90196c82018-04-25 21:49:147019 last_interactive_input_event_time_ = ui::EventTimeForNow();
dominickn9c7ceaa32016-02-27 01:52:537020
Alexander Timin90c20c32020-08-12 15:28:327021 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7022 observer->DidGetUserInteraction(event);
7023 });
dominickn2dd142dd2015-10-29 05:30:507024}
7025
Avi Drissman738ea192018-08-29 20:24:167026bool WebContentsImpl::ShouldIgnoreInputEvents() {
7027 WebContentsImpl* web_contents = this;
7028 while (web_contents) {
7029 if (web_contents->ignore_input_events_)
7030 return true;
7031 web_contents = web_contents->GetOuterWebContents();
7032 }
7033
7034 return false;
7035}
7036
avallee9993fca2016-11-17 06:16:507037void WebContentsImpl::FocusOwningWebContents(
7038 RenderWidgetHostImpl* render_widget_host) {
Alex Moshchukc4f0a722019-11-19 22:41:287039 RenderWidgetHostImpl* main_frame_widget_host =
7040 GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:507041 RenderWidgetHostImpl* focused_widget =
Alex Moshchukc4f0a722019-11-19 22:41:287042 GetFocusedRenderWidgetHost(main_frame_widget_host);
avallee9993fca2016-11-17 06:16:507043
7044 if (focused_widget != render_widget_host &&
avallee8e881592016-11-19 00:39:307045 (!focused_widget ||
7046 focused_widget->delegate() != render_widget_host->delegate())) {
avallee9993fca2016-11-17 06:16:507047 SetAsFocusedWebContentsIfNecessary();
7048 }
7049}
7050
[email protected]b172aee2012-04-10 17:05:267051void WebContentsImpl::OnIgnoredUIEvent() {
[email protected]31145092011-09-30 01:49:447052 // Notify observers.
Alexander Timin90c20c32020-08-12 15:28:327053 observers_.ForEachObserver(
7054 [&](WebContentsObserver* observer) { observer->DidGetIgnoredUIEvent(); });
[email protected]fa1cf0b82010-01-15 21:49:447055}
7056
avic3aa8422015-11-09 20:57:227057void WebContentsImpl::RendererUnresponsive(
Lukasz Anforowicz52b93722018-06-20 16:11:397058 RenderWidgetHostImpl* render_widget_host,
7059 base::RepeatingClosure hang_monitor_restarter) {
avic031d392017-03-03 03:09:427060 if (ShouldIgnoreUnresponsiveRenderer())
[email protected]e5fc1632011-08-08 07:51:537061 return;
7062
Lukasz Anforowicz4f0593d2018-09-21 18:33:547063 // Do not report hangs (to task manager, to hang renderer dialog, etc.) for
7064 // invisible tabs (like extension background page, background tabs). See
7065 // https://crbug.com/881812 for rationale and for choosing the visibility
7066 // (rather than process priority) as the signal here.
7067 if (GetVisibility() != Visibility::VISIBLE)
7068 return;
7069
Avi Drissman8920def2018-01-31 19:53:367070 if (!render_widget_host->renderer_initialized())
[email protected]55452902011-06-01 21:57:477071 return;
7072
Alexander Timin90c20c32020-08-12 15:28:327073 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7074 observer->OnRendererUnresponsive(render_widget_host->GetProcess());
7075 });
Dave Tapuskac6146c52017-12-20 22:48:157076 if (delegate_)
Lukasz Anforowicz52b93722018-06-20 16:11:397077 delegate_->RendererUnresponsive(this, render_widget_host,
7078 std::move(hang_monitor_restarter));
[email protected]420ae012009-04-24 05:16:327079}
7080
avic3aa8422015-11-09 20:57:227081void WebContentsImpl::RendererResponsive(
7082 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin90c20c32020-08-12 15:28:327083 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7084 observer->OnRendererResponsive(render_widget_host->GetProcess());
7085 });
[email protected]6934a702011-12-20 00:04:517086 if (delegate_)
Avi Drissman1572e8c3c2018-02-02 19:06:367087 delegate_->RendererResponsive(this, render_widget_host);
[email protected]420ae012009-04-24 05:16:327088}
7089
Alex Moshchuk7b4f0652019-05-30 18:54:417090void WebContentsImpl::SubframeCrashed(
7091 blink::mojom::FrameVisibility visibility) {
7092 // If a subframe crashed on a hidden tab, mark the tab for reload to avoid
7093 // showing a sad frame to the user if they ever switch back to that tab. Do
7094 // this for subframes that are either visible in viewport or visible but
7095 // scrolled out of view, but skip subframes that are not rendered (e.g., via
7096 // "display:none"), since in that case the user wouldn't see a sad frame
7097 // anyway.
7098 bool did_mark_for_reload = false;
7099 if (IsHidden() && visibility != blink::mojom::FrameVisibility::kNotRendered &&
7100 base::FeatureList::IsEnabled(
7101 features::kReloadHiddenTabsWithCrashedSubframes)) {
7102 controller_.SetNeedsReload(
7103 NavigationControllerImpl::NeedsReloadType::kCrashedSubframe);
7104 did_mark_for_reload = true;
7105 UMA_HISTOGRAM_ENUMERATION(
7106 "Stability.ChildFrameCrash.TabMarkedForReload.Visibility", visibility);
7107 }
7108
7109 UMA_HISTOGRAM_BOOLEAN("Stability.ChildFrameCrash.TabMarkedForReload",
7110 did_mark_for_reload);
7111}
7112
[email protected]b172aee2012-04-10 17:05:267113void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
[email protected]feaded02012-09-25 19:12:557114 bool proceed, const base::TimeTicks& proceed_time,
[email protected]420ae012009-04-24 05:16:327115 bool* proceed_to_fire_unload) {
Alexander Timin90c20c32020-08-12 15:28:327116 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7117 observer->BeforeUnloadFired(proceed, proceed_time);
7118 });
[email protected]6934a702011-12-20 00:04:517119 if (delegate_)
7120 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
[email protected]e80af492013-06-24 21:52:097121 // Note: |this| might be deleted at this point.
[email protected]420ae012009-04-24 05:16:327122}
7123
[email protected]58d5cfe2013-07-10 02:40:527124void WebContentsImpl::RenderProcessGoneFromRenderManager(
[email protected]3a3d47472010-07-15 21:03:547125 RenderViewHost* render_view_host) {
[email protected]443b80e2010-12-14 00:42:237126 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
[email protected]ec6a7eb2013-04-22 17:34:227127 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
[email protected]3a3d47472010-07-15 21:03:547128}
7129
[email protected]af905902013-10-01 21:38:517130void WebContentsImpl::CancelModalDialogsForRenderManager() {
7131 // We need to cancel modal dialogs when doing a process swap, since the load
avi2460c762015-04-17 15:21:547132 // deferrer would prevent us from swapping out. We also clear the state
7133 // because this is a cross-process navigation, which means that it's a new
7134 // site that should not have to pay for the sins of its predecessor.
creis89a0f782015-05-27 16:13:177135 //
Lei Zhang6410ec1a2019-01-31 21:38:587136 // Note that we don't bother telling |browser_plugin_embedder_| because the
creis89a0f782015-05-27 16:13:177137 // cross-process navigation will either destroy the browser plugins or not
7138 // require their dialogs to close.
avi5d3b8692016-10-12 22:00:467139 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:537140 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:467141 }
[email protected]af905902013-10-01 21:38:517142}
7143
danakja0bce4c952020-05-12 20:40:287144void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_frame,
7145 RenderFrameHost* new_frame,
[email protected]02d7b6e2014-06-24 21:01:507146 bool is_main_frame) {
7147 if (is_main_frame) {
danakja0bce4c952020-05-12 20:40:287148 // The |new_frame| and its various compadres are already swapped into place
7149 // for the WebContentsImpl when this method is called.
7150 DCHECK(GetMainFrame() == new_frame);
7151 DCHECK(GetRenderViewHost() == new_frame->GetRenderViewHost());
7152 DCHECK(GetRenderWidgetHostView() == new_frame->GetView());
7153
Fergal Daly6767b2e2020-02-04 03:15:167154 RenderViewHost* old_rvh =
danakja0bce4c952020-05-12 20:40:287155 old_frame ? old_frame->GetRenderViewHost() : nullptr;
7156 RenderViewHost* new_rvh = new_frame->GetRenderViewHost();
Fergal Daly6767b2e2020-02-04 03:15:167157 // |old_rvh| and |new_rvh| might be equal when navigating from a crashed
7158 // RenderFrameHost to a new same-site one. With RenderDocument, this will
7159 // happen for every same-site navigation.
7160 if (old_rvh != new_rvh)
7161 NotifyViewSwapped(old_rvh, new_rvh);
[email protected]a6b73c62013-02-11 23:05:087162
[email protected]02d7b6e2014-06-24 21:01:507163 // Make sure the visible RVH reflects the new delegate's preferences.
7164 if (delegate_)
7165 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]d56a49e2013-02-23 00:47:397166
danakja0bce4c952020-05-12 20:40:287167 auto* rwhv = static_cast<RenderWidgetHostViewBase*>(new_frame->GetView());
7168 if (rwhv) {
7169 rwhv->SetMainFrameAXTreeID(new_frame->GetAXTreeID());
7170
7171 // The RenderWidgetHostView for the speculative RenderFrameHost is not
7172 // resized with the current RenderFrameHost while a navigation is
7173 // pending. So when we swap in the main frame, we need to update the
7174 // RenderWidgetHostView's size.
7175 //
7176 // Historically, this was done to fix b/1079768 for interstitials.
7177 rwhv->SetSize(GetSizeForMainFrame());
7178 }
[email protected]02d7b6e2014-06-24 21:01:507179 }
7180
danakja0bce4c952020-05-12 20:40:287181 NotifyFrameSwapped(old_frame, new_frame, is_main_frame);
[email protected]3a3d47472010-07-15 21:03:547182}
7183
naskof5940b9f2015-03-02 23:04:057184void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
danakja0bce4c952020-05-12 20:40:287185 RenderFrameHost* old_frame,
7186 RenderFrameHost* new_frame) {
7187 NotifyViewSwapped(old_frame ? old_frame->GetRenderViewHost() : nullptr,
7188 new_frame->GetRenderViewHost());
naskof5940b9f2015-03-02 23:04:057189}
7190
[email protected]b172aee2012-04-10 17:05:267191NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
[email protected]d1198fd2012-08-13 22:50:197192 return GetController();
[email protected]3a3d47472010-07-15 21:03:547193}
7194
dcheng59716272016-04-09 05:19:087195std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost(
Miyoung Shin072d4052020-07-13 07:52:447196 RenderFrameHost* frame_host,
Denis Kuznetsov [CET]2c6f0159f2020-05-18 14:18:167197 const GURL& url) {
Miyoung Shin072d4052020-07-13 07:52:447198 return CreateWebUI(frame_host, url);
[email protected]420ae012009-04-24 05:16:327199}
7200
lfgbede6392015-09-11 21:54:067201void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
7202 RenderViewHost* render_view_host) {
lfgc740d4b22016-04-15 16:45:337203 RenderWidgetHostViewBase* rwh_view =
W. James MacLean13d834d2019-12-04 16:06:457204 view_->CreateViewForWidget(render_view_host->GetWidget());
danakja0bce4c952020-05-12 20:40:287205 rwh_view->SetSize(GetSizeForMainFrame());
lfgbede6392015-09-11 21:54:067206}
7207
7208bool WebContentsImpl::CreateRenderViewForRenderManager(
7209 RenderViewHost* render_view_host,
Antonio Gomesb3dd5fc2020-05-25 22:53:277210 const base::Optional<base::UnguessableToken>& opener_frame_token,
Daniel Chengabfdb002020-06-04 06:02:307211 int proxy_routing_id) {
lfgbede6392015-09-11 21:54:067212 TRACE_EVENT0("browser,navigation",
7213 "WebContentsImpl::CreateRenderViewForRenderManager");
7214
piman00cf9402017-04-03 17:09:207215 if (proxy_routing_id == MSG_ROUTING_NONE)
lfg9431efd2016-12-14 14:45:267216 CreateRenderWidgetHostViewForRenderManager(render_view_host);
lfg9431efd2016-12-14 14:45:267217
piman00cf9402017-04-03 17:09:207218 if (!static_cast<RenderViewHostImpl*>(render_view_host)
Daniel Chengabfdb002020-06-04 06:02:307219 ->CreateRenderView(opener_frame_token, proxy_routing_id,
Antonio Gomesb3dd5fc2020-05-25 22:53:277220 created_with_opener_)) {
[email protected]a4127722011-04-27 23:13:527221 return false;
[email protected]14392a52012-05-02 20:28:447222 }
W. James MacLean62198672019-06-04 16:46:107223 // Set the TextAutosizer state from the main frame's renderer on the new view,
7224 // but only if it's not for the main frame. Main frame renderers should create
7225 // this state themselves from up-to-date values, so we shouldn't override it
7226 // with the cached values.
7227 if (!render_view_host->GetMainFrame()) {
Antonio Gomesda7e03d2020-08-05 15:03:087228 auto* proxy_host = GetRenderManager()->GetRenderFrameProxyHost(
7229 render_view_host->GetSiteInstance());
7230 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
7231 text_autosizer_page_info_.Clone());
W. James MacLean62198672019-06-04 16:46:107232 }
[email protected]a4127722011-04-27 23:13:527233
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:147234 if (proxy_routing_id == MSG_ROUTING_NONE && node_.outer_web_contents())
7235 ReattachToOuterWebContentsFrame();
7236
avi2b177592014-12-10 02:08:027237 SetHistoryOffsetAndLengthForView(render_view_host,
7238 controller_.GetLastCommittedEntryIndex(),
7239 controller_.GetEntryCount());
7240
Avi Drissman7c57be72020-07-29 20:09:467241#if defined(OS_POSIX) && !defined(OS_MAC) && !defined(OS_ANDROID)
[email protected]f8233cc2011-05-31 20:24:507242 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
7243 // linux. See crbug.com/83941.
avif9ab5d942015-10-15 14:05:447244 RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
[email protected]245f7d52011-11-28 15:36:447245 if (rwh_view) {
7246 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:167247 render_widget_host->SynchronizeVisualProperties();
[email protected]245f7d52011-11-28 15:36:447248 }
[email protected]f8233cc2011-05-31 20:24:507249#endif
7250
[email protected]420ae012009-04-24 05:16:327251 return true;
7252}
7253
[email protected]82307f6b2014-08-07 03:30:127254bool WebContentsImpl::CreateRenderFrameForRenderManager(
7255 RenderFrameHost* render_frame_host,
arthursonzogni1efc7b962019-03-14 09:36:337256 int previous_routing_id,
Antonio Gomes9d150542020-05-25 18:32:117257 const base::Optional<base::UnguessableToken>& opener_frame_token,
japhete6adf142014-10-31 00:01:497258 int parent_routing_id,
alexmosa181efc2015-09-03 00:39:047259 int previous_sibling_routing_id) {
naskob8744d22014-08-28 17:07:437260 TRACE_EVENT0("browser,navigation",
7261 "WebContentsImpl::CreateRenderFrameForRenderManager");
[email protected]82307f6b2014-08-07 03:30:127262
7263 RenderFrameHostImpl* rfh =
7264 static_cast<RenderFrameHostImpl*>(render_frame_host);
Antonio Gomes9d150542020-05-25 18:32:117265 if (!rfh->CreateRenderFrame(previous_routing_id, opener_frame_token,
7266 parent_routing_id, previous_sibling_routing_id)) {
[email protected]82307f6b2014-08-07 03:30:127267 return false;
Antonio Gomes9d150542020-05-25 18:32:117268 }
[email protected]82307f6b2014-08-07 03:30:127269
7270 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
7271 // RenderFrameHost will have to be associated with the appropriate
7272 // RenderWidgetHostView or a new one should be created here.
7273
7274 return true;
7275}
7276
mfomitchev2b8b066a2016-01-28 19:23:157277#if defined(OS_ANDROID)
[email protected]fc2b46b2014-05-03 16:33:457278
[email protected]155c7f22013-12-09 17:07:187279base::android::ScopedJavaLocalRef<jobject>
7280WebContentsImpl::GetJavaWebContents() {
mostynb042582e2015-03-16 22:13:407281 DCHECK_CURRENTLY_ON(BrowserThread::UI);
[email protected]0e813a52014-08-13 10:34:567282 return GetWebContentsAndroid()->GetJavaObject();
7283}
[email protected]155c7f22013-12-09 17:07:187284
[email protected]0e813a52014-08-13 10:34:567285WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
Kevin McNee576bb5d82019-05-29 16:47:517286 if (!web_contents_android_) {
7287 web_contents_android_ = std::make_unique<WebContentsAndroid>(this);
[email protected]155c7f22013-12-09 17:07:187288 }
Kevin McNee576bb5d82019-05-29 16:47:517289 return web_contents_android_.get();
7290}
7291
7292void WebContentsImpl::ClearWebContentsAndroid() {
7293 DCHECK_CURRENTLY_ON(BrowserThread::UI);
7294 web_contents_android_.reset();
[email protected]155c7f22013-12-09 17:07:187295}
7296
paulmeyerc0b762b2016-04-13 11:55:177297void WebContentsImpl::ActivateNearestFindResult(float x,
7298 float y) {
7299 GetOrCreateFindRequestManager()->ActivateNearestFindResult(x, y);
7300}
7301
7302void WebContentsImpl::RequestFindMatchRects(int current_version) {
7303 GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
7304}
7305
rockot400ea35b2016-10-15 19:15:327306service_manager::InterfaceProvider* WebContentsImpl::GetJavaInterfaces() {
sammcf5f1b0f2016-09-20 23:05:117307 if (!java_interfaces_) {
Gyuyoung Kim6c9ce9022019-11-26 05:40:087308 mojo::PendingRemote<service_manager::mojom::InterfaceProvider> provider;
7309 BindInterfaceRegistryForWebContents(
7310 provider.InitWithNewPipeAndPassReceiver(), this);
rockot400ea35b2016-10-15 19:15:327311 java_interfaces_.reset(new service_manager::InterfaceProvider);
sammcf5f1b0f2016-09-20 23:05:117312 java_interfaces_->Bind(std::move(provider));
7313 }
7314 return java_interfaces_.get();
7315}
7316
Francois Doray6c26f3342018-08-24 17:17:227317#endif
7318
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:417319bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() {
Carlos Caballero91fffb22019-10-29 15:24:307320 return GetRenderViewHost()->did_first_visually_non_empty_paint();
spqchane72c3cb2017-06-30 23:02:107321}
7322
pkotwicz75ca8ffd2016-02-16 23:10:197323void WebContentsImpl::OnDidDownloadImage(
Avi Drissmana5a52dd2018-03-27 03:39:027324 ImageDownloadCallback callback,
pkotwicz75ca8ffd2016-02-16 23:10:197325 int id,
7326 const GURL& image_url,
leon.hancbc4bc3c2016-02-26 07:08:527327 int32_t http_status_code,
leon.hanc2228532016-08-16 05:59:187328 const std::vector<SkBitmap>& images,
7329 const std::vector<gfx::Size>& original_image_sizes) {
Avi Drissmana5a52dd2018-03-27 03:39:027330 std::move(callback).Run(id, http_status_code, image_url, images,
7331 original_image_sizes);
pkotwicz75ca8ffd2016-02-16 23:10:197332}
7333
[email protected]6fba26d2014-04-29 09:38:287334void WebContentsImpl::OnDialogClosed(int render_process_id,
7335 int render_frame_id,
Dave Tapuskacdf545cc2020-01-23 18:38:527336 JavaScriptDialogCallback response_callback,
Avi Drissman1a55a9d62020-03-10 18:56:457337 base::ScopedClosureRunner fullscreen_block,
[email protected]87de04b02014-04-08 22:14:497338 bool dialog_was_suppressed,
[email protected]b172aee2012-04-10 17:05:267339 bool success,
[email protected]fcf75d42013-12-03 20:11:267340 const base::string16& user_input) {
[email protected]6fba26d2014-04-29 09:38:287341 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
7342 render_frame_id);
[email protected]87de04b02014-04-08 22:14:497343 last_dialog_suppressed_ = dialog_was_suppressed;
Avi Drissman1a55a9d62020-03-10 18:56:457344 fullscreen_block.RunAndReset();
[email protected]87de04b02014-04-08 22:14:497345
Charlie Reis96077362019-07-04 00:34:047346 javascript_dialog_navigation_deferrer_.reset();
7347
[email protected]beb440c2009-11-06 04:08:547348 if (is_showing_before_unload_dialog_ && !success) {
clamybc6f4152016-04-01 20:14:237349 // It is possible for the current RenderFrameHost to have changed in the
7350 // meantime. Do not reset the navigation state in that case.
7351 if (rfh && rfh == rfh->frame_tree_node()->current_frame_host()) {
clamy44e84ce2016-02-22 15:38:257352 rfh->frame_tree_node()->BeforeUnloadCanceled();
clamybc6f4152016-04-01 20:14:237353 controller_.DiscardNonCommittedEntries();
7354 }
[email protected]ec8e8b02013-06-19 04:57:107355
Charles Reis15d60b132017-11-03 17:43:477356 // Update the URL display either way, to avoid showing a stale URL.
7357 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7358
Alexander Timin90c20c32020-08-12 15:28:327359 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7360 observer->BeforeUnloadDialogCancelled();
7361 });
[email protected]beb440c2009-11-06 04:08:547362 }
[email protected]87de04b02014-04-08 22:14:497363
Dave Tapuskacdf545cc2020-01-23 18:38:527364 std::move(response_callback).Run(success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:167365
Dave Tapuskacdf545cc2020-01-23 18:38:527366 std::vector<protocol::PageHandler*> page_handlers =
7367 protocol::PageHandler::EnabledForWebContents(this);
7368 for (auto* handler : page_handlers)
7369 handler->DidCloseJavaScriptDialog(success, user_input);
avi1c51fb62017-02-27 20:43:037370
7371 is_showing_javascript_dialog_ = false;
7372 is_showing_before_unload_dialog_ = false;
[email protected]beb440c2009-11-06 04:08:547373}
7374
[email protected]1ac10dca2013-08-20 20:47:047375bool WebContentsImpl::IsHidden() {
Francois Doraye6161152018-03-27 22:05:377376 return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
[email protected]1ac10dca2013-08-20 20:47:047377}
7378
rob97250742015-12-10 17:45:157379int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
lfg601233692017-03-06 22:45:447380 return node_.outer_contents_frame_tree_node_id();
lazyboy6ec48b2a2015-06-29 15:18:147381}
7382
ekaramadaeb3c5c2016-11-09 03:22:357383RenderWidgetHostImpl* WebContentsImpl::GetFullscreenRenderWidgetHost() const {
7384 return RenderWidgetHostImpl::FromID(fullscreen_widget_process_id_,
7385 fullscreen_widget_routing_id_);
7386}
7387
[email protected]b0936d22013-11-28 06:47:367388RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
[email protected]fa944cb82013-11-15 17:51:217389 return frame_tree_.root()->render_manager();
7390}
7391
[email protected]f8497342013-02-05 22:15:027392BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
[email protected]7a846df2012-09-20 19:17:397393 return browser_plugin_guest_.get();
7394}
7395
Albert J. Wongc55cc64d2018-10-12 02:50:047396void WebContentsImpl::SetBrowserPluginGuest(
7397 std::unique_ptr<BrowserPluginGuest> guest) {
7398 DCHECK(!browser_plugin_guest_);
7399 DCHECK(guest);
7400 browser_plugin_guest_ = std::move(guest);
[email protected]738f57a2013-06-29 21:06:547401}
7402
Aidan Wolter52bcc12a2018-11-14 03:27:297403base::UnguessableToken WebContentsImpl::GetAudioGroupId() {
Aidan Wolter52bcc12a2018-11-14 03:27:297404 return GetAudioStreamFactory()->group_id();
7405}
7406
Miyoung Shin5709ab02020-02-19 06:50:417407const std::vector<blink::mojom::FaviconURLPtr>&
7408WebContentsImpl::GetFaviconURLs() {
Mounir Lamouri7b4a1f232019-12-23 16:32:107409 return favicon_urls_;
7410}
7411
Mugdha Lakhani0a0d7862020-07-29 09:58:457412// The Mac implementation of the next two methods is in
7413// web_contents_impl_mac.mm
Avi Drissmand4d79f72020-07-30 18:35:187414#if !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:457415
7416void WebContentsImpl::Resize(const gfx::Rect& new_bounds) {
7417#if defined(USE_AURA)
7418 aura::Window* window = GetNativeView();
7419 window->SetBounds(gfx::Rect(window->bounds().origin(), new_bounds.size()));
7420#elif defined(OS_ANDROID)
7421 content::RenderWidgetHostView* view = GetRenderWidgetHostView();
7422 if (view)
7423 view->SetBounds(new_bounds);
7424#endif
7425}
7426
7427gfx::Size WebContentsImpl::GetSize() {
7428#if defined(USE_AURA)
7429 aura::Window* window = GetNativeView();
7430 return window->bounds().size();
7431#elif defined(OS_ANDROID)
7432 ui::ViewAndroid* view_android = GetNativeView();
7433 return view_android->bounds().size();
7434#endif
7435}
7436
Avi Drissmand4d79f72020-07-30 18:35:187437#endif // !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:457438
[email protected]f8497342013-02-05 22:15:027439BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
[email protected]7a846df2012-09-20 19:17:397440 return browser_plugin_embedder_.get();
7441}
[email protected]8ff00d72012-10-23 19:12:217442
fsamuel60b42282015-03-10 03:29:147443void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
7444 if (browser_plugin_embedder_)
7445 return;
7446 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
7447}
7448
danakja0bce4c952020-05-12 20:40:287449gfx::Size WebContentsImpl::GetSizeForMainFrame() {
7450 if (delegate_) {
7451 // The delegate has a chance to specify a size independent of the UI.
7452 gfx::Size delegate_size = delegate_->GetSizeForNewRenderView(this);
7453 if (!delegate_size.IsEmpty())
7454 return delegate_size;
7455 }
7456
7457 // Device emulation, when enabled, can specify a size independent of the UI.
7458 if (!device_emulation_size_.IsEmpty())
7459 return device_emulation_size_;
7460
7461 return GetContainerBounds().size();
[email protected]dc0fd432013-08-27 15:29:217462}
7463
[email protected]ae7eeda2014-07-04 01:53:267464void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
Alexander Timin90c20c32020-08-12 15:28:327465 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7466 observer->FrameDeleted(render_frame_host);
7467 });
[email protected]9b159a52013-10-03 17:24:557468}
7469
[email protected]222f5822014-02-05 23:40:497470void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
7471 if (!delegate_)
7472 return;
7473 const gfx::Size new_size = GetPreferredSize();
7474 if (new_size != old_size)
7475 delegate_->UpdatePreferredSize(this, new_size);
7476}
7477
Miyoung Shin072d4052020-07-13 07:52:447478std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(
7479 RenderFrameHost* frame_host,
7480 const GURL& url) {
7481 std::unique_ptr<WebUIImpl> web_ui =
7482 std::make_unique<WebUIImpl>(this, frame_host);
Lei Zhangee3b63ad2018-06-06 23:25:317483 std::unique_ptr<WebUIController> controller(
avie865b1d2016-10-24 19:42:597484 WebUIControllerFactoryRegistry::GetInstance()
Lei Zhangee3b63ad2018-06-06 23:25:317485 ->CreateWebUIControllerForURL(web_ui.get(), url));
dbeama1b926a2015-08-31 23:17:517486 if (controller) {
Lei Zhangee3b63ad2018-06-06 23:25:317487 web_ui->SetController(std::move(controller));
dbeama1b926a2015-08-31 23:17:517488 return web_ui;
7489 }
7490
avie865b1d2016-10-24 19:42:597491 return nullptr;
dbeama1b926a2015-08-31 23:17:517492}
7493
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:417494FindRequestManager* WebContentsImpl::GetFindRequestManager() {
7495 for (auto* contents = this; contents;
paulmeyerfeafc2d2017-04-25 21:46:407496 contents = contents->GetOuterWebContents()) {
7497 if (contents->find_request_manager_)
7498 return contents->find_request_manager_.get();
7499 }
7500
7501 return nullptr;
7502}
7503
paulmeyerc0b762b2016-04-13 11:55:177504FindRequestManager* WebContentsImpl::GetOrCreateFindRequestManager() {
paulmeyerfeafc2d2017-04-25 21:46:407505 if (FindRequestManager* manager = GetFindRequestManager())
7506 return manager;
7507
Ehsan Karamad6beb2ea2018-11-25 18:15:137508 DCHECK(!browser_plugin_guest_ || GetOuterWebContents());
7509
paulmeyerfeafc2d2017-04-25 21:46:407510 // No existing FindRequestManager found, so one must be created.
7511 find_request_manager_.reset(new FindRequestManager(this));
7512
7513 // Concurrent find sessions must not overlap, so destroy any existing
7514 // FindRequestManagers in any inner WebContentses.
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:167515 for (WebContents* contents : GetWebContentsAndAllInner()) {
7516 auto* web_contents_impl = static_cast<WebContentsImpl*>(contents);
7517 if (web_contents_impl == this)
paulmeyerfeafc2d2017-04-25 21:46:407518 continue;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:167519 if (web_contents_impl->find_request_manager_) {
7520 web_contents_impl->find_request_manager_->StopFinding(
7521 STOP_FIND_ACTION_CLEAR_SELECTION);
7522 web_contents_impl->find_request_manager_.release();
paulmeyerfeafc2d2017-04-25 21:46:407523 }
7524 }
paulmeyerc0b762b2016-04-13 11:55:177525
7526 return find_request_manager_.get();
7527}
7528
7529void WebContentsImpl::NotifyFindReply(int request_id,
7530 int number_of_matches,
7531 const gfx::Rect& selection_rect,
7532 int active_match_ordinal,
7533 bool final_update) {
Sebastien Marchandcf97ed52017-07-24 23:50:347534 if (delegate_ && !is_being_destroyed_ &&
Lukasz Anforowicze9ae3722017-09-29 17:37:387535 !GetMainFrame()->GetProcess()->FastShutdownStarted()) {
paulmeyerc0b762b2016-04-13 11:55:177536 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
7537 active_match_ordinal, final_update);
7538 }
7539}
7540
ortuno467e5792016-06-10 04:32:397541void WebContentsImpl::IncrementBluetoothConnectedDeviceCount() {
7542 // Trying to invalidate the tab state while being destroyed could result in a
7543 // use after free.
7544 if (IsBeingDestroyed()) {
7545 return;
7546 }
7547 // Notify for UI updates if the state changes.
7548 bluetooth_connected_device_count_++;
7549 if (bluetooth_connected_device_count_ == 1) {
Francois Doray66766a572019-12-17 20:56:497550 OnIsConnectedToBluetoothDeviceChanged(true);
ortuno467e5792016-06-10 04:32:397551 }
7552}
7553
7554void WebContentsImpl::DecrementBluetoothConnectedDeviceCount() {
7555 // Trying to invalidate the tab state while being destroyed could result in a
7556 // use after free.
7557 if (IsBeingDestroyed()) {
7558 return;
7559 }
7560 // Notify for UI updates if the state changes.
Lukasz Anforowicze9ae3722017-09-29 17:37:387561 DCHECK_NE(bluetooth_connected_device_count_, 0u);
ortuno467e5792016-06-10 04:32:397562 bluetooth_connected_device_count_--;
7563 if (bluetooth_connected_device_count_ == 0) {
Francois Doray66766a572019-12-17 20:56:497564 OnIsConnectedToBluetoothDeviceChanged(false);
7565 }
7566}
7567
7568void WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged(
7569 bool is_connected_to_bluetooth_device) {
7570 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:327571 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7572 observer->OnIsConnectedToBluetoothDeviceChanged(
Francois Doray66766a572019-12-17 20:56:497573 is_connected_to_bluetooth_device);
Alexander Timin90c20c32020-08-12 15:28:327574 });
ortuno467e5792016-06-10 04:32:397575}
7576
Ovidio Henriquez76696f62020-07-08 03:06:597577void WebContentsImpl::IncrementBluetoothScanningSessionsCount() {
7578 // Trying to invalidate the tab state while being destroyed could result in a
7579 // use after free.
7580 if (IsBeingDestroyed())
7581 return;
7582
7583 // Notify for UI updates if the state changes.
7584 bluetooth_scanning_sessions_count_++;
7585 if (bluetooth_scanning_sessions_count_ == 1)
7586 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7587}
7588
7589void WebContentsImpl::DecrementBluetoothScanningSessionsCount() {
7590 // Trying to invalidate the tab state while being destroyed could result in a
7591 // use after free.
7592 if (IsBeingDestroyed())
7593 return;
7594
7595 DCHECK_NE(0u, bluetooth_scanning_sessions_count_);
7596 bluetooth_scanning_sessions_count_--;
7597 if (bluetooth_scanning_sessions_count_ == 0)
7598 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7599}
7600
Reilly Grant5e7c79b22019-04-09 17:26:207601void WebContentsImpl::IncrementSerialActiveFrameCount() {
7602 // Trying to invalidate the tab state while being destroyed could result in a
7603 // use after free.
7604 if (IsBeingDestroyed())
7605 return;
7606
7607 // Notify for UI updates if the state changes.
7608 serial_active_frame_count_++;
7609 if (serial_active_frame_count_ == 1)
7610 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7611}
7612
7613void WebContentsImpl::DecrementSerialActiveFrameCount() {
7614 // Trying to invalidate the tab state while being destroyed could result in a
7615 // use after free.
7616 if (IsBeingDestroyed())
7617 return;
7618
7619 // Notify for UI updates if the state changes.
7620 DCHECK_NE(0u, serial_active_frame_count_);
7621 serial_active_frame_count_--;
7622 if (serial_active_frame_count_ == 0)
7623 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7624}
7625
Matt Reynoldse8c6c1f2019-11-02 09:53:537626void WebContentsImpl::IncrementHidActiveFrameCount() {
7627 // Trying to invalidate the tab state while being destroyed could result in a
7628 // use after free.
7629 if (IsBeingDestroyed())
7630 return;
7631
7632 // Notify for UI updates if the active frame count transitions from zero to
7633 // non-zero.
7634 hid_active_frame_count_++;
7635 if (hid_active_frame_count_ == 1)
7636 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7637}
7638
7639void WebContentsImpl::DecrementHidActiveFrameCount() {
7640 // Trying to invalidate the tab state while being destroyed could result in a
7641 // use after free.
7642 if (IsBeingDestroyed())
7643 return;
7644
7645 // Notify for UI updates if the active frame count transitions from non-zero
7646 // to zero.
7647 DCHECK_NE(0u, hid_active_frame_count_);
7648 hid_active_frame_count_--;
7649 if (hid_active_frame_count_ == 0)
7650 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
7651}
7652
Marijn Kruisselbrink29051042019-08-06 22:56:557653void WebContentsImpl::IncrementNativeFileSystemHandleCount() {
7654 // Trying to invalidate the tab state while being destroyed could result in a
7655 // use after free.
7656 if (IsBeingDestroyed())
7657 return;
7658
7659 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
7660 // to update both the tab-level usage indicator and the usage indicator in the
7661 // omnibox.
7662 native_file_system_handle_count_++;
7663 if (native_file_system_handle_count_ == 1) {
7664 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
7665 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
7666 }
7667}
7668
7669void WebContentsImpl::DecrementNativeFileSystemHandleCount() {
7670 // Trying to invalidate the tab state while being destroyed could result in a
7671 // use after free.
7672 if (IsBeingDestroyed())
7673 return;
7674
7675 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
7676 // to update both the tab-level usage indicator and the usage indicator in the
7677 // omnibox.
7678 DCHECK_NE(0u, native_file_system_handle_count_);
7679 native_file_system_handle_count_--;
7680 if (native_file_system_handle_count_ == 0) {
7681 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
7682 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
7683 }
7684}
7685
zqzhang8ac49002017-03-16 21:51:357686void WebContentsImpl::SetHasPersistentVideo(bool has_persistent_video) {
7687 if (has_persistent_video_ == has_persistent_video)
mlamouri5cd9ae82017-02-18 11:05:097688 return;
7689
zqzhang8ac49002017-03-16 21:51:357690 has_persistent_video_ = has_persistent_video;
mlamouri5cd9ae82017-02-18 11:05:097691 NotifyPreferencesChanged();
zqzhang8ac49002017-03-16 21:51:357692 media_web_contents_observer()->RequestPersistentVideo(has_persistent_video);
mlamouri5cd9ae82017-02-18 11:05:097693}
7694
Ian Vollick5d5c37f2019-06-19 22:50:577695void WebContentsImpl::SetSpatialNavigationDisabled(bool disabled) {
7696 if (is_spatial_navigation_disabled_ == disabled)
7697 return;
7698
7699 is_spatial_navigation_disabled_ = disabled;
7700 NotifyPreferencesChanged();
7701}
7702
paulmeyerfeafc2d2017-04-25 21:46:407703void WebContentsImpl::BrowserPluginGuestWillDetach() {
7704 WebContentsImpl* outermost = GetOutermostWebContents();
7705 if (this != outermost && ContainsOrIsFocusedWebContents())
7706 outermost->SetAsFocusedWebContentsIfNecessary();
7707}
7708
Becca Hughes112832e2019-06-11 17:19:027709PictureInPictureResult WebContentsImpl::EnterPictureInPicture(
Mounir Lamouri11e9ef42018-05-22 03:10:167710 const viz::SurfaceId& surface_id,
7711 const gfx::Size& natural_size) {
François Beaufortf09e4462019-01-18 14:34:517712 return delegate_
7713 ? delegate_->EnterPictureInPicture(this, surface_id, natural_size)
Becca Hughes112832e2019-06-11 17:19:027714 : PictureInPictureResult::kNotSupported;
Mounir Lamouri11e9ef42018-05-22 03:10:167715}
7716
Mounir Lamouri6d759e12018-05-16 20:01:307717void WebContentsImpl::ExitPictureInPicture() {
7718 if (delegate_)
7719 delegate_->ExitPictureInPicture();
7720}
7721
paulmeyerc0b762b2016-04-13 11:55:177722#if defined(OS_ANDROID)
7723void WebContentsImpl::NotifyFindMatchRectsReply(
7724 int version,
7725 const std::vector<gfx::RectF>& rects,
7726 const gfx::RectF& active_rect) {
7727 if (delegate_)
7728 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
7729}
7730#endif
7731
[email protected]34ff1cfc2014-08-20 06:16:057732void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
7733 force_disable_overscroll_content_ = force_disable;
7734 if (view_)
7735 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
7736}
7737
Jianzhou Fengd8720c72018-01-18 03:06:307738bool WebContentsImpl::SetDeviceEmulationSize(const gfx::Size& new_size) {
7739 device_emulation_size_ = new_size;
7740 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
7741
7742 const gfx::Size current_size = rwhv->GetViewBounds().size();
7743 if (view_size_before_emulation_.IsEmpty())
7744 view_size_before_emulation_ = current_size;
7745
7746 if (current_size != new_size)
7747 rwhv->SetSize(new_size);
7748
7749 return current_size != new_size;
7750}
7751
7752void WebContentsImpl::ClearDeviceEmulationSize() {
7753 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
7754 // WebContentsView could get resized during emulation, which also resizes
7755 // RWHV. If it happens, assume user would like to keep using the size after
7756 // emulation.
7757 // TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
7758 // WebContentsView size changes).
Dmitry Gozmanc63707182018-03-06 00:09:397759 if (!view_size_before_emulation_.IsEmpty() && rwhv &&
7760 rwhv->GetViewBounds().size() == device_emulation_size_) {
Jianzhou Fengd8720c72018-01-18 03:06:307761 rwhv->SetSize(view_size_before_emulation_);
Dmitry Gozmanc63707182018-03-06 00:09:397762 }
Jianzhou Fengd8720c72018-01-18 03:06:307763 device_emulation_size_ = gfx::Size();
7764 view_size_before_emulation_ = gfx::Size();
7765}
7766
Max Morin5bc74f52018-05-09 07:00:217767ForwardingAudioStreamFactory* WebContentsImpl::GetAudioStreamFactory() {
7768 if (!audio_stream_factory_) {
7769 audio_stream_factory_.emplace(
7770 this,
Max Morinddebb972018-09-20 10:04:147771 // BrowserMainLoop::GetInstance() may be null in unit tests.
7772 BrowserMainLoop::GetInstance()
7773 ? static_cast<media::UserInputMonitorBase*>(
7774 BrowserMainLoop::GetInstance()->user_input_monitor())
7775 : nullptr,
Ken Rockot72964402019-12-06 10:40:517776 AudioStreamBrokerFactory::CreateImpl());
Max Morin5bc74f52018-05-09 07:00:217777 }
7778
7779 return &*audio_stream_factory_;
7780}
7781
dalecurtis88c240072015-12-09 02:11:187782void WebContentsImpl::MediaStartedPlaying(
billorr21c005d2016-11-17 03:57:047783 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:357784 const MediaPlayerId& id) {
billorr21c005d2016-11-17 03:57:047785 if (media_info.has_video)
7786 currently_playing_video_count_++;
7787
Alexander Timin90c20c32020-08-12 15:28:327788 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7789 observer->MediaStartedPlaying(media_info, id);
7790 });
dalecurtis88c240072015-12-09 02:11:187791}
7792
7793void WebContentsImpl::MediaStoppedPlaying(
billorr21c005d2016-11-17 03:57:047794 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:357795 const MediaPlayerId& id,
Becca Hughes220bfc102017-11-14 18:24:077796 WebContentsObserver::MediaStoppedReason reason) {
billorr21c005d2016-11-17 03:57:047797 if (media_info.has_video)
7798 currently_playing_video_count_--;
7799
Alexander Timin90c20c32020-08-12 15:28:327800 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7801 observer->MediaStoppedPlaying(media_info, id, reason);
7802 });
billorr21c005d2016-11-17 03:57:047803}
7804
Mounir Lamouri0f5bdf52019-04-04 16:32:357805void WebContentsImpl::MediaResized(const gfx::Size& size,
7806 const MediaPlayerId& id) {
peconn257951522017-06-09 18:24:597807 cached_video_sizes_[id] = size;
7808
Alexander Timin90c20c32020-08-12 15:28:327809 observers_.ForEachObserver(
7810 [&](WebContentsObserver* observer) { observer->MediaResized(size, id); });
peconn257951522017-06-09 18:24:597811}
7812
Michael Crousee75c7a42020-07-31 21:11:557813void WebContentsImpl::MediaBufferUnderflow(const MediaPlayerId& id) {
Alexander Timin90c20c32020-08-12 15:28:327814 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7815 observer->MediaBufferUnderflow(id);
7816 });
Michael Crousee75c7a42020-07-31 21:11:557817}
7818
Peter E Conneccb34c22017-09-08 09:37:587819void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) {
Alexander Timin90c20c32020-08-12 15:28:327820 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7821 observer->MediaEffectivelyFullscreenChanged(is_fullscreen);
7822 });
Peter E Conneccb34c22017-09-08 09:37:587823}
7824
Peter Conn31c726a2017-08-17 11:07:347825base::Optional<gfx::Size> WebContentsImpl::GetFullscreenVideoSize() {
Mounir Lamouri0f5bdf52019-04-04 16:32:357826 base::Optional<MediaPlayerId> id =
Peter Conn31c726a2017-08-17 11:07:347827 media_web_contents_observer_->GetFullscreenVideoMediaPlayerId();
Jan Wilken Dörrie531be7ca2019-06-07 10:05:577828 if (id && base::Contains(cached_video_sizes_, id.value()))
Peter Conn31c726a2017-08-17 11:07:347829 return base::Optional<gfx::Size>(cached_video_sizes_[id.value()]);
Lei Zhang6410ec1a2019-01-31 21:38:587830 return base::nullopt;
peconn257951522017-06-09 18:24:597831}
7832
billorr21c005d2016-11-17 03:57:047833int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
7834 return currently_playing_video_count_;
dalecurtis88c240072015-12-09 02:11:187835}
7836
Raymond Toye413650c2018-08-31 00:12:477837void WebContentsImpl::AudioContextPlaybackStarted(RenderFrameHost* host,
7838 int context_id) {
7839 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:327840 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7841 observer->AudioContextPlaybackStarted(audio_context_id);
7842 });
Raymond Toye413650c2018-08-31 00:12:477843}
7844
7845void WebContentsImpl::AudioContextPlaybackStopped(RenderFrameHost* host,
7846 int context_id) {
7847 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:327848 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7849 observer->AudioContextPlaybackStopped(audio_context_id);
7850 });
Raymond Toye413650c2018-08-31 00:12:477851}
7852
Chris Hamilton16ca64a2020-05-14 23:13:177853void WebContentsImpl::OnFrameAudioStateChanged(RenderFrameHost* host,
7854 bool is_audible) {
Alexander Timin90c20c32020-08-12 15:28:327855 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7856 observer->OnFrameAudioStateChanged(host, is_audible);
7857 });
Chris Hamilton16ca64a2020-05-14 23:13:177858}
7859
evliu7f736f02019-11-07 17:43:507860media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
7861WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
Becca Hughes53652442020-03-17 15:35:427862 if (!delegate_ || !delegate_->GetDelegateWeakPtr())
7863 return base::DoNothing();
7864
evliu7f736f02019-11-07 17:43:507865 return base::BindRepeating(
Becca Hughes53652442020-03-17 15:35:427866 [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
7867 base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
7868 bool has_video, bool has_audio) {
evliua283c9e2019-11-08 22:57:227869 content::MediaPlayerWatchTime watch_time(
7870 last_committed_url, last_committed_url.GetOrigin(),
7871 total_watch_time, time_stamp, has_video, has_audio);
evliu7f736f02019-11-07 17:43:507872
7873 // Save the watch time if the delegate is still alive.
7874 if (delegate)
7875 delegate->MediaWatchTimeChanged(watch_time);
7876 },
Becca Hughes53652442020-03-17 15:35:427877 delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
evliu7f736f02019-11-07 17:43:507878}
7879
Ehsan Karamad1c631762019-05-13 23:04:017880RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(
7881 FrameTreeNode* frame_tree_node) {
7882 if (auto* web_contents = node_.GetInnerWebContentsInFrame(frame_tree_node))
7883 return web_contents->GetMainFrame();
7884 return nullptr;
7885}
7886
John Budorickee1c9512019-10-17 15:32:197887bool WebContentsImpl::IsFrameLowPriority(
7888 const RenderFrameHost* render_frame_host) {
7889 if (!delegate_)
7890 return false;
7891 return delegate_->IsFrameLowPriority(this, render_frame_host);
7892}
7893
Roger Tawa03ffdbd2020-01-16 18:12:547894void WebContentsImpl::IsClipboardPasteAllowed(
7895 const GURL& url,
7896 const ui::ClipboardFormatType& data_type,
7897 const std::string& data,
7898 IsClipboardPasteAllowedCallback callback) {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:007899 ++suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:547900 GetContentClient()->browser()->IsClipboardPasteAllowed(
Dominique Fauteux-Chapleau99244382020-07-08 20:37:007901 this, url, data_type, data,
7902 base::BindOnce(&WebContentsImpl::IsClipboardPasteAllowedWrapperCallback,
7903 weak_factory_.GetWeakPtr(), std::move(callback)));
7904}
7905
7906void WebContentsImpl::IsClipboardPasteAllowedWrapperCallback(
7907 IsClipboardPasteAllowedCallback callback,
7908 ClipboardPasteAllowed allowed) {
7909 std::move(callback).Run(allowed);
7910 --suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:547911}
7912
Lan Weif81c6e7c2020-02-12 16:46:097913bool WebContentsImpl::HasSeenRecentScreenOrientationChange() {
7914 static constexpr base::TimeDelta kMaxInterval =
7915 base::TimeDelta::FromSeconds(1);
7916 base::TimeDelta delta =
7917 ui::EventTimeForNow() - last_screen_orientation_change_time_;
7918 // Return whether there is a screen orientation change happened in the recent
7919 // 1 second.
7920 return delta <= kMaxInterval;
7921}
7922
7923void WebContentsImpl::DidChangeScreenOrientation() {
7924 last_screen_orientation_change_time_ = ui::EventTimeForNow();
7925}
7926
Miyoung Shin8f2e1832020-04-27 09:00:027927bool WebContentsImpl::ShowPopupMenu(
Miyoung Shin4d947d22020-04-24 04:48:337928 RenderFrameHostImpl* render_frame_host,
Miyoung Shin8f2e1832020-04-27 09:00:027929 mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
Miyoung Shin4d947d22020-04-24 04:48:337930 const gfx::Rect& bounds,
7931 int32_t item_height,
7932 double font_size,
7933 int32_t selected_item,
7934 std::vector<blink::mojom::MenuItemPtr>* menu_items,
7935 bool right_aligned,
7936 bool allow_multiple_selection) {
Alexander Timin90c20c32020-08-12 15:28:327937 for (auto& observer : observers_.observer_list()) {
Miyoung Shin8f2e1832020-04-27 09:00:027938 if (observer.ShowPopupMenu(render_frame_host, popup_client, bounds,
7939 item_height, font_size, selected_item,
7940 menu_items, right_aligned,
7941 allow_multiple_selection)) {
Miyoung Shin4d947d22020-04-24 04:48:337942 return true;
7943 }
7944 }
7945 return false;
7946}
7947
Francois Doraye6161152018-03-27 22:05:377948void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
Francois Doray3f2afbd2018-04-06 19:18:187949 // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
7950 // (for power and speed impact assessment) or when
7951 // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
7952 // the command line (to avoid flakiness in browser tests).
7953 const bool occlusion_is_disabled =
7954 !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
Francois Doraye6161152018-03-27 22:05:377955 base::CommandLine::ForCurrentProcess()->HasSwitch(
7956 switches::kDisableBackgroundingOccludedWindowsForTesting);
7957 if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
7958 visibility = Visibility::VISIBLE;
7959
tapted65ff2ea72016-03-01 23:39:007960 if (!did_first_set_visible_) {
Francois Doraye6161152018-03-27 22:05:377961 if (visibility == Visibility::VISIBLE) {
7962 // A WebContents created with CreateParams::initially_hidden = false
7963 // starts with GetVisibility() == Visibility::VISIBLE even though it is
7964 // not really visible. Call WasShown() when it becomes visible for real as
7965 // the page load mechanism and some WebContentsObserver rely on that.
tapted65ff2ea72016-03-01 23:39:007966 WasShown();
Francois Dorayfe4a1772018-02-17 04:17:097967 did_first_set_visible_ = true;
tapted65ff2ea72016-03-01 23:39:007968 }
Francois Doraye6161152018-03-27 22:05:377969
7970 // Trust the initial visibility of the WebContents and do not switch it to
7971 // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
7972 // result in destroying resources that would immediately be recreated (e.g.
7973 // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
7974 // hidden window that is about to be shown).
7975
tapted65ff2ea72016-03-01 23:39:007976 return;
7977 }
Francois Doraye6161152018-03-27 22:05:377978
7979 if (visibility == visibility_)
tapted65ff2ea72016-03-01 23:39:007980 return;
7981
Collin Baker989e0882019-11-01 01:27:177982 UpdateVisibilityAndNotifyPageAndView(visibility);
tapted65ff2ea72016-03-01 23:39:007983}
7984
aelias5252baa2016-04-10 01:18:027985void WebContentsImpl::UpdateOverridingUserAgent() {
mlamouri5cd9ae82017-02-18 11:05:097986 NotifyPreferencesChanged();
aelias5252baa2016-04-10 01:18:027987}
7988
avid53461d2016-02-25 17:15:047989void WebContentsImpl::SetJavaScriptDialogManagerForTesting(
7990 JavaScriptDialogManager* dialog_manager) {
7991 dialog_manager_ = dialog_manager;
7992}
7993
Julie Jeongeun Kim7d0986172019-12-04 03:17:257994void WebContentsImpl::RemoveReceiverSet(const std::string& interface_name) {
7995 auto it = receiver_sets_.find(interface_name);
7996 if (it != receiver_sets_.end())
7997 receiver_sets_.erase(it);
rockotf62002a2016-09-15 00:08:597998}
7999
nzolghadrd87a308d2016-12-07 15:45:568000bool WebContentsImpl::AddDomainInfoToRapporSample(rappor::Sample* sample) {
nzolghadrbbffc6c2017-05-25 17:56:398001 // Here we associate this metric to the main frame URL regardless of what
8002 // caused it.
nzolghadrd87a308d2016-12-07 15:45:568003 sample->SetStringField("Domain", ::rappor::GetDomainAndRegistrySampleFromGURL(
8004 GetLastCommittedURL()));
nzolghadrd87a308d2016-12-07 15:45:568005 return true;
8006}
8007
falken52a56e32016-12-08 05:02:408008void WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded() {
8009 bool allow_localhost = base::CommandLine::ForCurrentProcess()->HasSwitch(
8010 switches::kAllowInsecureLocalhost);
8011 if (!allow_localhost)
8012 return;
8013
8014 content::NavigationEntry* entry = GetController().GetLastCommittedEntry();
Rob Wuf79b3ba2018-01-14 01:54:318015 if (!entry || !net::IsLocalhost(entry->GetURL()))
falken52a56e32016-12-08 05:02:408016 return;
8017
8018 content::SSLStatus ssl_status = entry->GetSSL();
Matt Mueller936511442019-09-03 18:15:128019 if (!net::IsCertStatusError(ssl_status.cert_status))
falken52a56e32016-12-08 05:02:408020 return;
8021
8022 GetMainFrame()->AddMessageToConsole(
Abhijeet Kandalkara5928a0a2019-03-13 05:04:428023 blink::mojom::ConsoleMessageLevel::kWarning,
falken52a56e32016-12-08 05:02:408024 base::StringPrintf("This site does not have a valid SSL "
8025 "certificate! Without SSL, your site's and "
8026 "visitors' data is vulnerable to theft and "
8027 "tampering. Get a valid SSL certificate before"
8028 " releasing your website to the public."));
8029}
8030
ekaramadf6750aa2017-06-06 18:29:428031bool WebContentsImpl::IsShowingContextMenuOnPage() const {
8032 return showing_context_menu_;
8033}
8034
Min Qina904f3302018-02-13 23:33:348035download::DownloadUrlParameters::RequestHeadersType
8036WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
8037 download::DownloadUrlParameters::RequestHeadersType request_headers;
Megan Jablonski2f6a4c52017-07-10 23:01:258038 for (const base::StringPiece& key_value : base::SplitStringPiece(
8039 headers, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
8040 std::vector<std::string> pair = base::SplitString(
8041 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
8042 if (2ul == pair.size())
8043 request_headers.push_back(make_pair(pair[0], pair[1]));
8044 }
8045 return request_headers;
8046}
8047
lukasza6f8ac622017-06-06 03:10:208048void WebContentsImpl::SetOpenerForNewContents(FrameTreeNode* opener,
8049 bool opener_suppressed) {
8050 if (opener) {
8051 FrameTreeNode* new_root = GetFrameTree()->root();
8052
8053 // For the "original opener", track the opener's main frame instead, because
8054 // if the opener is a subframe, the opener tracking could be easily bypassed
8055 // by spawning from a subframe and deleting the subframe.
8056 // https://crbug.com/705316
8057 new_root->SetOriginalOpener(opener->frame_tree()->root());
8058
8059 if (!opener_suppressed) {
8060 new_root->SetOpener(opener);
8061 created_with_opener_ = true;
8062 }
8063 }
8064}
8065
Mounir Lamouri0f5bdf52019-04-04 16:32:358066void WebContentsImpl::MediaMutedStatusChanged(const MediaPlayerId& id,
8067 bool muted) {
Alexander Timin90c20c32020-08-12 15:28:328068 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8069 observer->MediaMutedStatusChanged(id, muted);
8070 });
Becca Hughes9f6fd4b82017-06-15 10:01:408071}
8072
EhsanK2075c7e2017-08-21 02:42:398073void WebContentsImpl::SetVisibilityForChildViews(bool visible) {
8074 GetMainFrame()->SetVisibilityForChildViews(visible);
8075}
8076
Alison Maher7f366dc62020-03-03 19:46:008077void WebContentsImpl::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
8078 DCHECK(native_theme_observer_.IsObserving(observed_theme));
8079
8080 bool using_dark_colors = observed_theme->ShouldUseDarkColors();
8081 ui::NativeTheme::PreferredColorScheme preferred_color_scheme =
8082 observed_theme->GetPreferredColorScheme();
8083 bool preferences_changed = false;
8084
8085 if (using_dark_colors_ != using_dark_colors) {
8086 using_dark_colors_ = using_dark_colors;
8087 preferences_changed = true;
8088 }
8089 if (preferred_color_scheme_ != preferred_color_scheme) {
8090 preferred_color_scheme_ = preferred_color_scheme;
8091 preferences_changed = true;
8092 }
8093
8094 if (preferences_changed)
8095 NotifyPreferencesChanged();
8096}
8097
Dave Tapuska58a099e2020-06-08 21:48:408098blink::mojom::FrameWidgetInputHandler*
8099WebContentsImpl::GetFocusedFrameWidgetInputHandler() {
8100 auto* focused_render_widget_host =
8101 GetFocusedRenderWidgetHost(GetMainFrame()->GetRenderWidgetHost());
8102 if (!focused_render_widget_host)
Dave Tapuskae782bea2019-07-09 16:21:518103 return nullptr;
Dave Tapuska58a099e2020-06-08 21:48:408104 return focused_render_widget_host->GetFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:518105}
8106
Alexander Timine3ec4192020-04-20 16:39:408107ukm::SourceId WebContentsImpl::GetCurrentPageUkmSourceId() {
8108 return GetMainFrame()->GetPageUkmSourceId();
8109}
8110
Yuzu Saijo232076f2020-05-29 07:14:028111std::set<RenderViewHostImpl*>
8112WebContentsImpl::GetRenderViewHostsIncludingBackForwardCached() {
8113 std::set<RenderViewHostImpl*> render_view_hosts;
8114
8115 // Add RenderViewHostImpls outside of BackForwardCache.
8116 for (auto& render_view_host : frame_tree_.render_view_hosts()) {
8117 render_view_hosts.insert(render_view_host.second);
8118 }
8119
8120 // Add RenderViewHostImpls in BackForwardCache.
8121 const auto& entries = GetController().GetBackForwardCache().GetEntries();
8122 for (const auto& entry : entries) {
8123 std::set<RenderViewHostImpl*> bfcached_hosts = entry->render_view_hosts;
8124 render_view_hosts.insert(bfcached_hosts.begin(), bfcached_hosts.end());
8125 }
8126
8127 return render_view_hosts;
8128}
8129
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508130void WebContentsImpl::RenderFrameHostStateChanged(
8131 RenderFrameHost* render_frame_host,
8132 LifecycleState old_state,
8133 LifecycleState new_state) {
8134 if (render_frame_host->GetParent())
8135 return;
8136
8137 if (old_state == LifecycleState::kActive &&
8138 new_state != LifecycleState::kActive) {
8139 // TODO(sreejakshetty): Remove this reset when ColorChooser becomes
8140 // per-frame.
8141 // Close the color chooser popup when RenderFrameHost changes state from
8142 // kActive.
8143 color_chooser_.reset();
8144 }
8145}
8146
[email protected]8ff00d72012-10-23 19:12:218147} // namespace content