blob: 705f6daa1e21a0df69a38e852025f16baeac56db [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>
Alexander Timin5fdeff22020-09-08 09:20:3711#include <memory>
[email protected]2bb171882012-03-07 02:09:4612#include <utility>
rkaplowe56a52032017-02-07 00:14:5413#include <vector>
[email protected]b75b8292010-10-01 07:28:2514
Sebastien Marchandf8cbfab2019-01-25 16:02:3015#include "base/bind.h"
[email protected]36fb2c7c2011-04-04 15:49:0816#include "base/command_line.h"
Avi Drissman33972942020-06-19 14:16:0117#include "base/containers/flat_set.h"
creisfafed882016-07-29 00:03:0918#include "base/debug/dump_without_crashing.h"
zqzhang181047e62016-07-01 13:37:1719#include "base/feature_list.h"
Marijn Kruisselbrink46fa4bd2019-07-11 18:15:4720#include "base/files/file_path.h"
[email protected]cbb1ef592013-06-05 19:49:4621#include "base/lazy_instance.h"
skyostil95082a62015-06-05 19:53:0722#include "base/location.h"
[email protected]6d636e62013-07-31 03:15:5623#include "base/logging.h"
avib7348942015-12-25 20:57:1024#include "base/macros.h"
fdorayba121422016-12-23 19:51:4825#include "base/memory/ptr_util.h"
dmazzonid95ae842016-04-12 21:17:3926#include "base/memory/ref_counted.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2027#include "base/metrics/field_trial.h"
asvitkine8d51e9d2016-09-02 23:55:4328#include "base/metrics/histogram_macros.h"
bratell0a7406f2017-03-28 07:46:3729#include "base/metrics/user_metrics.h"
Avi Drissman4891b852018-09-25 18:12:5830#include "base/no_destructor.h"
Carlos Caballero1215f882019-10-29 15:58:4331#include "base/optional.h"
[email protected]04cbd3d2013-12-04 04:58:2032#include "base/process/process.h"
skyostil95082a62015-06-05 19:53:0733#include "base/single_thread_task_runner.h"
Arthur Sonzogni929d29f2018-09-17 14:19:4434#include "base/stl_util.h"
[email protected]348fbaac2013-06-11 06:31:5135#include "base/strings/string16.h"
36#include "base/strings/string_number_conversions.h"
Avi Drissman4891b852018-09-25 18:12:5837#include "base/strings/string_split.h"
[email protected]348fbaac2013-06-11 06:31:5138#include "base/strings/string_util.h"
[email protected]74ebfb12013-06-07 20:48:0039#include "base/strings/utf_string_conversions.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:2040#include "base/system/sys_info.h"
gab30f26df2016-05-11 19:37:5541#include "base/threading/thread_task_runner_handle.h"
[email protected]a43858f2013-06-28 15:18:3742#include "base/time/time.h"
Alexander Timin5fdeff22020-09-08 09:20:3743#include "base/trace_event/optional_trace_event.h"
44#include "base/trace_event/trace_conversion_helper.h"
ssid3e765612015-01-28 04:03:4245#include "base/trace_event/trace_event.h"
Alexander Timin5fdeff22020-09-08 09:20:3746#include "base/trace_event/traced_value.h"
avib7348942015-12-25 20:57:1047#include "build/build_config.h"
Hidehiko Abe7c68f582020-09-03 15:47:2548#include "build/chromeos_buildflags.h"
Min Qinda0ed2062018-02-23 22:00:5349#include "components/download/public/common/download_stats.h"
nzolghadrd87a308d2016-12-07 15:45:5650#include "components/rappor/public/rappor_utils.h"
rsleevi24f64dc22015-08-07 21:39:2151#include "components/url_formatter/url_formatter.h"
Abigail Kleinaa898742019-11-01 02:31:2552#include "content/browser/accessibility/accessibility_event_recorder.h"
James Wallace-Leeeafc94cb92018-07-23 21:35:0953#include "content/browser/accessibility/accessibility_tree_formatter_blink.h"
jamescookda2505812015-03-20 18:01:1854#include "content/browser/bad_message.h"
Max Morinddebb972018-09-20 10:04:1455#include "content/browser/browser_main_loop.h"
[email protected]7a846df2012-09-20 19:17:3956#include "content/browser/browser_plugin/browser_plugin_embedder.h"
57#include "content/browser/browser_plugin/browser_plugin_guest.h"
[email protected]b9535422012-02-09 01:47:5958#include "content/browser/child_process_security_policy_impl.h"
John Delaney732721e92020-02-07 23:11:2759#include "content/browser/conversions/conversion_host.h"
Pavel Feldman3c1842b2017-08-02 05:00:1660#include "content/browser/devtools/protocol/page_handler.h"
dgozmanf00c4f72016-10-19 17:45:1561#include "content/browser/devtools/render_frame_devtools_agent_host.h"
Becca Hughes3b5a43482018-07-17 22:31:5562#include "content/browser/display_cutout/display_cutout_host_impl.h"
[email protected]5f2aa722013-08-07 16:59:4163#include "content/browser/dom_storage/dom_storage_context_wrapper.h"
[email protected]1ea3c792012-04-17 01:25:0464#include "content/browser/dom_storage/session_storage_namespace_impl.h"
[email protected]aa4f3972012-03-01 18:12:1265#include "content/browser/download/mhtml_generation_manager.h"
[email protected]a53209b2012-01-20 16:48:1666#include "content/browser/download/save_package.h"
paulmeyerc0b762b2016-04-13 11:55:1767#include "content/browser/find_request_manager.h"
[email protected]bffc8302014-01-23 20:52:1668#include "content/browser/frame_host/cross_process_frame_connector.h"
ananta4b7467a52016-09-23 01:42:3869#include "content/browser/frame_host/frame_tree_node.h"
[email protected]d4a8ca482013-10-30 21:06:4070#include "content/browser/frame_host/navigation_entry_impl.h"
Arthur Hemeryc3380172018-01-22 14:00:1771#include "content/browser/frame_host/navigation_request.h"
Hiroki Nakagawa080f86c2020-05-13 10:56:4272#include "content/browser/frame_host/navigator.h"
[email protected]52913802013-12-10 05:52:1873#include "content/browser/frame_host/render_frame_host_impl.h"
lfgdb5c4ed2016-03-04 23:09:0774#include "content/browser/frame_host/render_frame_proxy_host.h"
Kenneth Russell954ed9ce2018-04-12 23:07:0175#include "content/browser/gpu/gpu_data_manager_impl.h"
mlamouriefdca9d2014-09-16 16:55:4076#include "content/browser/manifest/manifest_manager_host.h"
Max Morin5bc74f52018-05-09 07:00:2177#include "content/browser/media/audio_stream_broker.h"
dalecurtisbc6572e12014-09-12 19:22:3078#include "content/browser/media/audio_stream_monitor.h"
miu50f97892014-09-22 22:49:5279#include "content/browser/media/capture/web_contents_audio_muter.h"
dalecurtis88c240072015-12-09 02:11:1880#include "content/browser/media/media_web_contents_observer.h"
zqzhang1adf3cb2016-11-01 11:26:4581#include "content/browser/media/session/media_session_impl.h"
Mike Wassermandabad612020-08-13 04:26:2782#include "content/browser/permissions/permission_controller_impl.h"
Yuzu Saijoa11069a2020-04-22 10:56:5583#include "content/browser/plugin_content_origin_allowlist.h"
Kevin McNee94ea52f52020-06-23 17:42:0684#include "content/browser/portal/portal.h"
Tal Pressman5dcd2382020-08-26 07:13:0585#include "content/browser/renderer_host/agent_scheduling_group_host.h"
David Black9cca3592019-11-06 23:02:2286#include "content/browser/renderer_host/frame_token_message_queue.h"
[email protected]f3b1a082011-11-18 00:34:3087#include "content/browser/renderer_host/render_process_host_impl.h"
[email protected]21161032014-05-05 16:56:5088#include "content/browser/renderer_host/render_view_host_delegate_view.h"
[email protected]b3c41c0b2012-03-06 15:48:3289#include "content/browser/renderer_host/render_view_host_impl.h"
[email protected]bafe6cd2012-05-23 23:09:5090#include "content/browser/renderer_host/render_widget_host_impl.h"
kenrb2a565f82015-09-02 20:24:5991#include "content/browser/renderer_host/render_widget_host_input_event_router.h"
[email protected]cfd80b02014-05-01 17:46:4892#include "content/browser/renderer_host/render_widget_host_view_base.h"
Ken Buchanandaef006b2017-08-17 18:32:1593#include "content/browser/renderer_host/render_widget_host_view_child_frame.h"
ekaramadadd882292016-06-08 15:22:5694#include "content/browser/renderer_host/text_input_manager.h"
Mike Wassermanb213b9352020-04-16 00:32:3495#include "content/browser/screen_enumeration/screen_change_monitor.h"
leon.han552e9de2017-02-09 14:37:3096#include "content/browser/screen_orientation/screen_orientation_provider.h"
[email protected]b6583592012-01-25 19:52:3397#include "content/browser/site_instance_impl.h"
Charlie Reis96077362019-07-04 00:34:0498#include "content/browser/web_contents/javascript_dialog_navigation_deferrer.h"
lfgc740d4b22016-04-15 16:45:3399#include "content/browser/web_contents/web_contents_view_child_frame.h"
Tsuyoshi Horob0d8d902020-03-12 00:09:39100#include "content/browser/web_package/save_as_web_bundle_job.h"
[email protected]86a0a6e2013-01-28 06:33:03101#include "content/browser/webui/web_ui_controller_factory_registry.h"
[email protected]d2353452012-01-19 19:53:56102#include "content/browser/webui/web_ui_impl.h"
[email protected]8eb04562013-03-06 03:41:14103#include "content/common/browser_plugin/browser_plugin_constants.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20104#include "content/common/content_switches_internal.h"
Paul Meyer0c58c3712016-11-17 22:59:51105#include "content/common/drag_messages.h"
[email protected]f114fa42013-12-06 17:06:44106#include "content/common/frame_messages.h"
[email protected]1f3fc1d2014-04-03 14:50:17107#include "content/common/input_messages.h"
lfgdb5c4ed2016-03-04 23:09:07108#include "content/common/page_messages.h"
nasko34634672016-07-29 18:46:06109#include "content/common/page_state_serialization.h"
rockot5c478a72016-09-28 23:14:18110#include "content/common/render_message_filter.mojom.h"
[email protected]2c5569662011-03-22 20:45:02111#include "content/common/view_messages.h"
Albert J. Wong3c93c182018-09-27 17:29:43112#include "content/common/widget_messages.h"
Abigail Kleinabb428332019-09-13 18:26:21113#include "content/public/browser/accessibility_tree_formatter.h"
[email protected]31a71eaf2014-03-13 01:47:36114#include "content/public/browser/ax_event_notification_details.h"
[email protected]ccb797302011-12-15 16:55:11115#include "content/public/browser/browser_context.h"
[email protected]139355f2014-05-11 14:21:28116#include "content/public/browser/browser_plugin_guest_manager.h"
Eric Seckler8652dcd52018-09-20 10:42:28117#include "content/public/browser/browser_task_traits.h"
Gabriel Charette790754c2018-03-16 21:32:59118#include "content/public/browser/browser_thread.h"
[email protected]87f3c082011-10-19 18:07:44119#include "content/public/browser/content_browser_client.h"
Lukasz Anforowicz8c4446dc2020-03-11 22:16:42120#include "content/public/browser/context_menu_params.h"
Ken Rockotce010f02019-12-12 23:32:32121#include "content/public/browser/device_service.h"
[email protected]e582fdd2011-12-20 16:48:17122#include "content/public/browser/download_manager.h"
Kent Tamura512a27e2018-10-04 00:49:32123#include "content/public/browser/file_select_listener.h"
ekaramada110f642016-12-21 19:47:28124#include "content/public/browser/focused_node_details.h"
Danyao Wanga78f3dd22020-03-05 05:31:27125#include "content/public/browser/global_routing_id.h"
[email protected]d9083482012-01-06 00:38:46126#include "content/public/browser/invalidate_type.h"
[email protected]71a88bb2013-02-01 22:05:15127#include "content/public/browser/javascript_dialog_manager.h"
skyf65d9bb2017-03-24 02:26:39128#include "content/public/browser/keyboard_event_processing_result.h"
[email protected]09d31d52012-03-11 22:30:27129#include "content/public/browser/load_notification_details.h"
[email protected]5b96836f2011-12-22 07:39:00130#include "content/public/browser/navigation_details.h"
[email protected]375fa1b2012-05-22 22:05:37131#include "content/public/browser/notification_details.h"
[email protected]be2510c02012-05-28 14:52:14132#include "content/public/browser/notification_service.h"
scottmg011d96e32016-06-29 19:15:08133#include "content/public/browser/notification_types.h"
[email protected]95640212014-07-26 18:14:30134#include "content/public/browser/render_widget_host_iterator.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06135#include "content/public/browser/restore_type.h"
estark5ea80e52015-06-19 18:43:12136#include "content/public/browser/security_style_explanations.h"
falken52a56e32016-12-08 05:02:40137#include "content/public/browser/ssl_status.h"
[email protected]4c3a23582012-08-18 08:54:34138#include "content/public/browser/storage_partition.h"
[email protected]674bc592011-12-20 23:00:42139#include "content/public/browser/web_contents_delegate.h"
Julie Jeongeun Kim7d0986172019-12-04 03:17:25140#include "content/public/browser/web_contents_receiver_set.h"
Lei Zhangee3b63ad2018-06-06 23:25:31141#include "content/public/browser/web_ui_controller.h"
[email protected]e091df82011-10-11 18:13:21142#include "content/public/common/bindings_policy.h"
alexmosc9e76ec2016-05-16 22:59:37143#include "content/public/common/child_process_host.h"
Hans Wennborg5ffd1392019-10-16 11:00:02144#include "content/public/common/content_client.h"
[email protected]54087fe2011-10-28 22:02:48145#include "content/public/common/content_constants.h"
Francois Doray3f2afbd2018-04-06 19:18:18146#include "content/public/common/content_features.h"
[email protected]64d69de42012-02-06 00:19:54147#include "content/public/common/content_switches.h"
Lukasz Anforowicze1b954d92017-10-30 21:28:06148#include "content/public/common/page_state.h"
Leon Han963dc182018-11-06 05:41:48149#include "content/public/common/referrer_type_converters.h"
[email protected]04cbd3d2013-12-04 04:58:20150#include "content/public/common/result_codes.h"
[email protected]f16cc6782013-12-16 23:42:57151#include "content/public/common/url_utils.h"
danakjffc8baf2019-10-10 23:49:42152#include "content/public/common/use_zoom_for_dsf_policy.h"
[email protected]b3a97b52014-07-09 06:25:05153#include "content/public/common/web_preferences.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20154#include "media/base/media_switches.h"
Max Morinddebb972018-09-20 10:04:14155#include "media/base/user_input_monitor.h"
wjmaclean64951902016-04-29 20:59:12156#include "net/base/url_util.h"
[email protected]8bfc8272013-09-09 20:10:53157#include "net/http/http_cache.h"
158#include "net/http/http_transaction_factory.h"
David Van Clevef99881632020-07-16 19:41:13159#include "net/http/http_util.h"
rhalavati0fbaeef32017-06-01 15:56:30160#include "net/traffic_annotation/network_traffic_annotation.h"
Scott Violet02e38b92018-03-27 23:42:14161#include "ppapi/buildflags/buildflags.h"
Mounir Lamourifd9dcefa2017-07-06 10:26:55162#include "services/metrics/public/cpp/ukm_recorder.h"
John Abd-El-Malekb175a612018-12-03 20:11:58163#include "services/network/public/cpp/features.h"
arthursonzognib93a4472020-04-10 07:38:00164#include "services/network/public/cpp/web_sandbox_flags.h"
165#include "services/network/public/mojom/web_sandbox_flags.mojom.h"
rockot734fb662016-10-15 16:41:30166#include "services/service_manager/public/cpp/interface_provider.h"
Becca Hughes6daf5662018-06-27 16:50:54167#include "third_party/blink/public/common/associated_interfaces/associated_interface_provider.h"
Blink Reformata30d4232018-04-07 15:31:06168#include "third_party/blink/public/common/mime_util/mime_util.h"
danakj938b37a62019-09-24 18:35:54169#include "third_party/blink/public/common/page/page_zoom.h"
Sergio Villar Senin9d9d4f52019-10-15 10:57:57170#include "third_party/blink/public/common/security/security_style.h"
Abhijeet Kandalkarde7348e2020-01-13 06:06:54171#include "third_party/blink/public/mojom/frame/frame.mojom.h"
Dave Tapuskaa4189512019-10-15 20:27:34172#include "third_party/blink/public/mojom/frame/fullscreen.mojom.h"
Takuto Ikutaaa3b796c2019-02-06 02:54:56173#include "third_party/blink/public/mojom/loader/pause_subresource_loading_handle.mojom.h"
Antonio Gomes0d42960a2019-06-05 12:35:51174#include "third_party/blink/public/mojom/mediastream/media_stream.mojom-shared.h"
halton.huoca2eabd2015-07-06 08:17:40175#include "third_party/skia/include/core/SkBitmap.h"
dmazzonid95ae842016-04-12 21:17:39176#include "ui/accessibility/ax_tree_combiner.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20177#include "ui/base/device_form_factor.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45178#if defined(USE_AURA)
179#include "ui/aura/window.h"
180#endif
[email protected]a08412b62012-05-29 21:28:56181#include "ui/base/layout.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20182#include "ui/base/ui_base_features.h"
183#include "ui/base/ui_base_switches.h"
184#include "ui/display/screen.h"
Daniel Cheng90196c82018-04-25 21:49:14185#include "ui/events/base_event_utils.h"
chongz4a9751942016-08-17 17:49:39186#include "ui/events/blink/web_input_event_traits.h"
Rakina Zata Amni4029b6d2020-07-28 02:36:20187#include "ui/gfx/animation/animation.h"
[email protected]66bd5512012-08-01 02:02:52188#include "ui/gl/gl_switches.h"
[email protected]3c733bde2010-12-21 19:56:31189
ekaramada110f642016-12-21 19:47:28190#if defined(OS_WIN)
191#include "content/browser/renderer_host/dip_util.h"
192#include "ui/gfx/geometry/dip_util.h"
193#endif
194
[email protected]583418cc2013-01-17 14:01:10195#if defined(OS_ANDROID)
mfomitchev2b8b066a2016-01-28 19:23:15196#include "content/browser/android/date_time_chooser_android.h"
sammcf5f1b0f2016-09-20 23:05:11197#include "content/browser/android/java_interfaces_impl.h"
Leon Hanccb985f2019-08-26 02:43:24198#include "content/browser/android/nfc_host.h"
[email protected]155c7f22013-12-09 17:07:18199#include "content/browser/web_contents/web_contents_android.h"
Ke He31d0bb02018-02-24 07:16:24200#include "services/device/public/mojom/nfc.mojom.h"
Mugdha Lakhani0a0d7862020-07-29 09:58:45201#include "ui/android/view_android.h"
mcnee336ea2c2017-05-23 22:50:59202#else // !OS_ANDROID
203#include "content/browser/host_zoom_map_impl.h"
mfomitchev2b8b066a2016-01-28 19:23:15204#endif // OS_ANDROID
[email protected]583418cc2013-01-17 14:01:10205
brettw4b461082016-11-19 18:55:16206#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17207#include "content/browser/media/session/pepper_playback_observer.h"
Lei Zhangebcc6302018-01-12 19:46:45208#endif
zqzhang181047e62016-07-01 13:37:17209
[email protected]8ff00d72012-10-23 19:12:21210namespace content {
Abigail Kleinaa898742019-11-01 02:31:25211
212using AccessibilityEventCallback =
213 base::RepeatingCallback<void(const std::string&)>;
214
[email protected]420ae012009-04-24 05:16:32215namespace {
216
[email protected]960b0372014-05-19 18:01:00217const int kMinimumDelayBetweenLoadingUpdatesMS = 100;
[email protected]82114f52012-03-20 22:53:41218const char kDotGoogleDotCom[] = ".google.com";
[email protected]ca406032011-07-19 21:53:05219
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50220using LifecycleState = RenderFrameHostImpl::LifecycleState;
221
Alexander Timin33bd754c02020-03-10 22:50:18222// TODO(crbug.com/1059903): Clean up after the initial investigation.
223constexpr base::Feature kCheckWebContentsAccessFromNonCurrentFrame{
224 "CheckWebContentsAccessFromNonCurrentFrame",
225 base::FEATURE_DISABLED_BY_DEFAULT};
226
Avi Drissmana9114822018-03-23 18:25:55227base::LazyInstance<std::vector<
228 WebContentsImpl::FriendWrapper::CreatedCallback>>::DestructorAtExit
229 g_created_callbacks = LAZY_INSTANCE_INITIALIZER;
[email protected]cbb1ef592013-06-05 19:49:46230
dcheng57e39e22016-01-21 00:25:38231bool HasMatchingProcess(FrameTree* tree, int render_process_id) {
232 for (FrameTreeNode* node : tree->Nodes()) {
233 if (node->current_frame_host()->GetProcess()->GetID() == render_process_id)
234 return true;
alexmos4cf2aa32015-07-15 23:40:43235 }
dcheng57e39e22016-01-21 00:25:38236 return false;
[email protected]95640212014-07-26 18:14:30237}
238
kenrb19221852016-04-29 17:21:40239bool HasMatchingWidgetHost(FrameTree* tree, RenderWidgetHost* host) {
240 // This method scans the frame tree rather than checking whether
241 // host->delegate() == this, which allows it to return false when the host
242 // for a frame that is pending or pending deletion.
243 if (!host)
244 return false;
245
246 for (FrameTreeNode* node : tree->Nodes()) {
247 if (node->current_frame_host()->GetRenderWidgetHost() == host)
248 return true;
249 }
250 return false;
251}
252
dmazzonif8a31042016-12-03 00:52:13253void UpdateAccessibilityModeOnFrame(RenderFrameHost* frame_host) {
254 static_cast<RenderFrameHostImpl*>(frame_host)->UpdateAccessibilityMode();
[email protected]95640212014-07-26 18:14:30255}
256
dtseng0dd3fa12015-07-22 19:00:52257void ResetAccessibility(RenderFrameHost* rfh) {
258 static_cast<RenderFrameHostImpl*>(rfh)->AccessibilityReset();
259}
260
Ian Clelland5cbaaf82017-11-27 22:00:03261RenderFrameHostImpl* FindOpenerRFH(const WebContents::CreateParams& params) {
262 RenderFrameHostImpl* opener_rfh = nullptr;
alexmose201c7cd2015-06-10 17:14:21263 if (params.opener_render_frame_id != MSG_ROUTING_NONE) {
Ian Clelland5cbaaf82017-11-27 22:00:03264 opener_rfh = RenderFrameHostImpl::FromID(params.opener_render_process_id,
265 params.opener_render_frame_id);
alexmose201c7cd2015-06-10 17:14:21266 }
Ian Clelland5cbaaf82017-11-27 22:00:03267 return opener_rfh;
lukasza6f8ac622017-06-06 03:10:20268}
269
Dominick Ng37a15052018-07-17 23:56:35270// Returns |true| if |type| is the kind of user input that should trigger the
271// user interaction observers.
272bool IsUserInteractionInputType(blink::WebInputEvent::Type type) {
273 // Ideally, this list would be based more off of
274 // https://whatwg.org/C/interaction.html#triggered-by-user-activation.
Dave Tapuska347d60a2020-04-21 23:55:47275 return type == blink::WebInputEvent::Type::kMouseDown ||
276 type == blink::WebInputEvent::Type::kGestureScrollBegin ||
277 type == blink::WebInputEvent::Type::kTouchStart ||
278 type == blink::WebInputEvent::Type::kRawKeyDown;
Dominick Ng37a15052018-07-17 23:56:35279}
280
Pavel Feldman3c1842b2017-08-02 05:00:16281// Ensures that OnDialogClosed is only called once.
282class CloseDialogCallbackWrapper
283 : public base::RefCountedThreadSafe<CloseDialogCallbackWrapper> {
284 public:
Avi Drissmane04d3992017-10-05 15:11:36285 using CloseCallback =
286 base::OnceCallback<void(bool, bool, const base::string16&)>;
287
288 explicit CloseDialogCallbackWrapper(CloseCallback callback)
289 : callback_(std::move(callback)) {}
Pavel Feldman3c1842b2017-08-02 05:00:16290
291 void Run(bool dialog_was_suppressed,
292 bool success,
293 const base::string16& user_input) {
Avi Drissmane04d3992017-10-05 15:11:36294 if (callback_.is_null())
Pavel Feldman3c1842b2017-08-02 05:00:16295 return;
Avi Drissmane04d3992017-10-05 15:11:36296 std::move(callback_).Run(dialog_was_suppressed, success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:16297 }
298
299 private:
300 friend class base::RefCountedThreadSafe<CloseDialogCallbackWrapper>;
301 ~CloseDialogCallbackWrapper() {}
Avi Drissmane04d3992017-10-05 15:11:36302
303 CloseCallback callback_;
Pavel Feldman3c1842b2017-08-02 05:00:16304};
305
Arthur Sonzogni929d29f2018-09-17 14:19:44306bool FrameCompareDepth(RenderFrameHostImpl* a, RenderFrameHostImpl* b) {
307 return a->frame_tree_node()->depth() < b->frame_tree_node()->depth();
308}
309
Raymes Khoury58373df2019-08-06 06:29:20310bool AreValidRegisterProtocolHandlerArguments(const std::string& protocol,
311 const GURL& url,
312 const url::Origin& origin) {
313 ChildProcessSecurityPolicyImpl* policy =
314 ChildProcessSecurityPolicyImpl::GetInstance();
315 if (policy->IsPseudoScheme(protocol))
316 return false;
317
318 url::Origin url_origin = url::Origin::Create(url);
319 if (url_origin.opaque())
320 return false;
321
322 if (!url_origin.IsSameOriginWith(origin))
323 return false;
324
325 return true;
326}
327
yilkal796e89e2019-10-02 23:58:28328void RecordMaxFrameCountUMA(size_t max_frame_count) {
329 UMA_HISTOGRAM_COUNTS_10000("Navigation.MainFrame.MaxFrameCount",
330 max_frame_count);
331}
332
Jeremy Roman03ce13ce2020-05-29 22:16:57333// Returns whether the condition provided applies to any inner contents.
334// This check is not recursive (however, the predicate provided may itself
335// recurse each contents' own inner contents).
336//
337// For example, if this is used to aggregate state from inner contents to outer
338// contents, then that propagation will gather transitive descendants without
339// need for this helper to do so. In fact, in such cases recursing on inner
340// contents here would make that operation quadratic rather than linear.
341template <typename Functor>
342bool AnyInnerWebContents(WebContents* web_contents, const Functor& f) {
343 const auto& inner_contents = web_contents->GetInnerWebContents();
344 return std::any_of(inner_contents.begin(), inner_contents.end(), f);
345}
346
Xuehui Xieb2300ae42020-06-09 20:25:05347std::vector<RenderFrameHost*> GetAllFramesImpl(FrameTree& frame_tree,
348 bool include_pending) {
349 std::vector<RenderFrameHost*> frame_hosts;
350 for (FrameTreeNode* node : frame_tree.Nodes()) {
351 frame_hosts.push_back(node->current_frame_host());
352 if (include_pending) {
353 RenderFrameHostImpl* pending_frame_host =
354 node->render_manager()->speculative_frame_host();
355 if (pending_frame_host)
356 frame_hosts.push_back(pending_frame_host);
357 }
358 }
359 return frame_hosts;
360}
361
362int SendToAllFramesImpl(FrameTree& frame_tree,
363 bool include_pending,
364 IPC::Message* message) {
365 int number_of_messages = 0;
366 std::vector<RenderFrameHost*> frame_hosts =
367 GetAllFramesImpl(frame_tree, include_pending);
368 for (RenderFrameHost* rfh : frame_hosts) {
369 if (!rfh->IsRenderFrameLive())
370 continue;
371
372 ++number_of_messages;
373 IPC::Message* message_copy = new IPC::Message(*message);
374 message_copy->set_routing_id(rfh->GetRoutingID());
375 rfh->Send(message_copy);
376 }
377 delete message;
378 return number_of_messages;
379}
380
Avi Drissman33972942020-06-19 14:16:01381// Returns the set of all WebContentses that are reachable from |web_contents|
382// by applying some combination of WebContents::GetOriginalOpener() and
383// WebContents::GetOuterWebContents(). The |web_contents| parameter will be
384// included in the returned set.
385base::flat_set<WebContentsImpl*> GetAllOpeningWebContents(
386 WebContentsImpl* web_contents) {
387 base::flat_set<WebContentsImpl*> result;
388 base::flat_set<WebContentsImpl*> current;
389
390 current.insert(web_contents);
391
392 while (!current.empty()) {
393 WebContentsImpl* current_contents = *current.begin();
394 current.erase(current.begin());
395 auto insert_result = result.insert(current_contents);
396
397 if (insert_result.second) {
398 RenderFrameHostImpl* opener_rfh = current_contents->GetOriginalOpener();
399 if (opener_rfh) {
400 current.insert(static_cast<WebContentsImpl*>(
401 WebContents::FromRenderFrameHost(opener_rfh)));
402 }
403
404 WebContentsImpl* outer_contents = current_contents->GetOuterWebContents();
405 if (outer_contents)
406 current.insert(outer_contents);
407 }
408 }
409
410 return result;
411}
412
Rakina Zata Amni4029b6d2020-07-28 02:36:20413#if defined(OS_ANDROID)
414float GetDeviceScaleAdjustment(int min_width) {
415 static const float kMinFSM = 1.05f;
416 static const int kWidthForMinFSM = 320;
417 static const float kMaxFSM = 1.3f;
418 static const int kWidthForMaxFSM = 800;
419
420 if (min_width <= kWidthForMinFSM)
421 return kMinFSM;
422 if (min_width >= kWidthForMaxFSM)
423 return kMaxFSM;
424
425 // The font scale multiplier varies linearly between kMinFSM and kMaxFSM.
426 float ratio = static_cast<float>(min_width - kWidthForMinFSM) /
427 (kWidthForMaxFSM - kWidthForMinFSM);
428 return ratio * (kMaxFSM - kMinFSM) + kMinFSM;
429}
430#endif
431
Avi Drissman33972942020-06-19 14:16:01432// Used to attach the "set of fullscreen contents" to a browser context. Storing
433// sets of WebContents on their browser context is done for two reasons. One,
434// related WebContentses must necessarily share a browser context, so this saves
435// lookup time by restricting to one specific browser context. Two, separating
436// by browser context is preemptive paranoia about keeping things separate.
437class FullscreenContentsHolder : public base::SupportsUserData::Data {
438 public:
439 FullscreenContentsHolder() = default;
440 ~FullscreenContentsHolder() override = default;
441
442 FullscreenContentsHolder(const FullscreenContentsHolder&) = delete;
443 FullscreenContentsHolder& operator=(const FullscreenContentsHolder&) = delete;
444
445 base::flat_set<WebContentsImpl*>* set() { return &set_; }
446
447 private:
448 base::flat_set<WebContentsImpl*> set_;
449};
450
451const char kFullscreenContentsSet[] = "fullscreen-contents";
452
453base::flat_set<WebContentsImpl*>* FullscreenContentsSet(
454 BrowserContext* browser_context) {
455 auto* set_holder = static_cast<FullscreenContentsHolder*>(
456 browser_context->GetUserData(kFullscreenContentsSet));
457 if (!set_holder) {
458 auto new_holder = std::make_unique<FullscreenContentsHolder>();
459 set_holder = new_holder.get();
460 browser_context->SetUserData(kFullscreenContentsSet, std::move(new_holder));
461 }
462
463 return set_holder->set();
464}
465
Mike Wasserman5b7d3bf2020-08-21 21:52:26466// Returns true if |host| has the Window Placement permission granted.
467bool WindowPlacementGranted(RenderFrameHost* host) {
468 auto* controller =
469 PermissionControllerImpl::FromBrowserContext(host->GetBrowserContext());
470 return controller && controller->GetPermissionStatusForFrame(
471 PermissionType::WINDOW_PLACEMENT, host,
472 host->GetLastCommittedURL()) ==
473 blink::mojom::PermissionStatus::GRANTED;
474}
475
Mike Wassermanb6bc0152020-08-25 22:46:20476// Adjust the requested |bounds| for opening or placing a window and return the
477// id of the display where the window will be placed. The bounds may not extend
478// outside a single screen's work area, and the |host| requires permission to
479// specify bounds on a screen other than its current screen.
Mike Wassermandabad612020-08-13 04:26:27480// TODO(crbug.com/897300): These adjustments are inaccurate for window.open(),
481// which specifies the inner content size, and for window.moveTo, resizeTo, etc.
482// calls on newly created windows, which may pass empty sizes or positions to
483// indicate uninitialized placement information in the renderer. Constraints
484// enforced later should resolve most inaccuracies, but this early enforcement
485// is needed to ensure bounds indicate the appropriate display.
Mike Wassermanb6bc0152020-08-25 22:46:20486int64_t AdjustRequestedWindowBounds(gfx::Rect* bounds, RenderFrameHost* host) {
Mike Wassermandabad612020-08-13 04:26:27487 auto* screen = display::Screen::GetScreen();
Mike Wassermanb6bc0152020-08-25 22:46:20488 auto display = screen->GetDisplayMatching(*bounds);
Mike Wassermandabad612020-08-13 04:26:27489
490 // Check, but do not prompt, for permission to place windows on other screens.
491 // Sites generally need permission to get such bounds in the first place.
492 // Also clamp offscreen bounds to the window's current screen.
Mike Wassermanb6bc0152020-08-25 22:46:20493 if (!bounds->Intersects(display.bounds()) || !WindowPlacementGranted(host))
Mike Wassermandabad612020-08-13 04:26:27494 display = screen->GetDisplayNearestView(host->GetNativeView());
Mike Wassermandabad612020-08-13 04:26:27495
Mike Wassermanb6bc0152020-08-25 22:46:20496 bounds->AdjustToFit(display.work_area());
497 return display.id();
Mike Wassermandabad612020-08-13 04:26:27498}
499
lukasza6f8ac622017-06-06 03:10:20500} // namespace
501
Joel Hockey8c2011b22020-04-30 05:07:19502CreatedWindow::CreatedWindow() = default;
503CreatedWindow::CreatedWindow(std::unique_ptr<WebContentsImpl> contents,
504 GURL target_url)
505 : contents(std::move(contents)), target_url(std::move(target_url)) {}
506CreatedWindow::~CreatedWindow() = default;
507CreatedWindow::CreatedWindow(CreatedWindow&&) = default;
508CreatedWindow& CreatedWindow::operator=(CreatedWindow&&) = default;
509
Erik Chenbb8e738e2018-04-28 14:10:43510std::unique_ptr<WebContents> WebContents::Create(
511 const WebContents::CreateParams& params) {
Albert J. Wong65fe64d2019-09-20 02:48:14512 return WebContentsImpl::Create(params);
513}
514
515std::unique_ptr<WebContentsImpl> WebContentsImpl::Create(
516 const CreateParams& params) {
517 return CreateWithOpener(params, FindOpenerRFH(params));
[email protected]d1198fd2012-08-13 22:50:19518}
519
erikchenade1fef2018-05-02 22:07:57520std::unique_ptr<WebContents> WebContents::CreateWithSessionStorage(
[email protected]54944cde2012-12-09 09:24:59521 const WebContents::CreateParams& params,
[email protected]fdac6ade2013-07-20 01:06:30522 const SessionStorageNamespaceMap& session_storage_namespace_map) {
Alexander Timin5fdeff22020-09-08 09:20:37523 OPTIONAL_TRACE_EVENT0("content", "WebContents::CreateWithSessionStorage");
erikchenade1fef2018-05-02 22:07:57524 std::unique_ptr<WebContentsImpl> new_contents(
525 new WebContentsImpl(params.browser_context));
Ian Clelland5cbaaf82017-11-27 22:00:03526 RenderFrameHostImpl* opener_rfh = FindOpenerRFH(params);
527 FrameTreeNode* opener = nullptr;
528 if (opener_rfh)
529 opener = opener_rfh->frame_tree_node();
530 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
[email protected]fdac6ade2013-07-20 01:06:30531
jdoerrie55ec69d2018-10-08 13:34:46532 for (auto it = session_storage_namespace_map.begin();
533 it != session_storage_namespace_map.end(); ++it) {
Fergal Daly09d6c762020-05-29 02:05:18534 new_contents->GetController().SetSessionStorageNamespace(it->first,
535 it->second.get());
[email protected]fdac6ade2013-07-20 01:06:30536 }
537
Sean Toppingbbc4a2bd2019-01-30 02:16:14538 WebContentsImpl* outer_web_contents = nullptr;
Sam McNally69a33772018-06-27 16:54:12539 if (params.guest_delegate) {
540 // This makes |new_contents| act as a guest.
541 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:04542 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
543 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:14544 outer_web_contents = static_cast<WebContentsImpl*>(
545 params.guest_delegate->GetOwnerWebContents());
Sam McNally69a33772018-06-27 16:54:12546 }
547
[email protected]54944cde2012-12-09 09:24:59548 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:14549 if (outer_web_contents)
550 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:19551 return new_contents;
[email protected]a81343d232011-12-27 07:39:20552}
[email protected]746d3052012-05-22 15:15:47553
benwells5e7260d2017-03-20 23:36:33554void WebContentsImpl::FriendWrapper::AddCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37555 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46556 g_created_callbacks.Get().push_back(callback);
557}
558
benwells5e7260d2017-03-20 23:36:33559void WebContentsImpl::FriendWrapper::RemoveCreatedCallbackForTesting(
nickf9acfbe2014-12-23 19:12:37560 const CreatedCallback& callback) {
[email protected]cbb1ef592013-06-05 19:49:46561 for (size_t i = 0; i < g_created_callbacks.Get().size(); ++i) {
Robert Liao1db5a352019-06-05 20:57:34562 if (g_created_callbacks.Get().at(i) == callback) {
[email protected]cbb1ef592013-06-05 19:49:46563 g_created_callbacks.Get().erase(g_created_callbacks.Get().begin() + i);
564 return;
565 }
566 }
567}
568
avidf38c952015-10-27 13:45:13569WebContents* WebContents::FromRenderViewHost(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:37570 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
571 "WebContents::FromRenderViewHost", "render_view_host",
572 rvh);
avidf38c952015-10-27 13:45:13573 if (!rvh)
574 return nullptr;
[email protected]746d3052012-05-22 15:15:47575 return rvh->GetDelegate()->GetAsWebContents();
576}
577
[email protected]a86c0e962013-12-17 17:10:39578WebContents* WebContents::FromRenderFrameHost(RenderFrameHost* rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37579 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
580 "WebContents::FromRenderFrameHost", "render_frame_host",
581 base::trace_event::ToTracedValue(rfh));
avidf38c952015-10-27 13:45:13582 if (!rfh)
583 return nullptr;
Alexander Timin33bd754c02020-03-10 22:50:18584 if (!rfh->IsCurrent() && base::FeatureList::IsEnabled(
585 kCheckWebContentsAccessFromNonCurrentFrame)) {
586 // TODO(crbug.com/1059903): return nullptr here eventually.
587 base::debug::DumpWithoutCrashing();
588 }
avidf38c952015-10-27 13:45:13589 return static_cast<RenderFrameHostImpl*>(rfh)->delegate()->GetAsWebContents();
[email protected]a86c0e962013-12-17 17:10:39590}
591
ananta4b7467a52016-09-23 01:42:38592WebContents* WebContents::FromFrameTreeNodeId(int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:37593 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
594 "WebContents::FromFrameTreeNodeId",
595 "frame_tree_node_id", frame_tree_node_id);
ananta4b7467a52016-09-23 01:42:38596 FrameTreeNode* frame_tree_node =
597 FrameTreeNode::GloballyFindByID(frame_tree_node_id);
anantab8cfa3b2016-10-14 22:43:19598 if (!frame_tree_node)
599 return nullptr;
jam8c4edd02017-05-06 18:50:33600 return WebContentsImpl::FromFrameTreeNode(frame_tree_node);
ananta4b7467a52016-09-23 01:42:38601}
602
leon.han552e9de2017-02-09 14:37:30603void WebContents::SetScreenOrientationDelegate(
604 ScreenOrientationDelegate* delegate) {
605 ScreenOrientationProvider::SetDelegate(delegate);
606}
607
[email protected]7fff43e2013-05-21 20:21:10608// WebContentsImpl::DestructionObserver ----------------------------------------
609
610class WebContentsImpl::DestructionObserver : public WebContentsObserver {
611 public:
612 DestructionObserver(WebContentsImpl* owner, WebContents* watched_contents)
Fergal Daly09d6c762020-05-29 02:05:18613 : WebContentsObserver(watched_contents), owner_(owner) {}
[email protected]7fff43e2013-05-21 20:21:10614
615 // WebContentsObserver:
dchengc2282aa2014-10-21 12:07:58616 void WebContentsDestroyed() override {
[email protected]12a46832014-05-09 13:35:58617 owner_->OnWebContentsDestroyed(
618 static_cast<WebContentsImpl*>(web_contents()));
[email protected]7fff43e2013-05-21 20:21:10619 }
620
621 private:
622 WebContentsImpl* owner_;
623
624 DISALLOW_COPY_AND_ASSIGN(DestructionObserver);
625};
626
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:50627// TODO(sreejakshetty): Make |WebContentsImpl::ColorChooser| per-frame instead
628// of WebContents-owned.
Joel Hockey85b379d2017-12-11 10:42:13629// WebContentsImpl::ColorChooser ----------------------------------------------
Joel Hockey163835a2017-12-20 11:51:57630class WebContentsImpl::ColorChooser : public blink::mojom::ColorChooser {
Joel Hockey85b379d2017-12-11 10:42:13631 public:
632 ColorChooser(content::ColorChooser* chooser,
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20633 mojo::PendingReceiver<blink::mojom::ColorChooser> receiver,
634 mojo::PendingRemote<blink::mojom::ColorChooserClient> client)
Joel Hockey85b379d2017-12-11 10:42:13635 : chooser_(chooser),
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20636 receiver_(this, std::move(receiver)),
Joel Hockey85b379d2017-12-11 10:42:13637 client_(std::move(client)) {
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20638 receiver_.set_disconnect_handler(
Joel Hockey85b379d2017-12-11 10:42:13639 base::BindOnce([](content::ColorChooser* chooser) { chooser->End(); },
640 base::Unretained(chooser)));
641 }
[email protected]8ed16472014-04-11 19:02:48642
Joel Hockey85b379d2017-12-11 10:42:13643 ~ColorChooser() override { chooser_->End(); }
[email protected]8ed16472014-04-11 19:02:48644
Joel Hockey85b379d2017-12-11 10:42:13645 void SetSelectedColor(SkColor color) override {
Alexander Timin5fdeff22020-09-08 09:20:37646 OPTIONAL_TRACE_EVENT0("content",
647 "WebContentsImpl::ColorChooser::SetSelectedColor");
Joel Hockey85b379d2017-12-11 10:42:13648 chooser_->SetSelectedColor(color);
649 }
650
651 void DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:37652 OPTIONAL_TRACE_EVENT0(
653 "content",
654 "WebContentsImpl::ColorChooser::DidChooseColorInColorChooser");
Joel Hockey85b379d2017-12-11 10:42:13655 client_->DidChooseColor(color);
656 }
657
658 private:
659 // Color chooser that was opened by this tab.
660 std::unique_ptr<content::ColorChooser> chooser_;
661
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20662 // mojo receiver.
663 mojo::Receiver<blink::mojom::ColorChooser> receiver_;
Joel Hockey85b379d2017-12-11 10:42:13664
665 // mojo renderer client.
Julie Jeongeun Kim8e2879e2019-08-06 23:55:20666 mojo::Remote<blink::mojom::ColorChooserClient> client_;
Joel Hockey85b379d2017-12-11 10:42:13667};
nicka0ac8382016-12-15 23:59:23668
lazyboy6ec48b2a2015-06-29 15:18:14669// WebContentsImpl::WebContentsTreeNode ----------------------------------------
lfg601233692017-03-06 22:45:44670WebContentsImpl::WebContentsTreeNode::WebContentsTreeNode(
671 WebContentsImpl* current_web_contents)
672 : current_web_contents_(current_web_contents),
673 outer_web_contents_(nullptr),
lazyboy6ec48b2a2015-06-29 15:18:14674 outer_contents_frame_tree_node_id_(
avallee0206f782016-07-28 18:55:33675 FrameTreeNode::kFrameTreeNodeInvalidId),
lfg601233692017-03-06 22:45:44676 focused_web_contents_(current_web_contents) {}
lazyboy6ec48b2a2015-06-29 15:18:14677
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18678WebContentsImpl::WebContentsTreeNode::~WebContentsTreeNode() {}
lazyboy6ec48b2a2015-06-29 15:18:14679
Lucas Furukawa Gadani99125822019-01-03 15:41:49680std::unique_ptr<WebContents>
681WebContentsImpl::WebContentsTreeNode::DisconnectFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:37682 OPTIONAL_TRACE_EVENT0("content",
683 "WebContentsTreeNode::DisconnectFromOuterWebContents");
Lucas Furukawa Gadani99125822019-01-03 15:41:49684 std::unique_ptr<WebContents> inner_contents =
685 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
686 OuterContentsFrameTreeNode()->RemoveObserver(this);
687 outer_contents_frame_tree_node_id_ = FrameTreeNode::kFrameTreeNodeInvalidId;
688 outer_web_contents_ = nullptr;
689 return inner_contents;
690}
691
paulmeyerfeafc2d2017-04-25 21:46:40692void WebContentsImpl::WebContentsTreeNode::AttachInnerWebContents(
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50693 std::unique_ptr<WebContents> inner_web_contents,
694 RenderFrameHostImpl* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:37695 OPTIONAL_TRACE_EVENT0("content",
696 "WebContentsTreeNode::AttachInnerWebContents");
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50697 WebContentsImpl* inner_web_contents_impl =
698 static_cast<WebContentsImpl*>(inner_web_contents.get());
699 WebContentsTreeNode& inner_web_contents_node = inner_web_contents_impl->node_;
700
701 inner_web_contents_node.focused_web_contents_ = nullptr;
702 inner_web_contents_node.outer_web_contents_ = current_web_contents_;
703 inner_web_contents_node.outer_contents_frame_tree_node_id_ =
704 render_frame_host->frame_tree_node()->frame_tree_node_id();
705
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18706 inner_web_contents_.push_back(std::move(inner_web_contents));
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:50707
708 render_frame_host->frame_tree_node()->AddObserver(&inner_web_contents_node);
Jeremy Roman03ce13ce2020-05-29 22:16:57709 current_web_contents_->InnerWebContentsAttached(inner_web_contents_impl);
paulmeyerfeafc2d2017-04-25 21:46:40710}
711
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18712std::unique_ptr<WebContents>
713WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents(
paulmeyerfeafc2d2017-04-25 21:46:40714 WebContentsImpl* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:37715 OPTIONAL_TRACE_EVENT0(
716 "content",
717 "WebContentsImpl::WebContentsTreeNode::DetachInnerWebContents");
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18718 std::unique_ptr<WebContents> detached_contents;
719 for (std::unique_ptr<WebContents>& web_contents : inner_web_contents_) {
720 if (web_contents.get() == inner_web_contents) {
721 detached_contents = std::move(web_contents);
722 std::swap(web_contents, inner_web_contents_.back());
723 inner_web_contents_.pop_back();
Jeremy Roman03ce13ce2020-05-29 22:16:57724 current_web_contents_->InnerWebContentsDetached(inner_web_contents);
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18725 return detached_contents;
726 }
727 }
728
729 NOTREACHED();
730 return nullptr;
paulmeyerfeafc2d2017-04-25 21:46:40731}
732
lfga3e2bdc2017-03-07 20:44:01733FrameTreeNode*
734WebContentsImpl::WebContentsTreeNode::OuterContentsFrameTreeNode() const {
735 return FrameTreeNode::GloballyFindByID(outer_contents_frame_tree_node_id_);
lfg601233692017-03-06 22:45:44736}
737
lfga3e2bdc2017-03-07 20:44:01738void WebContentsImpl::WebContentsTreeNode::OnFrameTreeNodeDestroyed(
739 FrameTreeNode* node) {
Alexander Timin5fdeff22020-09-08 09:20:37740 OPTIONAL_TRACE_EVENT0("content",
741 "WebContentsTreeNode::OnFrameTreeNodeDestroyed");
lfga3e2bdc2017-03-07 20:44:01742 DCHECK_EQ(outer_contents_frame_tree_node_id_, node->frame_tree_node_id())
743 << "WebContentsTreeNode should only receive notifications for the "
744 "FrameTreeNode in its outer WebContents that hosts it.";
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18745
746 // Deletes |this| too.
747 outer_web_contents_->node_.DetachInnerWebContents(current_web_contents_);
lazyboy6ec48b2a2015-06-29 15:18:14748}
749
avallee0206f782016-07-28 18:55:33750void WebContentsImpl::WebContentsTreeNode::SetFocusedWebContents(
751 WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:37752 OPTIONAL_TRACE_EVENT0("content",
753 "WebContentsTreeNode::SetFocusedWebContents");
avallee0206f782016-07-28 18:55:33754 DCHECK(!outer_web_contents())
755 << "Only the outermost WebContents tracks focus.";
756 focused_web_contents_ = web_contents;
757}
758
paulmeyerfeafc2d2017-04-25 21:46:40759WebContentsImpl*
760WebContentsImpl::WebContentsTreeNode::GetInnerWebContentsInFrame(
761 const FrameTreeNode* frame) {
762 auto ftn_id = frame->frame_tree_node_id();
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18763 for (auto& contents : inner_web_contents_) {
764 WebContentsImpl* impl = static_cast<WebContentsImpl*>(contents.get());
765 if (impl->node_.outer_contents_frame_tree_node_id() == ftn_id) {
766 return impl;
paulmeyerfeafc2d2017-04-25 21:46:40767 }
768 }
769 return nullptr;
770}
771
Lucas Furukawa Gadani3d38ec152018-10-26 20:55:18772std::vector<WebContentsImpl*>
773WebContentsImpl::WebContentsTreeNode::GetInnerWebContents() const {
774 std::vector<WebContentsImpl*> inner_web_contents;
775 for (auto& contents : inner_web_contents_)
776 inner_web_contents.push_back(static_cast<WebContentsImpl*>(contents.get()));
777
778 return inner_web_contents;
paulmeyerfeafc2d2017-04-25 21:46:40779}
780
Alexander Timin90c20c32020-08-12 15:28:32781// WebContentsObserverList -----------------------------------------------------
782WebContentsImpl::WebContentsObserverList::WebContentsObserverList() = default;
783WebContentsImpl::WebContentsObserverList::~WebContentsObserverList() = default;
784
785void WebContentsImpl::WebContentsObserverList::AddObserver(
786 WebContentsObserver* observer) {
787 observers_.AddObserver(observer);
788}
789
790void WebContentsImpl::WebContentsObserverList::RemoveObserver(
791 WebContentsObserver* observer) {
792 observers_.RemoveObserver(observer);
793}
794
[email protected]b172aee2012-04-10 17:05:26795// WebContentsImpl -------------------------------------------------------------
[email protected]420ae012009-04-24 05:16:32796
alexmose201c7cd2015-06-10 17:14:21797WebContentsImpl::WebContentsImpl(BrowserContext* browser_context)
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28798 : delegate_(nullptr),
[email protected]69e797f2013-04-30 01:10:22799 controller_(this, browser_context),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28800 render_view_host_delegate_view_(nullptr),
alexmose201c7cd2015-06-10 17:14:21801 created_with_opener_(false),
Lucas Furukawa Gadani99125822019-01-03 15:41:49802 node_(this),
Fergal Daly09d6c762020-05-29 02:05:18803 frame_tree_(&controller_, this, this, this, this, this),
[email protected]6dfed692014-05-22 04:18:03804 is_load_to_different_document_(false),
[email protected]443b80e2010-12-14 00:42:23805 crashed_status_(base::TERMINATION_STATUS_STILL_RUNNING),
806 crashed_error_code_(0),
[email protected]d5f942ba2008-09-26 19:30:34807 waiting_for_response_(false),
[email protected]fcf75d42013-12-03 20:11:26808 load_state_(net::LOAD_STATE_IDLE, base::string16()),
[email protected]094e5b22009-09-25 04:23:56809 upload_size_(0),
810 upload_position_(0),
dfalcantarae6b7b46752015-07-10 18:14:16811 is_resume_pending_(false),
[email protected]b4c84012014-04-28 19:51:10812 has_accessed_initial_document_(false),
Collin Bakerc5259962019-11-14 17:51:58813 visible_capturer_count_(0),
814 hidden_capturer_count_(0),
[email protected]fdd61c62009-04-22 19:22:57815 is_being_destroyed_(false),
816 notify_disconnection_(false),
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28817 dialog_manager_(nullptr),
[email protected]7ab1e7d62009-10-14 23:32:01818 is_showing_before_unload_dialog_(false),
gab0dccfef2015-05-20 18:43:39819 last_active_time_(base::TimeTicks::Now()),
[email protected]ebf40a72010-07-22 01:46:38820 closed_by_user_gesture_(false),
danakj938b37a62019-09-24 18:35:54821 minimum_zoom_percent_(
822 static_cast<int>(blink::kMinimumPageZoomFactor * 100)),
823 maximum_zoom_percent_(
824 static_cast<int>(blink::kMaximumPageZoomFactor * 100)),
w.shackleton49bcd392016-01-06 17:38:22825 zoom_scroll_remainder_(0),
alexmosc9e76ec2016-05-16 22:59:37826 fullscreen_widget_process_id_(ChildProcessHost::kInvalidUniqueID),
[email protected]5dcaf8e2013-12-28 01:31:42827 fullscreen_widget_routing_id_(MSG_ROUTING_NONE),
[email protected]0b431992014-06-24 00:08:03828 fullscreen_widget_had_focus_at_shutdown_(false),
[email protected]34ff1cfc2014-08-20 06:16:05829 force_disable_overscroll_content_(false),
[email protected]95640212014-07-26 18:14:30830 last_dialog_suppressed_(false),
waffles1c12bf402016-02-10 17:45:48831 accessibility_mode_(
Dominic Mazzoni21fb0282019-02-13 18:32:47832 GetContentClient()->browser()->GetAXModeForBrowserContext(
833 browser_context)),
avayvodcc85bbd2015-08-28 19:11:15834 audio_stream_monitor_(this),
Thomas Guilbert882c4cec2019-02-14 05:55:45835 media_web_contents_observer_(
836 std::make_unique<MediaWebContentsObserver>(this)),
mcnee336ea2c2017-05-23 22:50:59837#if !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:46838 page_scale_factor_is_one_(true),
mcnee336ea2c2017-05-23 22:50:59839#endif // !defined(OS_ANDROID)
qinmin72e8bd02016-10-21 19:35:37840 is_overlay_content_(false),
ekaramadf6750aa2017-06-06 18:29:42841 showing_context_menu_(false),
W. James MacLean62198672019-06-04 16:46:10842 text_autosizer_page_info_({0, 0, 1.f}),
shivanigithubcceeacf2020-03-06 20:00:27843 native_theme_observer_(this) {
Alexander Timin5fdeff22020-09-08 09:20:37844 TRACE_EVENT0("content", "WebContentsImpl::WebContentsImpl");
danakjf4b9e942019-11-29 15:43:04845 frame_tree_.SetFrameRemoveListener(base::BindRepeating(
846 &WebContentsImpl::OnFrameRemoved, base::Unretained(this)));
brettw4b461082016-11-19 18:55:16847#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17848 pepper_playback_observer_.reset(new PepperPlaybackObserver(this));
849#endif
blundelle75a8f92017-03-27 08:11:17850
Becca Hughes86334622018-07-09 21:29:38851#if defined(OS_ANDROID)
Elly Fong-Jonescdd7ae82019-02-20 23:26:33852 display_cutout_host_impl_ = std::make_unique<DisplayCutoutHostImpl>(this);
Becca Hughes86334622018-07-09 21:29:38853#endif
John Delaney732721e92020-02-07 23:11:27854
Alison Maher7f366dc62020-03-03 19:46:00855 ui::NativeTheme* native_theme = ui::NativeTheme::GetInstanceForWeb();
856 native_theme_observer_.Add(native_theme);
857 using_dark_colors_ = native_theme->ShouldUseDarkColors();
858 preferred_color_scheme_ = native_theme->GetPreferredColorScheme();
859
Mike Wassermanb213b9352020-04-16 00:32:34860 screen_change_monitor_ =
861 std::make_unique<ScreenChangeMonitor>(base::BindRepeating(
862 &WebContentsImpl::OnScreensChange, base::Unretained(this)));
863
John Delaney732721e92020-02-07 23:11:27864 // ConversionHost takes a weak ref on |this|, so it must be created outside of
865 // the initializer list.
Charlie Harrison405f6212020-04-14 21:57:32866 if (base::FeatureList::IsEnabled(features::kConversionMeasurement)) {
867 conversion_host_ = std::make_unique<ConversionHost>(this);
868 }
[email protected]332af7732009-03-11 13:21:35869}
initial.commit09911bf2008-07-26 23:55:29870
[email protected]b172aee2012-04-10 17:05:26871WebContentsImpl::~WebContentsImpl() {
Alexander Timin5fdeff22020-09-08 09:20:37872 TRACE_EVENT0("content", "WebContentsImpl::~WebContentsImpl");
873
creisba91ba82017-05-12 22:56:19874 // Imperfect sanity check against double free, given some crashes unexpectedly
875 // observed in the wild.
876 CHECK(!is_being_destroyed_);
877
878 // We generally keep track of is_being_destroyed_ to let other features know
879 // to avoid certain actions during destruction.
[email protected]420ae012009-04-24 05:16:32880 is_being_destroyed_ = true;
881
creis97867aa2017-02-17 18:39:45882 // A WebContents should never be deleted while it is notifying observers,
creisba91ba82017-05-12 22:56:19883 // since this will lead to a use-after-free as it continues to notify later
creis97867aa2017-02-17 18:39:45884 // observers.
Alexander Timin90c20c32020-08-12 15:28:32885 CHECK(!observers_.is_notifying_observers());
creis97867aa2017-02-17 18:39:45886
Avi Drissman33972942020-06-19 14:16:01887 FullscreenContentsSet(GetBrowserContext())->erase(this);
888
kenrb2a565f82015-09-02 20:24:59889 rwh_input_event_router_.reset();
890
Julie Jeongeun Kim7d0986172019-12-04 03:17:25891 for (auto& entry : receiver_sets_)
892 entry.second->CloseAllReceivers();
rockotf62002a2016-09-15 00:08:59893
avallee0206f782016-07-28 18:55:33894 WebContentsImpl* outermost = GetOutermostWebContents();
avallee9993fca2016-11-17 06:16:50895 if (this != outermost && ContainsOrIsFocusedWebContents()) {
avallee0206f782016-07-28 18:55:33896 // If the current WebContents is in focus, unset it.
avallee9993fca2016-11-17 06:16:50897 outermost->SetAsFocusedWebContentsIfNecessary();
avallee0206f782016-07-28 18:55:33898 }
899
Nick Carterd73635b2018-03-13 18:31:41900 if (mouse_lock_widget_)
James Hollyerd5c9de462020-03-10 19:02:45901 mouse_lock_widget_->RejectMouseLockOrUnlockIfNecessary(
902 blink::mojom::PointerLockResult::kElementDestroyed);
Nick Carterd73635b2018-03-13 18:31:41903
dcheng72be33c2016-01-21 04:11:31904 for (FrameTreeNode* node : frame_tree_.Nodes()) {
905 // Delete all RFHs pending shutdown, which will lead the corresponding RVHs
906 // to be shutdown and be deleted as well.
dcheng57e39e22016-01-21 00:25:38907 node->render_manager()->ClearRFHsPendingShutdown();
dcheng57e39e22016-01-21 00:25:38908 node->render_manager()->ClearWebUIInstances();
dcheng72be33c2016-01-21 04:11:31909 }
carlosk35f35af2015-12-01 10:55:40910
dcheng57e39e22016-01-21 00:25:38911 for (RenderWidgetHostImpl* widget : created_widgets_)
912 widget->DetachDelegate();
[email protected]b24b68a2012-09-24 21:57:26913 created_widgets_.clear();
914
[email protected]3ab9cb82011-06-03 18:02:07915 // Clear out any JavaScript state.
avi5d3b8692016-10-12 22:00:46916 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:53917 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:46918 }
[email protected]3ab9cb82011-06-03 18:02:07919
Joel Hockey85b379d2017-12-11 10:42:13920 color_chooser_.reset();
Rakina Zata Amni16196122018-11-14 02:14:00921 find_request_manager_.reset();
[email protected]da8543762012-03-20 08:52:20922
[email protected]420ae012009-04-24 05:16:32923 NotifyDisconnected();
[email protected]420ae012009-04-24 05:16:32924
[email protected]ca13a442012-04-17 14:00:12925 // Notify any observer that have a reference on this WebContents.
[email protected]8ff00d72012-10-23 19:12:21926 NotificationService::current()->Notify(
927 NOTIFICATION_WEB_CONTENTS_DESTROYED,
928 Source<WebContents>(this),
929 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:32930
Arthur Sonzogni5a9a88c2018-10-18 13:16:00931 // Destroy all subframes now. This notifies observers.
932 GetMainFrame()->ResetChildren();
[email protected]df0c843f2014-05-23 20:37:23933 GetRenderManager()->ResetProxyHosts();
[email protected]c06c58c2014-03-12 20:31:59934
clamy0e119882015-07-31 16:12:33935 // Manually call the observer methods for the root frame tree node. It is
936 // necessary to manually delete all objects tracking navigations
937 // (NavigationHandle, NavigationRequest) for observers to be properly
938 // notified of these navigations stopping before the WebContents is
939 // destroyed.
[email protected]df0c843f2014-05-23 20:37:23940 RenderFrameHostManager* root = GetRenderManager();
naskob21fe4872015-02-24 14:15:56941
Lowell Manners20250112019-10-18 15:06:15942 GetController().GetBackForwardCache().Shutdown();
943
naskob21fe4872015-02-24 14:15:56944 root->current_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28945 root->current_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33946
Arthur Hemeryc3380172018-01-22 14:00:17947 // Do not update state as the WebContents is being destroyed.
Arthur Hemery241b9392019-10-24 11:08:41948 frame_tree_.root()->ResetNavigationRequest(true);
Arthur Hemeryc3380172018-01-22 14:00:17949 if (root->speculative_frame_host()) {
danakjf2342432019-05-15 21:46:09950 root->speculative_frame_host()->DeleteRenderFrame(
951 FrameDeleteIntention::kSpeculativeMainFrameForShutdown);
Arthur Hemeryc3380172018-01-22 14:00:17952 root->speculative_frame_host()->SetRenderFrameCreated(false);
clamyfc3850d2018-02-23 14:35:28953 root->speculative_frame_host()->ResetNavigationRequests();
clamy0e119882015-07-31 16:12:33954 }
[email protected]f273ee52013-10-18 16:05:27955
brettw4b461082016-11-19 18:55:16956#if BUILDFLAG(ENABLE_PLUGINS)
zqzhang181047e62016-07-01 13:37:17957 // Call this before WebContentsDestroyed() is broadcasted since
958 // AudioFocusManager will be destroyed after that.
959 pepper_playback_observer_.reset();
960#endif // defined(ENABLED_PLUGINS)
961
Chris Hamiltondf0d72cd2018-05-29 16:23:53962 // If audio is playing then notify external observers of the audio stream
963 // disappearing.
964 if (is_currently_audible_) {
965 is_currently_audible_ = false;
Alexander Timin90c20c32020-08-12 15:28:32966 observers_.ForEachObserver([&](WebContentsObserver* observer) {
967 observer->OnAudioStateChanged(false);
968 });
Chris Hamiltondf0d72cd2018-05-29 16:23:53969 if (GetOuterWebContents())
970 GetOuterWebContents()->OnAudioStateChanged();
971 }
972
Alexander Timin90c20c32020-08-12 15:28:32973 observers_.ForEachObserver([&](WebContentsObserver* observer) {
974 observer->FrameDeleted(root->current_frame_host());
975 });
976 observers_.ForEachObserver([&](WebContentsObserver* observer) {
977 observer->RenderViewDeleted(root->current_host());
978 });
Kevin McNee576bb5d82019-05-29 16:47:51979#if defined(OS_ANDROID)
980 // For simplicity, destroy the Java WebContents before we notify of the
981 // destruction of the WebContents.
982 ClearWebContentsAndroid();
983#endif
984
Alexander Timin90c20c32020-08-12 15:28:32985 observers_.ForEachObserver(
986 [&](WebContentsObserver* observer) { observer->WebContentsDestroyed(); });
Becca Hughesd11d6502018-07-31 17:01:28987 if (display_cutout_host_impl_)
988 display_cutout_host_impl_->WebContentsDestroyed();
989
Alexander Timin90c20c32020-08-12 15:28:32990 observers_.ForEachObserver(
991 [&](WebContentsObserver* observer) { observer->ResetWebContents(); });
Ivan Kotenkov2c0d2bb32017-11-01 15:41:28992 SetDelegate(nullptr);
[email protected]b5a1d11c2011-02-17 03:09:42993}
994
erikchen50735fd2018-05-05 15:08:33995std::unique_ptr<WebContentsImpl> WebContentsImpl::CreateWithOpener(
[email protected]54944cde2012-12-09 09:24:59996 const WebContents::CreateParams& params,
Ian Clelland5cbaaf82017-11-27 22:00:03997 RenderFrameHostImpl* opener_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:37998 OPTIONAL_TRACE_EVENT1("browser", "WebContentsImpl::CreateWithOpener",
999 "opener", base::trace_event::ToTracedValue(opener_rfh));
Ian Clelland5cbaaf82017-11-27 22:00:031000 FrameTreeNode* opener = nullptr;
1001 if (opener_rfh)
1002 opener = opener_rfh->frame_tree_node();
erikchen50735fd2018-05-05 15:08:331003 std::unique_ptr<WebContentsImpl> new_contents(
1004 new WebContentsImpl(params.browser_context));
lukasza6f8ac622017-06-06 03:10:201005 new_contents->SetOpenerForNewContents(opener, params.opener_suppressed);
alexmose201c7cd2015-06-10 17:14:211006
alexmosaedfc6f2016-01-21 23:57:381007 // If the opener is sandboxed, a new popup must inherit the opener's sandbox
1008 // flags, and these flags take effect immediately. An exception is if the
1009 // opener's sandbox flags lack the PropagatesToAuxiliaryBrowsingContexts
1010 // bit (which is controlled by the "allow-popups-to-escape-sandbox" token).
1011 // See https://html.spec.whatwg.org/#attr-iframe-sandbox.
lukasza6f8ac622017-06-06 03:10:201012 FrameTreeNode* new_root = new_contents->GetFrameTree()->root();
alexmosaedfc6f2016-01-21 23:57:381013 if (opener) {
arthursonzognib93a4472020-04-10 07:38:001014 network::mojom::WebSandboxFlags opener_flags =
Antonio Gomes7096ac02020-02-14 14:29:541015 opener_rfh->active_sandbox_flags();
arthursonzognib93a4472020-04-10 07:38:001016 const network::mojom::WebSandboxFlags inherit_flag =
1017 network::mojom::WebSandboxFlags::kPropagatesToAuxiliaryBrowsingContexts;
Ehsan Karamad39407082019-02-19 23:38:191018 bool sandbox_propagates_to_auxilary_context =
1019 (opener_flags & inherit_flag) == inherit_flag;
1020 if (sandbox_propagates_to_auxilary_context)
Charlie Hue1b77ac2019-12-13 21:30:171021 new_root->SetPendingFramePolicy({opener_flags,
1022 {} /* container_policy */,
1023 {} /* required_document_policy */});
arthursonzognib93a4472020-04-10 07:38:001024 if (opener_flags == network::mojom::WebSandboxFlags::kNone ||
Ehsan Karamad39407082019-02-19 23:38:191025 sandbox_propagates_to_auxilary_context) {
1026 // TODO(ekaramad, iclelland): Do not propagate feature policies from non-
1027 // sandboxed disowned openers (rel=noopener).
1028 // If the current page is not sandboxed, or if the sandbox is to propagate
1029 // to the popups then opener's feature policy will apply to the new popup
1030 // as well.
1031 new_root->SetOpenerFeaturePolicyState(
Ehsan Karamad34d10682019-02-26 20:55:041032 opener_rfh->feature_policy()->GetFeatureState());
alexmosaedfc6f2016-01-21 23:57:381033 }
1034 }
1035
mark a. foltzef394fce2017-10-21 09:11:021036 // Apply starting sandbox flags.
Luna Luc3fdacdf2017-11-08 04:48:531037 blink::FramePolicy frame_policy(new_root->pending_frame_policy());
mark a. foltzef394fce2017-10-21 09:11:021038 frame_policy.sandbox_flags |= params.starting_sandbox_flags;
1039 new_root->SetPendingFramePolicy(frame_policy);
Charlie Hu5ffc0152019-12-06 15:59:531040 new_root->CommitFramePolicy(frame_policy);
mark a. foltzef394fce2017-10-21 09:11:021041
alexmose201c7cd2015-06-10 17:14:211042 // This may be true even when opener is null, such as when opening blocked
1043 // popups.
alexmos090fae8e2015-05-28 17:09:281044 if (params.created_with_opener)
1045 new_contents->created_with_opener_ = true;
1046
Sean Toppingbbc4a2bd2019-01-30 02:16:141047 WebContentsImpl* outer_web_contents = nullptr;
[email protected]4858e432014-06-23 18:14:171048 if (params.guest_delegate) {
[email protected]83100cd2014-05-10 11:50:061049 // This makes |new_contents| act as a guest.
1050 // For more info, see comment above class BrowserPluginGuest.
Albert J. Wongc55cc64d2018-10-12 02:50:041051 BrowserPluginGuest::CreateInWebContents(new_contents.get(),
1052 params.guest_delegate);
Sean Toppingbbc4a2bd2019-01-30 02:16:141053 outer_web_contents = static_cast<WebContentsImpl*>(
1054 params.guest_delegate->GetOwnerWebContents());
[email protected]83100cd2014-05-10 11:50:061055 }
mark a. foltzef394fce2017-10-21 09:11:021056
[email protected]54944cde2012-12-09 09:24:591057 new_contents->Init(params);
Sean Toppingbbc4a2bd2019-01-30 02:16:141058 if (outer_web_contents)
1059 outer_web_contents->InnerWebContentsCreated(new_contents.get());
[email protected]d1198fd2012-08-13 22:50:191060 return new_contents;
1061}
1062
[email protected]95640212014-07-26 18:14:301063// static
1064std::vector<WebContentsImpl*> WebContentsImpl::GetAllWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:371065 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1066 "WebContentsImpl::GetAllWebContents");
[email protected]95640212014-07-26 18:14:301067 std::vector<WebContentsImpl*> result;
dcheng59716272016-04-09 05:19:081068 std::unique_ptr<RenderWidgetHostIterator> widgets(
[email protected]95640212014-07-26 18:14:301069 RenderWidgetHostImpl::GetRenderWidgetHosts());
[email protected]95640212014-07-26 18:14:301070 while (RenderWidgetHost* rwh = widgets->GetNextHost()) {
[email protected]95640212014-07-26 18:14:301071 RenderViewHost* rvh = RenderViewHost::From(rwh);
1072 if (!rvh)
1073 continue;
1074 WebContents* web_contents = WebContents::FromRenderViewHost(rvh);
1075 if (!web_contents)
1076 continue;
avidf38c952015-10-27 13:45:131077 if (web_contents->GetRenderViewHost() != rvh)
1078 continue;
1079 // Because a WebContents can only have one current RVH at a time, there will
1080 // be no duplicate WebContents here.
1081 result.push_back(static_cast<WebContentsImpl*>(web_contents));
[email protected]95640212014-07-26 18:14:301082 }
1083 return result;
1084}
1085
clamya16aa8172015-05-26 13:07:251086// static
1087WebContentsImpl* WebContentsImpl::FromFrameTreeNode(
paulmeyerfeafc2d2017-04-25 21:46:401088 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371089 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1090 "WebContentsImpl::FromFrameTreeNode", "frame_tree_node",
1091 frame_tree_node);
clamya16aa8172015-05-26 13:07:251092 return static_cast<WebContentsImpl*>(
1093 WebContents::FromRenderFrameHost(frame_tree_node->current_frame_host()));
1094}
1095
clamy0d32d6d2015-11-24 11:16:261096// static
Patrick Monette275a6f92b2020-01-09 21:05:041097WebContents* WebContentsImpl::FromRenderFrameHostID(
1098 GlobalFrameRoutingId render_frame_host_id) {
Alexander Timin5fdeff22020-09-08 09:20:371099 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1100 "WebContentsImpl::FromRenderFrameHostID", "process_id",
1101 render_frame_host_id.child_id, "frame_id",
1102 render_frame_host_id.frame_routing_id);
Patrick Monette275a6f92b2020-01-09 21:05:041103 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI) ||
1104 !BrowserThread::IsThreadInitialized(BrowserThread::UI));
Patrick Monette7364e6972020-01-09 22:56:021105 RenderFrameHost* render_frame_host =
1106 RenderFrameHost::FromID(render_frame_host_id);
1107 if (!render_frame_host)
1108 return nullptr;
1109
1110 return WebContents::FromRenderFrameHost(render_frame_host);
Patrick Monette275a6f92b2020-01-09 21:05:041111}
1112
1113// static
clamy0d32d6d2015-11-24 11:16:261114WebContents* WebContentsImpl::FromRenderFrameHostID(int render_process_host_id,
1115 int render_frame_host_id) {
Patrick Monette7364e6972020-01-09 22:56:021116 return FromRenderFrameHostID(
1117 GlobalFrameRoutingId(render_process_host_id, render_frame_host_id));
clamy0d32d6d2015-11-24 11:16:261118}
1119
paulmeyerfeafc2d2017-04-25 21:46:401120// static
1121WebContentsImpl* WebContentsImpl::FromOuterFrameTreeNode(
1122 const FrameTreeNode* frame_tree_node) {
Alexander Timin5fdeff22020-09-08 09:20:371123 OPTIONAL_TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1124 "WebContentsImpl::FromOuterFrameTreeNode",
1125 "frame_tree_node", frame_tree_node);
paulmeyerfeafc2d2017-04-25 21:46:401126 return WebContentsImpl::FromFrameTreeNode(frame_tree_node)
1127 ->node_.GetInnerWebContentsInFrame(frame_tree_node);
1128}
1129
[email protected]b0936d22013-11-28 06:47:361130RenderFrameHostManager* WebContentsImpl::GetRenderManagerForTesting() {
[email protected]fa944cb82013-11-15 17:51:211131 return GetRenderManager();
[email protected]765187182012-01-11 23:59:281132}
1133
nicka0ac8382016-12-15 23:59:231134bool WebContentsImpl::OnMessageReceived(RenderViewHostImpl* render_view_host,
[email protected]7bb761892012-07-20 09:32:471135 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371136 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1137 "render_view_host", render_view_host);
Alexander Timin90c20c32020-08-12 15:28:321138 for (auto& observer : observers_.observer_list()) {
Lukasz Anforowicz89f2c1b2017-08-30 21:36:461139 // TODO(nick, creis): https://crbug.com/758026: Replace all uses of this
1140 // variant of OnMessageReceived with the version that takes a
1141 // RenderFrameHost, and then delete it.
nicka0ac8382016-12-15 23:59:231142 if (observer.OnMessageReceived(message))
1143 return true;
[email protected]64ffefa2014-05-10 12:06:331144 }
[email protected]403415a2011-01-10 18:57:531145
Henrique Ferreiroba535472020-04-21 11:38:361146#if BUILDFLAG(ENABLE_PLUGINS)
[email protected]724159a2010-12-30 01:11:181147 bool handled = true;
nicka0ac8382016-12-15 23:59:231148 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_view_host)
nicka0ac8382016-12-15 23:59:231149 IPC_MESSAGE_HANDLER(ViewHostMsg_RequestPpapiBrokerPermission,
1150 OnRequestPpapiBrokerPermission)
nicka0ac8382016-12-15 23:59:231151 IPC_MESSAGE_UNHANDLED(handled = false)
1152 IPC_END_MESSAGE_MAP()
nicka0ac8382016-12-15 23:59:231153 return handled;
Henrique Ferreiroba535472020-04-21 11:38:361154#else
1155 return false;
1156#endif
nicka0ac8382016-12-15 23:59:231157}
1158
1159bool WebContentsImpl::OnMessageReceived(RenderFrameHostImpl* render_frame_host,
1160 const IPC::Message& message) {
Alexander Timin5fdeff22020-09-08 09:20:371161 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnMessageReceived",
1162 "render_frame_host",
1163 base::trace_event::ToTracedValue(render_frame_host));
1164
Alexander Timin90c20c32020-08-12 15:28:321165 for (auto& observer : observers_.observer_list()) {
nicka0ac8382016-12-15 23:59:231166 if (observer.OnMessageReceived(message, render_frame_host))
1167 return true;
1168 }
1169
1170 bool handled = true;
brettw4b461082016-11-19 18:55:161171#if BUILDFLAG(ENABLE_PLUGINS)
Hiroki Nakagawa761b9b02020-07-13 11:12:021172 IPC_BEGIN_MESSAGE_MAP_WITH_PARAM(WebContentsImpl, message, render_frame_host)
emaxxe70f5e12015-05-29 11:26:001173 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceCreated,
1174 OnPepperInstanceCreated)
1175 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperInstanceDeleted,
1176 OnPepperInstanceDeleted)
tommyclie6633ca72014-10-31 00:40:421177 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperPluginHung, OnPepperPluginHung)
zqzhang181047e62016-07-01 13:37:171178 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStartsPlayback,
1179 OnPepperStartsPlayback)
1180 IPC_MESSAGE_HANDLER(FrameHostMsg_PepperStopsPlayback,
1181 OnPepperStopsPlayback)
tommyclie6633ca72014-10-31 00:40:421182 IPC_MESSAGE_HANDLER(FrameHostMsg_PluginCrashed, OnPluginCrashed)
[email protected]724159a2010-12-30 01:11:181183 IPC_MESSAGE_UNHANDLED(handled = false)
[email protected]e44d1342014-05-16 21:29:331184 IPC_END_MESSAGE_MAP()
Hiroki Nakagawa761b9b02020-07-13 11:12:021185#else
1186 handled = false;
1187#endif
[email protected]724159a2010-12-30 01:11:181188
[email protected]724159a2010-12-30 01:11:181189 return handled;
1190}
1191
[email protected]d1198fd2012-08-13 22:50:191192NavigationControllerImpl& WebContentsImpl::GetController() {
[email protected]f5fa20e2011-12-21 22:35:561193 return controller_;
1194}
1195
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411196BrowserContext* WebContentsImpl::GetBrowserContext() {
[email protected]a26023822011-12-29 00:23:551197 return controller_.GetBrowserContext();
[email protected]627e0512011-12-21 22:55:301198}
1199
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411200const GURL& WebContentsImpl::GetURL() {
Peter Boström101d7672018-12-15 00:43:591201 return GetVisibleURL();
[email protected]be1f56ab2011-12-22 06:55:311202}
1203
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411204const GURL& WebContentsImpl::GetVisibleURL() {
[email protected]c854a7e2013-05-21 16:42:241205 // We may not have a navigation entry yet.
[email protected]59167c22013-06-03 18:07:321206 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]c854a7e2013-05-21 16:42:241207 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1208}
1209
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411210const GURL& WebContentsImpl::GetLastCommittedURL() {
[email protected]c854a7e2013-05-21 16:42:241211 // We may not have a navigation entry yet.
1212 NavigationEntry* entry = controller_.GetLastCommittedEntry();
1213 return entry ? entry->GetVirtualURL() : GURL::EmptyGURL();
1214}
1215
[email protected]8ff00d72012-10-23 19:12:211216WebContentsDelegate* WebContentsImpl::GetDelegate() {
[email protected]be1f56ab2011-12-22 06:55:311217 return delegate_;
1218}
1219
[email protected]8ff00d72012-10-23 19:12:211220void WebContentsImpl::SetDelegate(WebContentsDelegate* delegate) {
Alexander Timin5fdeff22020-09-08 09:20:371221 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetDelegate", "delegate",
1222 delegate);
[email protected]be1f56ab2011-12-22 06:55:311223 // TODO(cbentzel): remove this debugging code?
1224 if (delegate == delegate_)
1225 return;
1226 if (delegate_)
1227 delegate_->Detach(this);
1228 delegate_ = delegate;
[email protected]a6b73c62013-02-11 23:05:081229 if (delegate_) {
[email protected]be1f56ab2011-12-22 06:55:311230 delegate_->Attach(this);
[email protected]a6b73c62013-02-11 23:05:081231 // Ensure the visible RVH reflects the new delegate's preferences.
[email protected]86f98a22013-03-20 14:35:001232 if (view_)
[email protected]e85165c642014-06-10 14:34:311233 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Joel Einbinder848001c2017-09-19 21:39:311234 if (GetRenderViewHost())
1235 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]a6b73c62013-02-11 23:05:081236 }
[email protected]be1f56ab2011-12-22 06:55:311237}
1238
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411239RenderFrameHostImpl* WebContentsImpl::GetMainFrame() {
[email protected]94d0cc12013-12-18 00:07:411240 return frame_tree_.root()->current_frame_host();
[email protected]60eca4eb2013-12-06 00:02:161241}
1242
nick53d5cbf2015-04-23 22:50:141243RenderFrameHostImpl* WebContentsImpl::GetFocusedFrame() {
1244 FrameTreeNode* focused_node = frame_tree_.GetFocusedFrame();
1245 if (!focused_node)
1246 return nullptr;
1247 return focused_node->current_frame_host();
[email protected]9c9343b2014-03-08 02:56:071248}
1249
rob3e2a0732016-01-06 21:22:091250RenderFrameHostImpl* WebContentsImpl::FindFrameByFrameTreeNodeId(
creisf71a2632017-05-04 19:03:501251 int frame_tree_node_id,
1252 int process_id) {
Alexander Timin5fdeff22020-09-08 09:20:371253 OPTIONAL_TRACE_EVENT2(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1254 "WebContentsImpl::FindFrameByFrameTreeNodeId",
1255 "frame_tree_node_id", frame_tree_node_id, "process_id",
1256 process_id);
creisf71a2632017-05-04 19:03:501257 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1258
1259 // Sanity check that this is in the caller's expected process. Otherwise a
1260 // recent cross-process navigation may have led to a privilege change that the
1261 // caller is not expecting.
1262 if (!frame ||
1263 frame->current_frame_host()->GetProcess()->GetID() != process_id)
1264 return nullptr;
1265
1266 return frame->current_frame_host();
1267}
1268
1269RenderFrameHostImpl* WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId(
rob3e2a0732016-01-06 21:22:091270 int frame_tree_node_id) {
Alexander Timin5fdeff22020-09-08 09:20:371271 OPTIONAL_TRACE_EVENT1("content",
1272 "WebContentsImpl::UnsafeFindFrameByFrameTreeNodeId",
1273 "frame_tree_node_id", frame_tree_node_id);
creisf71a2632017-05-04 19:03:501274 // Beware using this! The RenderFrameHost may have changed since the caller
1275 // obtained frame_tree_node_id.
rob3e2a0732016-01-06 21:22:091276 FrameTreeNode* frame = frame_tree_.FindByID(frame_tree_node_id);
1277 return frame ? frame->current_frame_host() : nullptr;
1278}
1279
[email protected]a86c0e962013-12-17 17:10:391280void WebContentsImpl::ForEachFrame(
Lei Zhangebcc6302018-01-12 19:46:451281 const base::RepeatingCallback<void(RenderFrameHost*)>& on_frame) {
Alexander Timin5fdeff22020-09-08 09:20:371282 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
1283 "WebContentsImpl::ForEachFrame");
dcheng57e39e22016-01-21 00:25:381284 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1285 on_frame.Run(node->current_frame_host());
1286 }
[email protected]a86c0e962013-12-17 17:10:391287}
1288
dchengafb53e22016-02-04 08:11:081289std::vector<RenderFrameHost*> WebContentsImpl::GetAllFrames() {
Xuehui Xieb2300ae42020-06-09 20:25:051290 return GetAllFramesImpl(frame_tree_, /*include_pending=*/false);
1291}
1292
1293std::vector<RenderFrameHost*> WebContentsImpl::GetAllFramesIncludingPending() {
1294 return GetAllFramesImpl(frame_tree_, /*include_pending=*/true);
dchengafb53e22016-02-04 08:11:081295}
1296
lukaszacbdf52e2016-01-15 21:19:511297int WebContentsImpl::SendToAllFrames(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371298 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendToAllFrames");
Xuehui Xieb2300ae42020-06-09 20:25:051299 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/false, message);
1300}
lukasza1a9ab2422016-03-02 18:47:251301
Xuehui Xieb2300ae42020-06-09 20:25:051302int WebContentsImpl::SendToAllFramesIncludingPending(IPC::Message* message) {
Alexander Timin5fdeff22020-09-08 09:20:371303 OPTIONAL_TRACE_EVENT0("content",
1304 "WebContentsImpl::SentToAllFramesIncludingPending");
Xuehui Xieb2300ae42020-06-09 20:25:051305 return SendToAllFramesImpl(frame_tree_, /*include_pending=*/true, message);
[email protected]a86c0e962013-12-17 17:10:391306}
1307
lfgdb5c4ed2016-03-04 23:09:071308void WebContentsImpl::SendPageMessage(IPC::Message* msg) {
Alexander Timin5fdeff22020-09-08 09:20:371309 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendPageMessage");
alexmos136fd6e62016-08-15 20:58:411310 frame_tree_.root()->render_manager()->SendPageMessage(msg, nullptr);
lfgdb5c4ed2016-03-04 23:09:071311}
1312
Gyuyoung Kim877e86d2020-07-21 04:01:021313void WebContentsImpl::ExecutePageBroadcastMethod(
1314 PageBroadcastMethodCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:371315 OPTIONAL_TRACE_EVENT0("content",
1316 "WebContentsImpl::ExecutePageBroadcastMethod");
Gyuyoung Kim877e86d2020-07-21 04:01:021317 frame_tree_.root()->render_manager()->ExecutePageBroadcastMethod(callback);
1318}
1319
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411320RenderViewHostImpl* WebContentsImpl::GetRenderViewHost() {
[email protected]fa944cb82013-11-15 17:51:211321 return GetRenderManager()->current_host();
[email protected]be1f56ab2011-12-22 06:55:311322}
1323
creis89a0f782015-05-27 16:13:171324void WebContentsImpl::CancelActiveAndPendingDialogs() {
Alexander Timin5fdeff22020-09-08 09:20:371325 OPTIONAL_TRACE_EVENT0("content",
1326 "WebContentsImpl::CancelActiveAndPendingDialogs");
Evan Stade753fc202020-07-13 18:09:541327 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:531328 dialog_manager_->CancelDialogs(this, /*reset_state=*/false);
Evan Stade753fc202020-07-13 18:09:541329 }
creis89a0f782015-05-27 16:13:171330 if (browser_plugin_embedder_)
1331 browser_plugin_embedder_->CancelGuestDialogs();
1332}
1333
naskoc0fceff2015-04-30 15:53:521334void WebContentsImpl::ClosePage() {
Alexander Timin5fdeff22020-09-08 09:20:371335 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClosePage");
naskoc0fceff2015-04-30 15:53:521336 GetRenderViewHost()->ClosePage();
1337}
1338
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411339RenderWidgetHostView* WebContentsImpl::GetRenderWidgetHostView() {
[email protected]fa944cb82013-11-15 17:51:211340 return GetRenderManager()->GetRenderWidgetHostView();
[email protected]be1f56ab2011-12-22 06:55:311341}
1342
lfg265a2672016-04-23 03:11:021343RenderWidgetHostView* WebContentsImpl::GetTopLevelRenderWidgetHostView() {
1344 if (GetOuterWebContents())
1345 return GetOuterWebContents()->GetTopLevelRenderWidgetHostView();
1346 return GetRenderManager()->GetRenderWidgetHostView();
1347}
1348
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411349RenderWidgetHostView* WebContentsImpl::GetFullscreenRenderWidgetHostView() {
vmpstr6d9996c82017-02-23 00:43:251350 if (auto* widget_host = GetFullscreenRenderWidgetHost())
ekaramadaeb3c5c2016-11-09 03:22:351351 return widget_host->GetView();
1352 return nullptr;
[email protected]4aebbca2013-09-17 22:26:491353}
1354
[email protected]8ff00d72012-10-23 19:12:211355WebContentsView* WebContentsImpl::GetView() const {
[email protected]be1f56ab2011-12-22 06:55:311356 return view_.get();
1357}
1358
Mike Wasserman5a3cc61d2020-08-27 21:12:031359void WebContentsImpl::OnScreensChange(bool is_multi_screen_changed) {
Alexander Timin5fdeff22020-09-08 09:20:371360 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnScreensChange",
1361 "is_multi_screen_changed", is_multi_screen_changed);
Mike Wasserman5a3cc61d2020-08-27 21:12:031362 // Send |is_multi_screen_changed| events to all visible frames, but limit
1363 // other events to frames with the Window Placement permission. This obviates
1364 // the most pressing need for sites to poll isMultiScreen(), which is exposed
1365 // without explicit permission, while also protecting privacy.
1366 // TODO(crbug.com/1109989): Postpone events; refine utility/privacy balance.
Mike Wassermanb213b9352020-04-16 00:32:341367 for (FrameTreeNode* node : frame_tree_.Nodes()) {
1368 RenderFrameHostImpl* rfh = node->current_frame_host();
Mike Wasserman5a3cc61d2020-08-27 21:12:031369 if ((is_multi_screen_changed &&
1370 rfh->GetVisibilityState() == PageVisibilityState::kVisible) ||
1371 WindowPlacementGranted(rfh)) {
1372 rfh->GetAssociatedLocalFrame()->OnScreensChange();
1373 }
Mike Wassermanb213b9352020-04-16 00:32:341374 }
1375}
1376
leon.han552e9de2017-02-09 14:37:301377void WebContentsImpl::OnScreenOrientationChange() {
Alexander Timin5fdeff22020-09-08 09:20:371378 OPTIONAL_TRACE_EVENT0("content",
1379 "WebContentsImpl::OnScreenOrientationChange");
leon.han552e9de2017-02-09 14:37:301380 DCHECK(screen_orientation_provider_);
Lan Weif81c6e7c2020-02-12 16:46:091381 DidChangeScreenOrientation();
Becca Hughese9e27952018-06-25 17:08:271382 screen_orientation_provider_->OnOrientationChange();
leon.hane4db177a2017-02-07 14:19:161383}
1384
Alan Cutter92d59252019-03-29 02:32:331385base::Optional<SkColor> WebContentsImpl::GetThemeColor() {
Carlos Caballero1215f882019-10-29 15:58:431386 return GetRenderViewHost()->theme_color();
yusufod41c5f92015-03-06 00:14:281387}
1388
Alan Cutterd73a15d92020-08-21 07:12:451389base::Optional<SkColor> WebContentsImpl::GetBackgroundColor() {
1390 return GetRenderViewHost()->background_color();
1391}
1392
Doug Turner63f3c7b2017-07-29 05:10:011393void WebContentsImpl::SetAccessibilityMode(ui::AXMode mode) {
Alexander Timin5fdeff22020-09-08 09:20:371394 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetAccessibilityMode",
1395 "mode", mode.ToString(), "previous_mode",
1396 accessibility_mode_.ToString());
1397
[email protected]95640212014-07-26 18:14:301398 if (mode == accessibility_mode_)
1399 return;
1400
dmazzonif8a31042016-12-03 00:52:131401 // Don't allow accessibility to be enabled for WebContents that are never
danakj77eb7e82020-01-09 19:38:461402 // user-visible, like background pages.
1403 if (IsNeverComposited())
dmazzonif8a31042016-12-03 00:52:131404 return;
1405
[email protected]95640212014-07-26 18:14:301406 accessibility_mode_ = mode;
dcheng57e39e22016-01-21 00:25:381407
1408 for (FrameTreeNode* node : frame_tree_.Nodes()) {
dmazzonif8a31042016-12-03 00:52:131409 UpdateAccessibilityModeOnFrame(node->current_frame_host());
clamy610c63b32017-12-22 15:05:181410 // Also update accessibility mode on the speculative RenderFrameHost for
1411 // this FrameTreeNode, if one exists.
Alex Moshchuk3d8a1f392017-10-24 19:01:261412 RenderFrameHost* speculative_frame_host =
1413 node->render_manager()->speculative_frame_host();
1414 if (speculative_frame_host)
1415 UpdateAccessibilityModeOnFrame(speculative_frame_host);
dcheng57e39e22016-01-21 00:25:381416 }
[email protected]95640212014-07-26 18:14:301417}
1418
Doug Turner63f3c7b2017-07-29 05:10:011419void WebContentsImpl::AddAccessibilityMode(ui::AXMode mode) {
1420 ui::AXMode new_mode(accessibility_mode_);
dougtcd3dad732017-03-14 03:26:231421 new_mode |= mode;
1422 SetAccessibilityMode(new_mode);
[email protected]95640212014-07-26 18:14:301423}
1424
Avi Drissman1e620f32018-03-16 13:57:291425// Helper class used by WebContentsImpl::RequestAXTreeSnapshot.
1426// Handles the callbacks from parallel snapshot requests to each frame,
1427// and feeds the results to an AXTreeCombiner, which converts them into a
1428// single combined accessibility tree.
1429class WebContentsImpl::AXTreeSnapshotCombiner
1430 : public base::RefCounted<AXTreeSnapshotCombiner> {
1431 public:
1432 explicit AXTreeSnapshotCombiner(AXTreeSnapshotCallback callback)
1433 : callback_(std::move(callback)) {}
1434
1435 AXTreeSnapshotCallback AddFrame(bool is_root) {
1436 // Adds a reference to |this|.
1437 return base::BindOnce(&AXTreeSnapshotCombiner::ReceiveSnapshot, this,
1438 is_root);
1439 }
1440
1441 void ReceiveSnapshot(bool is_root, const ui::AXTreeUpdate& snapshot) {
1442 combiner_.AddTree(snapshot, is_root);
1443 }
1444
1445 private:
1446 friend class base::RefCounted<AXTreeSnapshotCombiner>;
1447
1448 // This is called automatically after the last call to ReceiveSnapshot
1449 // when there are no more references to this object.
1450 ~AXTreeSnapshotCombiner() {
1451 combiner_.Combine();
1452 std::move(callback_).Run(combiner_.combined());
1453 }
1454
1455 ui::AXTreeCombiner combiner_;
1456 AXTreeSnapshotCallback callback_;
1457};
1458
1459void WebContentsImpl::RequestAXTreeSnapshot(AXTreeSnapshotCallback callback,
1460 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371461 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RequestAXTreeSnapshot",
1462 "mode", ax_mode.ToString());
dmazzonid95ae842016-04-12 21:17:391463 // Send a request to each of the frames in parallel. Each one will return
1464 // an accessibility tree snapshot, and AXTreeSnapshotCombiner will combine
1465 // them into a single tree and call |callback| with that result, then
1466 // delete |combiner|.
Avi Drissman1e620f32018-03-16 13:57:291467 FrameTreeNode* root_node = frame_tree_.root();
tzik58faa742018-08-01 10:54:181468 auto combiner =
1469 base::MakeRefCounted<AXTreeSnapshotCombiner>(std::move(callback));
Avi Drissman1e620f32018-03-16 13:57:291470
tzik58faa742018-08-01 10:54:181471 RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner.get(), ax_mode);
Avi Drissman1e620f32018-03-16 13:57:291472}
1473
1474void WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame(
1475 FrameTreeNode* root_node,
1476 AXTreeSnapshotCombiner* combiner,
1477 ui::AXMode ax_mode) {
Alexander Timin5fdeff22020-09-08 09:20:371478 OPTIONAL_TRACE_EVENT0(
1479 "content", "WebContentsImpl::RecursiveRequestAXTreeSnapshotOnFrame");
dmazzonid95ae842016-04-12 21:17:391480 for (FrameTreeNode* frame_tree_node : frame_tree_.Nodes()) {
Avi Drissman1e620f32018-03-16 13:57:291481 WebContentsImpl* inner_contents =
1482 node_.GetInnerWebContentsInFrame(frame_tree_node);
1483 if (inner_contents) {
1484 inner_contents->RecursiveRequestAXTreeSnapshotOnFrame(root_node, combiner,
1485 ax_mode);
1486 } else {
1487 bool is_root = frame_tree_node == root_node;
1488 frame_tree_node->current_frame_host()->RequestAXTreeSnapshot(
1489 combiner->AddFrame(is_root), ax_mode);
1490 }
dmazzonid95ae842016-04-12 21:17:391491 }
dmazzoni83ba5c82015-04-14 07:11:511492}
1493
Becca Hughes3b5a43482018-07-17 22:31:551494void WebContentsImpl::NotifyViewportFitChanged(
1495 blink::mojom::ViewportFit value) {
Alexander Timin5fdeff22020-09-08 09:20:371496 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyViewportFitChanged",
1497 "value", static_cast<int>(value));
Alexander Timin90c20c32020-08-12 15:28:321498 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1499 observer->ViewportFitChanged(value);
1500 });
Becca Hughes3b5a43482018-07-17 22:31:551501}
1502
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411503FindRequestManager* WebContentsImpl::GetFindRequestManagerForTesting() {
Ehsan Karamad6beb2ea2018-11-25 18:15:131504 return GetFindRequestManager();
1505}
1506
mcnee336ea2c2017-05-23 22:50:591507#if !defined(OS_ANDROID)
akabac6bd1212018-06-25 20:10:481508void WebContentsImpl::UpdateZoom() {
Alexander Timin5fdeff22020-09-08 09:20:371509 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdateZoom");
akabac6bd1212018-06-25 20:10:481510 RenderWidgetHostImpl* rwh = GetRenderViewHost()->GetWidget();
1511 if (rwh->GetView())
1512 rwh->SynchronizeVisualProperties();
wjmaclean64951902016-04-29 20:59:121513}
1514
wjmaclean64951902016-04-29 20:59:121515
1516void WebContentsImpl::UpdateZoomIfNecessary(const std::string& scheme,
akabac6bd1212018-06-25 20:10:481517 const std::string& host) {
Alexander Timin5fdeff22020-09-08 09:20:371518 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateZoomIfNecessary",
1519 "scheme", scheme, "host", host);
wjmaclean64951902016-04-29 20:59:121520 NavigationEntry* entry = GetController().GetLastCommittedEntry();
1521 if (!entry)
1522 return;
1523
1524 GURL url = HostZoomMap::GetURLFromEntry(entry);
1525 if (host != net::GetHostOrSpecFromURL(url) ||
1526 (!scheme.empty() && !url.SchemeIs(scheme))) {
1527 return;
1528 }
1529
akabac6bd1212018-06-25 20:10:481530 UpdateZoom();
wjmaclean64951902016-04-29 20:59:121531}
mcnee336ea2c2017-05-23 22:50:591532#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:121533
Julie Jeongeun Kim7d0986172019-12-04 03:17:251534base::OnceClosure WebContentsImpl::AddReceiverSet(
rockotf62002a2016-09-15 00:08:591535 const std::string& interface_name,
Julie Jeongeun Kim7d0986172019-12-04 03:17:251536 WebContentsReceiverSet* receiver_set) {
Alexander Timin5fdeff22020-09-08 09:20:371537 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::AddReceiverSet",
1538 "interface_name", interface_name);
rockotf62002a2016-09-15 00:08:591539 auto result =
Julie Jeongeun Kim7d0986172019-12-04 03:17:251540 receiver_sets_.insert(std::make_pair(interface_name, receiver_set));
rockotf62002a2016-09-15 00:08:591541 DCHECK(result.second);
Julie Jeongeun Kim7d0986172019-12-04 03:17:251542 return base::BindOnce(&WebContentsImpl::RemoveReceiverSet,
danakjf4b9e942019-11-29 15:43:041543 weak_factory_.GetWeakPtr(), interface_name);
rockotf62002a2016-09-15 00:08:591544}
1545
Julie Jeongeun Kim7d0986172019-12-04 03:17:251546WebContentsReceiverSet* WebContentsImpl::GetReceiverSet(
rockot8bbad222017-03-22 04:34:051547 const std::string& interface_name) {
Julie Jeongeun Kim7d0986172019-12-04 03:17:251548 auto it = receiver_sets_.find(interface_name);
1549 if (it == receiver_sets_.end())
rockot8bbad222017-03-22 04:34:051550 return nullptr;
1551 return it->second;
1552}
1553
John Delaney732721e92020-02-07 23:11:271554void WebContentsImpl::RemoveReceiverSetForTesting(
1555 const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:371556 OPTIONAL_TRACE_EVENT1("content",
1557 "WebContentsImpl::RemoveReceiverSetForTesting",
1558 "interface_name", interface_name);
John Delaney732721e92020-02-07 23:11:271559 RemoveReceiverSet(interface_name);
1560}
1561
paulmeyerfeafc2d2017-04-25 21:46:401562std::vector<WebContentsImpl*> WebContentsImpl::GetWebContentsAndAllInner() {
1563 std::vector<WebContentsImpl*> all_contents(1, this);
1564
1565 for (size_t i = 0; i != all_contents.size(); ++i) {
1566 for (auto* inner_contents : all_contents[i]->GetInnerWebContents()) {
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:161567 all_contents.push_back(static_cast<WebContentsImpl*>(inner_contents));
paulmeyerfeafc2d2017-04-25 21:46:401568 }
1569 }
1570
1571 return all_contents;
1572}
1573
Sam McNally145fb172017-05-10 00:13:231574void WebContentsImpl::NotifyManifestUrlChanged(
Yuzu Saijo0c263c702020-06-08 03:41:241575 RenderFrameHost* rfh,
Sam McNally145fb172017-05-10 00:13:231576 const base::Optional<GURL>& manifest_url) {
Alexander Timin5fdeff22020-09-08 09:20:371577 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyManifestUrlChanged",
1578 "render_frame_host",
1579 base::trace_event::ToTracedValue(rfh), "manifest_url",
1580 base::trace_event::ValueToString(manifest_url));
Alexander Timin90c20c32020-08-12 15:28:321581 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1582 observer->DidUpdateWebManifestURL(rfh, manifest_url);
1583 });
Sam McNally145fb172017-05-10 00:13:231584}
1585
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411586WebUI* WebContentsImpl::GetWebUI() {
Nasko Oskov2f7d2112019-10-29 03:26:571587 WebUI* committed_web_ui = GetCommittedWebUI();
1588 if (committed_web_ui)
1589 return committed_web_ui;
1590
1591 if (GetRenderManager()->speculative_frame_host())
1592 return GetRenderManager()->speculative_frame_host()->web_ui();
1593
1594 return nullptr;
[email protected]be1f56ab2011-12-22 06:55:311595}
1596
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411597WebUI* WebContentsImpl::GetCommittedWebUI() {
carlosk35f35af2015-12-01 10:55:401598 return frame_tree_.root()->current_frame_host()->web_ui();
[email protected]d5f942ba2008-09-26 19:30:341599}
1600
Maks Orlovich73f374d2020-04-02 12:46:131601void WebContentsImpl::SetUserAgentOverride(
1602 const blink::UserAgentOverride& ua_override,
1603 bool override_in_new_tabs) {
Alexander Timin5fdeff22020-09-08 09:20:371604 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetUserAgentOverride",
1605 "ua_override", ua_override.ua_string_override,
1606 "override_in_new_tabs", override_in_new_tabs);
Maks Orlovich73f374d2020-04-02 12:46:131607 DCHECK(!ua_override.ua_metadata_override.has_value() ||
1608 !ua_override.ua_string_override.empty());
1609
1610 if (GetUserAgentOverride() == ua_override)
[email protected]bf70edce2012-06-20 22:32:221611 return;
1612
Changwan Ryuc1134a82018-03-07 02:10:141613 should_override_user_agent_in_new_tabs_ = override_in_new_tabs;
1614
Maks Orlovich73f374d2020-04-02 12:46:131615 renderer_preferences_.user_agent_override = ua_override;
[email protected]bf70edce2012-06-20 22:32:221616
Bruce Long1e3e1f542019-10-16 17:56:281617 // Send the new override string to all renderers in the current page.
1618 SyncRendererPrefs();
[email protected]bf70edce2012-06-20 22:32:221619
1620 // Reload the page if a load is currently in progress to avoid having
1621 // different parts of the page loaded using different user agents.
Scott Violete1d58cc2020-04-28 23:07:171622 // No need to reload if the current entry matches that of the
1623 // NavigationRequest supplied to DidStartNavigation() as NavigationRequest
1624 // handles it.
[email protected]6286a372013-10-09 04:03:271625 NavigationEntry* entry = controller_.GetVisibleEntry();
Scott Violete1d58cc2020-04-28 23:07:171626 if (IsLoading() && entry != nullptr && entry->GetIsOverridingUserAgent() &&
1627 (!frame_tree_.root()->navigation_request() ||
1628 frame_tree_.root()->navigation_request()->ua_change_requires_reload())) {
toyoshim6142d96f2016-12-19 09:07:251629 controller_.Reload(ReloadType::BYPASSING_CACHE, true);
Scott Violete1d58cc2020-04-28 23:07:171630 }
[email protected]8d0f3312012-08-18 01:47:531631
Alexander Timin90c20c32020-08-12 15:28:321632 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1633 observer->UserAgentOverrideSet(ua_override);
1634 });
[email protected]86ef6a392012-05-11 22:03:111635}
1636
Scott Violet2a6c5bff2020-04-29 23:59:061637void WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption(
1638 NavigationController::UserAgentOverrideOption option) {
Alexander Timin5fdeff22020-09-08 09:20:371639 OPTIONAL_TRACE_EVENT0(
1640 "content",
1641 "WebContentsImpl::SetRendererInitiatedUserAgentOverrideOption");
Scott Violet2a6c5bff2020-04-29 23:59:061642 renderer_initiated_user_agent_override_option_ = option;
1643}
1644
Maks Orlovich73f374d2020-04-02 12:46:131645const blink::UserAgentOverride& WebContentsImpl::GetUserAgentOverride() {
[email protected]bf70edce2012-06-20 22:32:221646 return renderer_preferences_.user_agent_override;
[email protected]86ef6a392012-05-11 22:03:111647}
1648
Scott Violet2a6c5bff2020-04-29 23:59:061649bool WebContentsImpl::ShouldOverrideUserAgentForRendererInitiatedNavigation() {
1650 NavigationEntryImpl* current_entry = controller_.GetLastCommittedEntry();
1651 if (!current_entry)
1652 return should_override_user_agent_in_new_tabs_;
1653
1654 switch (renderer_initiated_user_agent_override_option_) {
1655 case NavigationController::UA_OVERRIDE_INHERIT:
1656 return current_entry->GetIsOverridingUserAgent();
1657 case NavigationController::UA_OVERRIDE_TRUE:
1658 return true;
1659 case NavigationController::UA_OVERRIDE_FALSE:
1660 return false;
1661 default:
1662 break;
1663 }
1664 return false;
Changwan Ryuc1134a82018-03-07 02:10:141665}
1666
dmazzonidd3d51a72016-12-14 18:41:011667void WebContentsImpl::EnableWebContentsOnlyAccessibilityMode() {
Alexander Timin5fdeff22020-09-08 09:20:371668 OPTIONAL_TRACE_EVENT0(
1669 "content", "WebContentsImpl::EnableWebContentsOnlyAccessibilityMode");
Dominic Mazzonid9fda172019-03-07 17:12:071670 // If accessibility is already enabled, we'll need to force a reset
1671 // in order to ensure new observers of accessibility events get the
1672 // full accessibility tree from scratch.
1673 bool need_reset = GetAccessibilityMode().has_mode(ui::AXMode::kWebContents);
1674
1675 ui::AXMode desired_mode =
1676 GetContentClient()->browser()->GetAXModeForBrowserContext(
1677 GetBrowserContext());
1678 desired_mode |= ui::kAXModeWebContentsOnly;
1679 AddAccessibilityMode(desired_mode);
1680
1681 if (need_reset) {
dchengafb53e22016-02-04 08:11:081682 for (RenderFrameHost* rfh : GetAllFrames())
1683 ResetAccessibility(rfh);
dchengafb53e22016-02-04 08:11:081684 }
[email protected]95640212014-07-26 18:14:301685}
1686
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411687bool WebContentsImpl::IsWebContentsOnlyAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011688 return accessibility_mode_ == ui::kAXModeWebContentsOnly;
[email protected]95640212014-07-26 18:14:301689}
1690
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411691bool WebContentsImpl::IsFullAccessibilityModeForTesting() {
Doug Turner63f3c7b2017-07-29 05:10:011692 return accessibility_mode_ == ui::kAXModeComplete;
[email protected]95640212014-07-26 18:14:301693}
1694
Becca Hughes6daf5662018-06-27 16:50:541695#if defined(OS_ANDROID)
1696
1697void WebContentsImpl::SetDisplayCutoutSafeArea(gfx::Insets insets) {
Alexander Timin5fdeff22020-09-08 09:20:371698 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDisplayCutoutSafeArea");
Becca Hughes86334622018-07-09 21:29:381699 if (display_cutout_host_impl_)
1700 display_cutout_host_impl_->SetDisplayCutoutSafeArea(insets);
Becca Hughes6daf5662018-06-27 16:50:541701}
1702
1703#endif
1704
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411705const base::string16& WebContentsImpl::GetTitle() {
Nasko Oskov2f7d2112019-10-29 03:26:571706 WebUI* our_web_ui =
1707 GetRenderManager()->speculative_frame_host()
1708 ? GetRenderManager()->speculative_frame_host()->web_ui()
1709 : GetRenderManager()->current_frame_host()->web_ui();
[email protected]7ade2732011-02-10 00:13:581710 if (our_web_ui) {
[email protected]96d185d2009-04-24 03:28:541711 // Don't override the title in view source mode.
Carlos IL4dea8902020-05-26 15:14:291712 NavigationEntry* entry = controller_.GetVisibleEntry();
[email protected]96d185d2009-04-24 03:28:541713 if (!(entry && entry->IsViewSourceMode())) {
[email protected]e0112912011-02-02 22:54:351714 // Give the Web UI the chance to override our title.
[email protected]fcf75d42013-12-03 20:11:261715 const base::string16& title = our_web_ui->GetOverriddenTitle();
[email protected]96d185d2009-04-24 03:28:541716 if (!title.empty())
1717 return title;
1718 }
1719 }
1720
1721 // We use the title for the last committed entry rather than a pending
1722 // navigation entry. For example, when the user types in a URL, we want to
1723 // keep the old page's title until the new load has committed and we get a new
1724 // title.
Carlos IL4dea8902020-05-26 15:14:291725 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]59167c22013-06-03 18:07:321726
creis072b61f2015-09-28 20:52:241727 // We make an exception for initial navigations. We only want to use the title
1728 // from the visible entry if:
1729 // 1. The pending entry has been explicitly assigned a title to display.
1730 // 2. The user is doing a history navigation in a new tab (e.g., Ctrl+Back),
1731 // which case there is a pending entry index other than -1.
1732 //
1733 // Otherwise, we want to stick with the last committed entry's title during
1734 // new navigations, which have pending entries at index -1 with no title.
1735 if (controller_.IsInitialNavigation() &&
1736 ((controller_.GetVisibleEntry() &&
1737 !controller_.GetVisibleEntry()->GetTitle().empty()) ||
1738 controller_.GetPendingEntryIndex() != -1)) {
1739 entry = controller_.GetVisibleEntry();
[email protected]9eeafc012013-11-25 23:49:471740 }
[email protected]59167c22013-06-03 18:07:321741
[email protected]45d0ef7f2011-01-05 13:46:231742 if (entry) {
jshin1fb76462016-04-05 22:13:031743 return entry->GetTitleForDisplay();
[email protected]45d0ef7f2011-01-05 13:46:231744 }
[email protected]987fc3a2011-05-26 14:18:091745
1746 // |page_title_when_no_navigation_entry_| is finally used
1747 // if no title cannot be retrieved.
1748 return page_title_when_no_navigation_entry_;
[email protected]96d185d2009-04-24 03:28:541749}
1750
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411751SiteInstanceImpl* WebContentsImpl::GetSiteInstance() {
[email protected]fa944cb82013-11-15 17:51:211752 return GetRenderManager()->current_host()->GetSiteInstance();
[email protected]96d185d2009-04-24 03:28:541753}
1754
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411755bool WebContentsImpl::IsLoading() {
Carlos ILd51e7702020-05-07 18:51:391756 return frame_tree_.IsLoading();
[email protected]3c9e1872010-11-18 16:17:491757}
1758
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411759double WebContentsImpl::GetLoadProgress() {
Peter Boström18a40fa2018-10-31 19:03:501760 return frame_tree_.load_progress();
1761}
1762
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411763bool WebContentsImpl::IsLoadingToDifferentDocument() {
clamy44e84ce2016-02-22 15:38:251764 return IsLoading() && is_load_to_different_document_;
[email protected]6dfed692014-05-22 04:18:031765}
1766
Alexander Timindd0fa0c52019-11-06 13:03:371767bool WebContentsImpl::IsDocumentOnLoadCompletedInMainFrame() {
1768 return GetRenderViewHost()->IsDocumentOnLoadCompletedInMainFrame();
1769}
1770
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411771bool WebContentsImpl::IsWaitingForResponse() {
Peter Boströma9a27f6e2018-11-21 13:12:191772 NavigationRequest* ongoing_navigation_request =
1773 frame_tree_.root()->navigation_request();
1774
1775 // An ongoing navigation request means we're waiting for a response.
1776 return ongoing_navigation_request != nullptr;
[email protected]be1f56ab2011-12-22 06:55:311777}
1778
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411779const net::LoadStateWithParam& WebContentsImpl::GetLoadState() {
[email protected]be1f56ab2011-12-22 06:55:311780 return load_state_;
1781}
1782
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411783const base::string16& WebContentsImpl::GetLoadStateHost() {
[email protected]be1f56ab2011-12-22 06:55:311784 return load_state_host_;
1785}
1786
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411787uint64_t WebContentsImpl::GetUploadSize() {
[email protected]be1f56ab2011-12-22 06:55:311788 return upload_size_;
1789}
1790
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411791uint64_t WebContentsImpl::GetUploadPosition() {
[email protected]be1f56ab2011-12-22 06:55:311792 return upload_position_;
1793}
1794
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411795const std::string& WebContentsImpl::GetEncoding() {
Alexander Timine5f20e22019-10-09 23:22:351796 return GetMainFrame()->GetEncoding();
[email protected]be1f56ab2011-12-22 06:55:311797}
1798
Charles Zhaod72f99d2018-09-17 14:18:271799bool WebContentsImpl::WasDiscarded() {
1800 return GetFrameTree()->root()->was_discarded();
1801}
1802
Shubhie Panickerddf2a4e2018-03-06 00:09:061803void WebContentsImpl::SetWasDiscarded(bool was_discarded) {
1804 GetFrameTree()->root()->set_was_discarded();
1805}
1806
Collin Bakerc5259962019-11-14 17:51:581807void WebContentsImpl::IncrementCapturerCount(const gfx::Size& capture_size,
1808 bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371809 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::IncrementCapturerCount");
[email protected]5a652232013-02-12 06:15:251810 DCHECK(!is_being_destroyed_);
Xianzhu Wang724e08f2020-09-01 21:35:071811 if (stay_hidden) {
1812 // A hidden capture should not have side effect on the web contents, so it
1813 // should not pass a non-empty |capture_size| which will cause side effect.
1814 DCHECK(capture_size.IsEmpty());
Collin Bakerc5259962019-11-14 17:51:581815 ++hidden_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071816 } else {
Collin Bakerc5259962019-11-14 17:51:581817 ++visible_capturer_count_;
Xianzhu Wang724e08f2020-09-01 21:35:071818 }
[email protected]222f5822014-02-05 23:40:491819
1820 // Note: This provides a hint to upstream code to size the views optimally
1821 // for quality (e.g., to avoid scaling).
1822 if (!capture_size.IsEmpty() && preferred_size_for_capture_.IsEmpty()) {
1823 preferred_size_for_capture_ = capture_size;
1824 OnPreferredSizeChanged(preferred_size_);
1825 }
ccameron8807c38f2015-01-17 00:29:191826
Collin Bakerc5259962019-11-14 17:51:581827 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]54597982013-02-06 01:59:551828}
1829
Collin Bakerc5259962019-11-14 17:51:581830void WebContentsImpl::DecrementCapturerCount(bool stay_hidden) {
Alexander Timin5fdeff22020-09-08 09:20:371831 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DecrementCapturerCount");
Collin Bakerc5259962019-11-14 17:51:581832 if (stay_hidden)
1833 --hidden_capturer_count_;
1834 else
1835 --visible_capturer_count_;
1836 DCHECK_GE(hidden_capturer_count_, 0);
1837 DCHECK_GE(visible_capturer_count_, 0);
[email protected]54597982013-02-06 01:59:551838
[email protected]5a652232013-02-12 06:15:251839 if (is_being_destroyed_)
1840 return;
1841
Francois Doray24fc62c2017-12-11 17:27:331842 if (!IsBeingCaptured()) {
[email protected]222f5822014-02-05 23:40:491843 const gfx::Size old_size = preferred_size_for_capture_;
1844 preferred_size_for_capture_ = gfx::Size();
1845 OnPreferredSizeChanged(old_size);
[email protected]54597982013-02-06 01:59:551846 }
Collin Bakerc5259962019-11-14 17:51:581847
1848 UpdateVisibilityAndNotifyPageAndView(GetVisibility());
[email protected]be1f56ab2011-12-22 06:55:311849}
1850
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411851bool WebContentsImpl::IsBeingCaptured() {
Collin Bakerc5259962019-11-14 17:51:581852 return visible_capturer_count_ + hidden_capturer_count_ > 0;
[email protected]f2bd40812013-07-20 04:30:441853}
1854
Xianzhu Wangc61434c2020-08-21 19:17:301855bool WebContentsImpl::IsBeingVisiblyCaptured() {
1856 return visible_capturer_count_ > 0;
1857}
1858
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411859bool WebContentsImpl::IsAudioMuted() {
Guido Urdanetaf8372942019-11-15 09:47:211860 return audio_stream_factory_ && audio_stream_factory_->IsMuted();
miu50f97892014-09-22 22:49:521861}
1862
1863void WebContentsImpl::SetAudioMuted(bool mute) {
Alexander Timin5fdeff22020-09-08 09:20:371864 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetAudioMuted", "mute",
1865 mute);
miu50f97892014-09-22 22:49:521866 DVLOG(1) << "SetAudioMuted(mute=" << mute << "), was " << IsAudioMuted()
1867 << " for WebContentsImpl@" << this;
1868
1869 if (mute == IsAudioMuted())
1870 return;
1871
Guido Urdanetaf8372942019-11-15 09:47:211872 GetAudioStreamFactory()->SetMuted(mute);
miu50f97892014-09-22 22:49:521873
Alexander Timin90c20c32020-08-12 15:28:321874 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1875 observer->DidUpdateAudioMutingState(mute);
1876 });
Jan Rucka442c83f2017-08-08 13:27:541877 // Notification for UI updates in response to the changed muting state.
Collin Bakeraf540cf2019-09-20 20:54:161878 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:541879}
1880
1881bool WebContentsImpl::IsCurrentlyAudible() {
Chris Hamiltondf0d72cd2018-05-29 16:23:531882 return is_currently_audible_;
miu50f97892014-09-22 22:49:521883}
1884
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411885bool WebContentsImpl::IsConnectedToBluetoothDevice() {
ortunodf4d7982016-04-08 02:33:351886 return bluetooth_connected_device_count_ > 0;
ortuno32e7db3c2016-03-29 16:14:201887}
1888
Ovidio Henriquez76696f62020-07-08 03:06:591889bool WebContentsImpl::IsScanningForBluetoothDevices() {
1890 return bluetooth_scanning_sessions_count_ > 0;
1891}
1892
Lucas Furukawa Gadani4b4eed02019-06-04 23:12:041893bool WebContentsImpl::IsConnectedToSerialPort() {
Reilly Grant5e7c79b22019-04-09 17:26:201894 return serial_active_frame_count_ > 0;
1895}
1896
Matt Reynoldse8c6c1f2019-11-02 09:53:531897bool WebContentsImpl::IsConnectedToHidDevice() {
1898 return hid_active_frame_count_ > 0;
1899}
1900
Marijn Kruisselbrink29051042019-08-06 22:56:551901bool WebContentsImpl::HasNativeFileSystemHandles() {
1902 return native_file_system_handle_count_ > 0;
1903}
Marijn Kruisselbrinkf1714aa22019-07-02 03:45:331904
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411905bool WebContentsImpl::HasPictureInPictureVideo() {
sawtellea7333a82018-05-31 02:36:361906 return has_picture_in_picture_video_;
1907}
1908
1909void WebContentsImpl::SetHasPictureInPictureVideo(
1910 bool has_picture_in_picture_video) {
Alexander Timin5fdeff22020-09-08 09:20:371911 OPTIONAL_TRACE_EVENT1("content",
1912 "WebContentsImpl::SetHasPictureInPictureVideo",
1913 "has_pip_video", has_picture_in_picture_video);
sawtellea7333a82018-05-31 02:36:361914 // If status of |this| is already accurate, there is no need to update.
1915 if (has_picture_in_picture_video == has_picture_in_picture_video_)
1916 return;
1917 has_picture_in_picture_video_ = has_picture_in_picture_video;
1918 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:321919 observers_.ForEachObserver([&](WebContentsObserver* observer) {
1920 observer->MediaPictureInPictureChanged(has_picture_in_picture_video_);
1921 });
sawtellea7333a82018-05-31 02:36:361922}
1923
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411924bool WebContentsImpl::IsCrashed() {
Dominic Mazzoni73a48322018-05-25 18:14:071925 switch (crashed_status_) {
1926 case base::TERMINATION_STATUS_PROCESS_CRASHED:
1927 case base::TERMINATION_STATUS_ABNORMAL_TERMINATION:
1928 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED:
1929 case base::TERMINATION_STATUS_OOM:
1930 case base::TERMINATION_STATUS_LAUNCH_FAILED:
Darin Fisher6cf20e782020-08-07 22:25:361931#if defined(OS_CHROMEOS) || BUILDFLAG(IS_LACROS)
Dominic Mazzoni73a48322018-05-25 18:14:071932 case base::TERMINATION_STATUS_PROCESS_WAS_KILLED_BY_OOM:
oshima620225722015-06-04 19:45:271933#endif
Dominic Mazzoni73a48322018-05-25 18:14:071934#if defined(OS_ANDROID)
1935 case base::TERMINATION_STATUS_OOM_PROTECTED:
1936#endif
Will Harris07925d12019-10-31 03:03:051937#if defined(OS_WIN)
1938 case base::TERMINATION_STATUS_INTEGRITY_FAILURE:
1939#endif
Dominic Mazzoni73a48322018-05-25 18:14:071940 return true;
1941 case base::TERMINATION_STATUS_NORMAL_TERMINATION:
1942 case base::TERMINATION_STATUS_STILL_RUNNING:
1943 return false;
1944 case base::TERMINATION_STATUS_MAX_ENUM:
1945 NOTREACHED();
1946 return false;
1947 }
1948
1949 NOTREACHED();
1950 return false;
[email protected]3c9e1872010-11-18 16:17:491951}
1952
[email protected]b172aee2012-04-10 17:05:261953void WebContentsImpl::SetIsCrashed(base::TerminationStatus status,
1954 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:371955 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetIsCrashed", "status",
1956 static_cast<int>(status), "old_status",
1957 static_cast<int>(crashed_status_));
[email protected]443b80e2010-12-14 00:42:231958 if (status == crashed_status_)
[email protected]d5f942ba2008-09-26 19:30:341959 return;
1960
[email protected]443b80e2010-12-14 00:42:231961 crashed_status_ = status;
1962 crashed_error_code_ = error_code;
[email protected]8ff00d72012-10-23 19:12:211963 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
[email protected]d5f942ba2008-09-26 19:30:341964}
1965
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411966base::TerminationStatus WebContentsImpl::GetCrashedStatus() {
[email protected]be1f56ab2011-12-22 06:55:311967 return crashed_status_;
1968}
1969
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411970int WebContentsImpl::GetCrashedErrorCode() {
afakhry98241832016-03-11 19:27:471971 return crashed_error_code_;
1972}
1973
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:411974bool WebContentsImpl::IsBeingDestroyed() {
[email protected]be1f56ab2011-12-22 06:55:311975 return is_being_destroyed_;
1976}
1977
[email protected]7f924832014-08-09 05:57:221978void WebContentsImpl::NotifyNavigationStateChanged(
1979 InvalidateTypes changed_flags) {
Alexander Timin5fdeff22020-09-08 09:20:371980 TRACE_EVENT1("content,navigation",
1981 "WebContentsImpl::NotifyNavigationStateChanged", "changed_flags",
1982 static_cast<int>(changed_flags));
dalecurtis88c240072015-12-09 02:11:181983 // Notify the media observer of potential audibility changes.
Collin Bakeraf540cf2019-09-20 20:54:161984 if (changed_flags & INVALIDATE_TYPE_AUDIO) {
mlamouri44e4ef42016-01-20 18:42:271985 media_web_contents_observer_->MaybeUpdateAudibleState();
dalecurtisbc6572e12014-09-12 19:22:301986 }
1987
[email protected]d5f942ba2008-09-26 19:30:341988 if (delegate_)
1989 delegate_->NavigationStateChanged(this, changed_flags);
wjmaclean1dabf3e32016-05-13 23:34:441990
1991 if (GetOuterWebContents())
1992 GetOuterWebContents()->NotifyNavigationStateChanged(changed_flags);
[email protected]d5f942ba2008-09-26 19:30:341993}
1994
W. James MacLean6f34b042019-07-12 19:25:301995RenderFrameHostImpl* WebContentsImpl::GetFocusedFrameFromFocusedDelegate() {
1996 FrameTreeNode* focused_node =
1997 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
1998 return focused_node ? focused_node->current_frame_host() : nullptr;
1999}
2000
David Black9cca3592019-11-06 23:02:222001void WebContentsImpl::OnVerticalScrollDirectionChanged(
2002 viz::VerticalScrollDirection scroll_direction) {
Alexander Timin5fdeff22020-09-08 09:20:372003 OPTIONAL_TRACE_EVENT1("content",
2004 "WebContentsImpl::OnVerticalScrollDirectionChanged",
2005 "scroll_direction", static_cast<int>(scroll_direction));
Alexander Timin90c20c32020-08-12 15:28:322006 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2007 observer->DidChangeVerticalScrollDirection(scroll_direction);
2008 });
David Black9cca3592019-11-06 23:02:222009}
2010
Chris Hamiltondf0d72cd2018-05-29 16:23:532011void WebContentsImpl::OnAudioStateChanged() {
2012 // This notification can come from any embedded contents or from this
2013 // WebContents' stream monitor. Aggregate these signals to get the actual
2014 // state.
Jeremy Roman03ce13ce2020-05-29 22:16:572015 //
2016 // Note that guests may not be attached as inner contents, and so may need to
2017 // be checked separately.
Chris Hamiltondf0d72cd2018-05-29 16:23:532018 bool is_currently_audible =
2019 audio_stream_monitor_.IsCurrentlyAudible() ||
2020 (browser_plugin_embedder_ &&
Jeremy Roman03ce13ce2020-05-29 22:16:572021 browser_plugin_embedder_->AreAnyGuestsCurrentlyAudible()) ||
2022 AnyInnerWebContents(this, [](WebContents* inner_contents) {
2023 return inner_contents->IsCurrentlyAudible();
2024 });
Alexander Timin5fdeff22020-09-08 09:20:372025 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnAudioStateChanged",
2026 "is_currently_audible", is_currently_audible,
2027 "was_audible", is_currently_audible_);
Chris Hamiltondf0d72cd2018-05-29 16:23:532028 if (is_currently_audible == is_currently_audible_)
2029 return;
2030
2031 // Update internal state.
2032 is_currently_audible_ = is_currently_audible;
2033 was_ever_audible_ = was_ever_audible_ || is_currently_audible_;
2034
Gyuyoung Kim877e86d2020-07-21 04:01:022035 ExecutePageBroadcastMethod(base::BindRepeating(
2036 [](bool is_currently_audible, RenderViewHostImpl* rvh) {
2037 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2038 broadcast->AudioStateChanged(is_currently_audible);
2039 },
2040 is_currently_audible_));
altimind8bd26c2016-11-04 11:44:542041
altiminec87fd1f2016-11-17 20:22:492042 // Notification for UI updates in response to the changed audio state.
Collin Bakeraf540cf2019-09-20 20:54:162043 NotifyNavigationStateChanged(INVALIDATE_TYPE_AUDIO);
Jan Rucka442c83f2017-08-08 13:27:542044
Chris Hamiltondf0d72cd2018-05-29 16:23:532045 // Ensure that audio state changes propagate from innermost to outermost
2046 // WebContents.
2047 if (GetOuterWebContents())
2048 GetOuterWebContents()->OnAudioStateChanged();
Tommy Steimel18360512017-11-01 00:38:192049
Alexander Timin90c20c32020-08-12 15:28:322050 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2051 observer->OnAudioStateChanged(is_currently_audible_);
2052 });
altimind8bd26c2016-11-04 11:44:542053}
2054
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412055base::TimeTicks WebContentsImpl::GetLastActiveTime() {
[email protected]9a890452014-02-13 22:21:022056 return last_active_time_;
[email protected]3e324142012-06-25 18:26:332057}
2058
[email protected]9e2e4632012-07-27 16:38:412059void WebContentsImpl::WasShown() {
Alexander Timin5fdeff22020-09-08 09:20:372060 TRACE_EVENT0("content", "WebContentsImpl::WasShown");
Collin Baker989e0882019-11-01 01:27:172061 UpdateVisibilityAndNotifyPageAndView(Visibility::VISIBLE);
[email protected]be1f56ab2011-12-22 06:55:312062}
2063
[email protected]b172aee2012-04-10 17:05:262064void WebContentsImpl::WasHidden() {
Alexander Timin5fdeff22020-09-08 09:20:372065 TRACE_EVENT0("content", "WebContentsImpl::WasHidden");
Collin Baker989e0882019-11-01 01:27:172066 UpdateVisibilityAndNotifyPageAndView(Visibility::HIDDEN);
[email protected]375fa1b2012-05-22 22:05:372067}
2068
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412069bool WebContentsImpl::HasRecentInteractiveInputEvent() {
Daniel Cheng90196c82018-04-25 21:49:142070 static constexpr base::TimeDelta kMaxInterval =
2071 base::TimeDelta::FromSeconds(5);
2072 base::TimeDelta delta =
2073 ui::EventTimeForNow() - last_interactive_input_event_time_;
2074 // Note: the expectation is that the caller is typically expecting an input
2075 // event, e.g. validating that a WebUI message that requires a gesture is
Daniel Chenge81030b32019-07-17 20:20:232076 // actually attached to a gesture.
Daniel Cheng90196c82018-04-25 21:49:142077 return delta <= kMaxInterval;
2078}
2079
Avi Drissman738ea192018-08-29 20:24:162080void WebContentsImpl::SetIgnoreInputEvents(bool ignore_input_events) {
Alexander Timin5fdeff22020-09-08 09:20:372081 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIgnoreInputEvents",
2082 "ignore_input_events", ignore_input_events);
Avi Drissman738ea192018-08-29 20:24:162083 ignore_input_events_ = ignore_input_events;
2084}
2085
Bo Liu168c8642017-08-28 18:26:022086#if defined(OS_ANDROID)
Bo Liu16dd7b8322018-05-02 21:19:502087void WebContentsImpl::SetMainFrameImportance(
2088 ChildProcessImportance importance) {
Alexander Timin5fdeff22020-09-08 09:20:372089 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetMainFrameImportance",
2090 "importance", static_cast<int>(importance));
Bo Liu16dd7b8322018-05-02 21:19:502091 GetMainFrame()->GetRenderWidgetHost()->SetImportance(importance);
Bo Liu7c6779e92017-08-16 02:02:282092}
Bo Liu168c8642017-08-28 18:26:022093#endif
Bo Liu7c6779e92017-08-16 02:02:282094
ccameron8807c38f2015-01-17 00:29:192095void WebContentsImpl::WasOccluded() {
Alexander Timin5fdeff22020-09-08 09:20:372096 TRACE_EVENT0("content", "WebContentsImpl::WasOccluded");
Collin Baker989e0882019-11-01 01:27:172097 UpdateVisibilityAndNotifyPageAndView(Visibility::OCCLUDED);
ccameron8807c38f2015-01-17 00:29:192098}
2099
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:412100Visibility WebContentsImpl::GetVisibility() {
Francois Doraye6161152018-03-27 22:05:372101 return visibility_;
Francois Dorayfe4a1772018-02-17 04:17:092102}
2103
Rakina Zata Amni26e8d8a2020-08-05 06:06:062104bool WebContentsImpl::NeedToFireBeforeUnloadOrUnloadEvents() {
Alexander Timinc7bee322020-05-19 17:54:342105 if (!notify_disconnection_)
Alex Moshchuk6fcaca752018-07-14 02:13:592106 return false;
2107
2108 // Don't fire if the main frame's RenderViewHost indicates that beforeunload
2109 // and unload have already executed (e.g., after receiving a ClosePage ACK)
2110 // or should be ignored.
2111 if (GetRenderViewHost()->SuddenTerminationAllowed())
2112 return false;
2113
Alex Moshchukc78dbc722019-10-31 20:00:502114 // Check whether any frame in the frame tree needs to run beforeunload or
Rakina Zata Amni26e8d8a2020-08-05 06:06:062115 // unload-time event handlers.
Alex Moshchukc78dbc722019-10-31 20:00:502116 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2117 RenderFrameHostImpl* rfh = node->current_frame_host();
2118
Rakina Zata Amni26e8d8a2020-08-05 06:06:062119 // No need to run beforeunload/unload-time events if the RenderFrame isn't
2120 // live.
Alex Moshchukc78dbc722019-10-31 20:00:502121 if (!rfh->IsRenderFrameLive())
2122 continue;
Rakina Zata Amni26e8d8a2020-08-05 06:06:062123 bool should_run_before_unload_handler =
Dave Tapuska97d22ab2019-12-03 17:56:362124 rfh->GetSuddenTerminationDisablerState(
Rakina Zata Amni26e8d8a2020-08-05 06:06:062125 blink::mojom::SuddenTerminationDisablerType::kBeforeUnloadHandler);
2126 bool should_run_unload_handler = rfh->GetSuddenTerminationDisablerState(
2127 blink::mojom::SuddenTerminationDisablerType::kUnloadHandler);
2128 bool should_run_page_hide_handler = rfh->GetSuddenTerminationDisablerState(
2129 blink::mojom::SuddenTerminationDisablerType::kPageHideHandler);
2130 auto* rvh = static_cast<RenderViewHostImpl*>(rfh->GetRenderViewHost());
2131 // If the tab is already hidden, we should not run visibilitychange
2132 // handlers.
2133 bool is_page_visible = rvh->GetPageLifecycleStateManager()
2134 ->CalculatePageLifecycleState()
2135 ->visibility == PageVisibilityState::kVisible;
2136
2137 bool should_run_visibility_change_handler =
2138 is_page_visible && rfh->GetSuddenTerminationDisablerState(
2139 blink::mojom::SuddenTerminationDisablerType::
2140 kVisibilityChangeHandler);
2141 if (should_run_before_unload_handler || should_run_unload_handler ||
2142 should_run_page_hide_handler || should_run_visibility_change_handler) {
Alex Moshchukc78dbc722019-10-31 20:00:502143 return true;
2144 }
Aditya Keerthi34f37e62019-03-08 15:54:532145 }
Alex Moshchuk6fcaca752018-07-14 02:13:592146
Alex Moshchukc78dbc722019-10-31 20:00:502147 return false;
[email protected]be1f56ab2011-12-22 06:55:312148}
2149
Chris Hamilton3b3e315d2018-09-19 13:16:212150void WebContentsImpl::DispatchBeforeUnload(bool auto_cancel) {
Alexander Timin5fdeff22020-09-08 09:20:372151 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DispatchBeforeUnload",
2152 "auto_cancel", auto_cancel);
Chris Hamilton3b3e315d2018-09-19 13:16:212153 auto before_unload_type =
2154 auto_cancel ? RenderFrameHostImpl::BeforeUnloadType::DISCARD
2155 : RenderFrameHostImpl::BeforeUnloadType::TAB_CLOSE;
2156 GetMainFrame()->DispatchBeforeUnload(before_unload_type, false);
[email protected]1c3f80bd2014-04-08 23:02:062157}
2158
W. James MacLean2539adb32019-12-13 00:40:442159bool WebContentsImpl::IsInnerWebContentsForGuest() {
2160 return !!browser_plugin_guest_;
2161}
2162
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502163void WebContentsImpl::AttachInnerWebContents(
2164 std::unique_ptr<WebContents> inner_web_contents,
W. James MacLean62883982019-11-12 20:39:002165 RenderFrameHost* render_frame_host,
2166 bool is_full_page) {
Alexander Timin5fdeff22020-09-08 09:20:372167 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::AttachInnerWebContents",
2168 "inner_web_contents", inner_web_contents.get(),
2169 "is_full_page", is_full_page);
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502170 WebContentsImpl* inner_web_contents_impl =
2171 static_cast<WebContentsImpl*>(inner_web_contents.get());
2172 DCHECK(!inner_web_contents_impl->node_.outer_web_contents());
2173 auto* render_frame_host_impl =
2174 static_cast<RenderFrameHostImpl*>(render_frame_host);
Fergal Daly445af932020-06-02 06:37:232175 DCHECK_EQ(&frame_tree_, render_frame_host_impl->frame_tree());
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392176
Yuzu Saijo3f86fb22020-06-11 03:51:102177 // Mark |render_frame_host_impl| as outer delegate frame.
2178 render_frame_host_impl->SetIsOuterDelegateFrame(true);
2179
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502180 RenderFrameHostManager* inner_render_manager =
2181 inner_web_contents_impl->GetRenderManager();
2182 RenderFrameHostImpl* inner_main_frame =
2183 inner_render_manager->current_frame_host();
2184 RenderViewHostImpl* inner_render_view_host =
2185 inner_render_manager->current_host();
2186 auto* outer_render_manager =
2187 render_frame_host_impl->frame_tree_node()->render_manager();
lfg91a79e12016-04-01 23:52:192188
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392189 // When attaching a WebContents as an inner WebContents, we need to replace
2190 // the Webcontents' view with a WebContentsViewChildFrame.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502191 inner_web_contents_impl->view_.reset(new WebContentsViewChildFrame(
2192 inner_web_contents_impl,
2193 GetContentClient()->browser()->GetWebContentsViewDelegate(
2194 inner_web_contents_impl),
2195 &inner_web_contents_impl->render_view_host_delegate_view_));
Lucas Furukawa Gadani105de1e812018-05-31 19:38:392196
lfg91a79e12016-04-01 23:52:192197 // When the WebContents being initialized has an opener, the browser side
2198 // Render{View,Frame}Host must be initialized and the RenderWidgetHostView
2199 // created. This is needed because the usual initialization happens during
2200 // the first navigation, but when attaching a new window we don't navigate
2201 // before attaching. If the browser side is already initialized, the calls
2202 // below will just early return.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502203 inner_render_manager->InitRenderView(inner_render_view_host, nullptr);
2204 inner_main_frame->Init();
2205 if (!inner_render_manager->GetRenderWidgetHostView()) {
2206 inner_web_contents_impl->CreateRenderWidgetHostViewForRenderManager(
2207 inner_render_view_host);
2208 }
lfg91a79e12016-04-01 23:52:192209
Adithya Srinivasane6e7f842019-12-16 18:41:362210 inner_web_contents_impl->RecursivelyUnregisterFrameSinkIds();
2211
lazyboy6ec48b2a2015-06-29 15:18:142212 // Create a link to our outer WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502213 node_.AttachInnerWebContents(std::move(inner_web_contents),
2214 render_frame_host_impl);
lazyboy6ec48b2a2015-06-29 15:18:142215
lazyboy6ec48b2a2015-06-29 15:18:142216 // Create a proxy in top-level RenderFrameHostManager, pointing to the
2217 // SiteInstance of the outer WebContents. The proxy will be used to send
2218 // postMessage to the inner WebContents.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502219 auto* proxy = inner_render_manager->CreateOuterDelegateProxy(
2220 render_frame_host_impl->GetSiteInstance());
lazyboy6ec48b2a2015-06-29 15:18:142221
Lucas Furukawa Gadani99125822019-01-03 15:41:492222 // When attaching a GuestView as an inner WebContents, there should already be
2223 // a live RenderFrame, which has to be swapped. When attaching a portal, there
2224 // will not be a live RenderFrame before creating the proxy.
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502225 if (render_frame_host_impl->IsRenderFrameLive()) {
2226 inner_render_manager->SwapOuterDelegateFrame(render_frame_host_impl, proxy);
Lucas Furukawa Gadani99125822019-01-03 15:41:492227
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502228 inner_web_contents_impl->ReattachToOuterWebContentsFrame();
Lucas Furukawa Gadani99125822019-01-03 15:41:492229 }
ekaramadadd882292016-06-08 15:22:562230
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502231 if (frame_tree_.GetFocusedFrame() ==
2232 render_frame_host_impl->frame_tree_node()) {
2233 inner_web_contents_impl->SetFocusedFrame(
2234 inner_web_contents_impl->frame_tree_.root(),
2235 render_frame_host_impl->GetSiteInstance());
avallee7529b2a2017-04-26 11:37:512236 }
Lucas Furukawa Gadani6e5b4f32019-03-02 04:18:502237 outer_render_manager->set_attach_complete();
W. James MacLean62883982019-11-12 20:39:002238
2239 // If the inner WebContents is full frame, give it focus.
2240 if (is_full_page) {
2241 // There should only ever be one inner WebContents when |is_full_page| is
2242 // true, and it is the one we just attached.
2243 DCHECK_EQ(1u, node_.GetInnerWebContents().size());
2244 inner_web_contents_impl->SetAsFocusedWebContentsIfNecessary();
2245 }
Chris Hamilton16b5d1d2020-06-04 00:08:122246
Alexander Timin90c20c32020-08-12 15:28:322247 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2248 observer->InnerWebContentsAttached(inner_web_contents_impl,
2249 render_frame_host, is_full_page);
2250 });
lazyboy6ec48b2a2015-06-29 15:18:142251}
2252
Lucas Furukawa Gadani99125822019-01-03 15:41:492253std::unique_ptr<WebContents> WebContentsImpl::DetachFromOuterWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:372254 OPTIONAL_TRACE_EVENT0("content",
2255 "WebContentsImpl::DetachFromOuterWebContents");
Chris Hamilton16b5d1d2020-06-04 00:08:122256 auto* outer_web_contents = GetOuterWebContents();
2257 DCHECK(outer_web_contents);
Yuzu Saijo3f86fb22020-06-11 03:51:102258 GetMainFrame()->ParentOrOuterDelegateFrame()->SetIsOuterDelegateFrame(false);
Chris Hamilton16b5d1d2020-06-04 00:08:122259
Adithya Srinivasane6e7f842019-12-16 18:41:362260 RecursivelyUnregisterFrameSinkIds();
Lucas Gadanid29952582020-06-09 21:24:002261
2262 // Each RenderViewHost has a RenderWidgetHost which can have a
2263 // RenderWidgetHostView, and it needs to be re-created with the appropriate
2264 // platform view. It is important to re-create all child views, not only the
2265 // current one, since the view can be swapped due to a cross-origin
2266 // navigation.
2267 std::set<RenderViewHostImpl*> render_view_hosts;
2268 for (auto& render_view_host : GetFrameTree()->render_view_hosts()) {
2269 if (render_view_host.second->GetWidget() &&
2270 render_view_host.second->GetWidget()->GetView()) {
2271 DCHECK(render_view_host.second->GetWidget()
2272 ->GetView()
2273 ->IsRenderWidgetHostViewChildFrame());
2274 render_view_hosts.insert(render_view_host.second);
Kevin McNee6471a702020-01-27 18:23:072275 }
2276 }
Lucas Gadanid29952582020-06-09 21:24:002277
2278 for (auto* render_view_host : render_view_hosts)
2279 render_view_host->GetWidget()->GetView()->Destroy();
2280
Lucas Furukawa Gadani99125822019-01-03 15:41:492281 GetRenderManager()->DeleteOuterDelegateProxy(
2282 node_.OuterContentsFrameTreeNode()
2283 ->current_frame_host()
2284 ->GetSiteInstance());
2285 view_.reset(CreateWebContentsView(
2286 this, GetContentClient()->browser()->GetWebContentsViewDelegate(this),
2287 &render_view_host_delegate_view_));
danakjfc5184932019-09-12 18:08:322288 view_->CreateView(nullptr);
Lucas Furukawa Gadani99125822019-01-03 15:41:492289 std::unique_ptr<WebContents> web_contents =
2290 node_.DisconnectFromOuterWebContents();
2291 DCHECK_EQ(web_contents.get(), this);
2292 node_.SetFocusedWebContents(this);
Lucas Gadanid29952582020-06-09 21:24:002293
2294 for (auto* render_view_host : render_view_hosts)
2295 CreateRenderWidgetHostViewForRenderManager(render_view_host);
2296
Adithya Srinivasane6e7f842019-12-16 18:41:362297 RecursivelyRegisterFrameSinkIds();
Adithya Srinivasan6f0f67b2019-12-19 01:26:462298 // TODO(adithyas): |browser_plugin_embedder_ax_tree_id| should either not be
2299 // used for portals, or it should get a different name.
2300 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(ui::AXTreeIDUnknown());
2301 GetMainFrame()->UpdateAXTreeData();
Chris Hamilton16b5d1d2020-06-04 00:08:122302
2303 // Invoke on the *outer* web contents observers for symmetry.
Alexander Timin90c20c32020-08-12 15:28:322304 outer_web_contents->observers_.ForEachObserver(
2305 [&](WebContentsObserver* observer) {
2306 observer->InnerWebContentsDetached(this);
2307 });
Chris Hamilton16b5d1d2020-06-04 00:08:122308
Lucas Furukawa Gadani99125822019-01-03 15:41:492309 return web_contents;
2310}
2311
W. James MacLean2dc75ed42019-03-06 14:31:092312void WebContentsImpl::RecursivelyRegisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372313 OPTIONAL_TRACE_EVENT0("content",
2314 "WebContentsImpl::RecursivelyRegisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362315 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2316 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2317 if (rwhvb->IsRenderWidgetHostViewChildFrame())
2318 static_cast<RenderWidgetHostViewChildFrame*>(view)->RegisterFrameSinkId();
2319 }
2320}
W. James MacLean2dc75ed42019-03-06 14:31:092321
Adithya Srinivasane6e7f842019-12-16 18:41:362322void WebContentsImpl::RecursivelyUnregisterFrameSinkIds() {
Alexander Timin5fdeff22020-09-08 09:20:372323 OPTIONAL_TRACE_EVENT0("content",
2324 "WebContentsImpl::RecursivelyUnregisterFrameSinkIds");
Adithya Srinivasane6e7f842019-12-16 18:41:362325 for (auto* view : GetRenderWidgetHostViewsInWebContentsTree()) {
2326 auto* rwhvb = static_cast<RenderWidgetHostViewBase*>(view);
2327 if (rwhvb->IsRenderWidgetHostViewChildFrame()) {
2328 static_cast<RenderWidgetHostViewChildFrame*>(view)
2329 ->UnregisterFrameSinkId();
2330 }
W. James MacLean2dc75ed42019-03-06 14:31:092331 }
2332}
2333
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142334void WebContentsImpl::ReattachToOuterWebContentsFrame() {
Alexander Timin5fdeff22020-09-08 09:20:372335 OPTIONAL_TRACE_EVENT0("content",
2336 "WebContentsImpl::ReattachToOuterWebContentsFrame");
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142337 DCHECK(node_.outer_web_contents());
2338 auto* render_manager = GetRenderManager();
2339 auto* parent_frame =
2340 node_.OuterContentsFrameTreeNode()->current_frame_host()->GetParent();
2341 render_manager->SetRWHViewForInnerContents(
2342 render_manager->GetRenderWidgetHostView());
2343
W. James MacLean2dc75ed42019-03-06 14:31:092344 RecursivelyRegisterFrameSinkIds();
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:142345
2346 // Set up the the guest's AX tree to point back at the embedder's AX tree.
2347 GetMainFrame()->set_browser_plugin_embedder_ax_tree_id(
2348 parent_frame->GetAXTreeID());
2349 GetMainFrame()->UpdateAXTreeData();
2350}
2351
Lucas Gadani972985622020-05-28 20:52:512352void WebContentsImpl::DidActivatePortal(
2353 WebContentsImpl* predecessor_web_contents,
2354 base::TimeTicks activation_time) {
Alexander Timin5fdeff22020-09-08 09:20:372355 TRACE_EVENT2("content", "WebContentsImpl::DidActivatePortal", "predecessor",
2356 predecessor_web_contents, "activation_time", activation_time);
Lucas Gadani972985622020-05-28 20:52:512357 DCHECK(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062358 NotifyInsidePortal(false);
Alexander Timin90c20c32020-08-12 15:28:322359 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2360 observer->DidActivatePortal(predecessor_web_contents, activation_time);
2361 });
Lucas Gadani972985622020-05-28 20:52:512362 GetDelegate()->WebContentsBecamePortal(predecessor_web_contents);
Kevin McNeef8eb64c2020-04-21 21:36:062363}
2364
Adithya Srinivasan11af2c52019-12-16 22:52:552365void WebContentsImpl::NotifyInsidePortal(bool inside_portal) {
Alexander Timin5fdeff22020-09-08 09:20:372366 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyInsidePortal",
2367 "inside_portal", inside_portal);
Gyuyoung Kim1c029712020-07-22 09:21:062368 ExecutePageBroadcastMethod(base::BindRepeating(
2369 [](bool inside_portal, RenderViewHostImpl* rvh) {
2370 if (auto& broadcast = rvh->GetAssociatedPageBroadcast())
2371 broadcast->SetInsidePortal(inside_portal);
2372 },
2373 inside_portal));
Adithya Srinivasan11af2c52019-12-16 22:52:552374}
2375
dalecurtis6c58ed02016-10-28 23:02:372376void WebContentsImpl::DidChangeVisibleSecurityState() {
Alexander Timin5fdeff22020-09-08 09:20:372377 OPTIONAL_TRACE_EVENT0("content",
2378 "WebContentsImpl::DidChangeVisibleSecurityState");
Emily Starkc663b0242019-04-26 19:34:452379 if (delegate_)
dalecurtis6c58ed02016-10-28 23:02:372380 delegate_->VisibleSecurityStateChanged(this);
Alexander Timin90c20c32020-08-12 15:28:322381 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2382 observer->DidChangeVisibleSecurityState();
2383 });
dalecurtis6c58ed02016-10-28 23:02:372384}
2385
Rakina Zata Amni4029b6d2020-07-28 02:36:202386const WebPreferences WebContentsImpl::ComputeWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:372387 OPTIONAL_TRACE_EVENT0("browser", "WebContentsImpl::ComputeWebPreferences");
2388
Rakina Zata Amni4029b6d2020-07-28 02:36:202389 WebPreferences prefs;
2390
2391 const base::CommandLine& command_line =
2392 *base::CommandLine::ForCurrentProcess();
2393
2394 SetSlowWebPreferences(command_line, &prefs);
2395
2396 prefs.web_security_enabled =
2397 !command_line.HasSwitch(switches::kDisableWebSecurity);
2398
2399 prefs.remote_fonts_enabled =
2400 !command_line.HasSwitch(switches::kDisableRemoteFonts);
2401 prefs.application_cache_enabled =
2402 base::FeatureList::IsEnabled(blink::features::kAppCache);
2403 prefs.local_storage_enabled =
2404 !command_line.HasSwitch(switches::kDisableLocalStorage);
2405 prefs.databases_enabled =
2406 !command_line.HasSwitch(switches::kDisableDatabases);
2407
2408 prefs.webgl1_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2409 !command_line.HasSwitch(switches::kDisableWebGL);
2410 prefs.webgl2_enabled = !command_line.HasSwitch(switches::kDisable3DAPIs) &&
2411 !command_line.HasSwitch(switches::kDisableWebGL) &&
2412 !command_line.HasSwitch(switches::kDisableWebGL2);
2413
2414 prefs.pepper_3d_enabled = !command_line.HasSwitch(switches::kDisablePepper3d);
2415
2416 prefs.flash_3d_enabled = !command_line.HasSwitch(switches::kDisableFlash3d);
2417 prefs.flash_stage3d_enabled =
2418 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2419 prefs.flash_stage3d_baseline_enabled =
2420 !command_line.HasSwitch(switches::kDisableFlashStage3d);
2421
2422 prefs.allow_file_access_from_file_urls =
2423 command_line.HasSwitch(switches::kAllowFileAccessFromFiles);
2424
2425 prefs.accelerated_2d_canvas_enabled =
2426 !command_line.HasSwitch(switches::kDisableAccelerated2dCanvas);
2427 prefs.new_canvas_2d_api_enabled =
Rakina Zata Amniea8d0c22020-07-30 17:22:502428 command_line.HasSwitch(switches::kEnableNewCanvas2DAPI) ||
2429 base::FeatureList::IsEnabled(features::kEnableNewCanvas2DAPI);
Rakina Zata Amni4029b6d2020-07-28 02:36:202430 prefs.antialiased_2d_canvas_disabled =
2431 command_line.HasSwitch(switches::kDisable2dCanvasAntialiasing);
2432 prefs.antialiased_clips_2d_canvas_enabled =
2433 !command_line.HasSwitch(switches::kDisable2dCanvasClipAntialiasing);
2434
2435 prefs.disable_ipc_flooding_protection =
2436 command_line.HasSwitch(switches::kDisableIpcFloodingProtection) ||
2437 command_line.HasSwitch(switches::kDisablePushStateThrottle);
2438
2439 prefs.accelerated_video_decode_enabled =
2440 !command_line.HasSwitch(switches::kDisableAcceleratedVideoDecode);
2441
2442 std::string autoplay_policy = media::GetEffectiveAutoplayPolicy(command_line);
2443 if (autoplay_policy == switches::autoplay::kNoUserGestureRequiredPolicy) {
2444 prefs.autoplay_policy = AutoplayPolicy::kNoUserGestureRequired;
2445 } else if (autoplay_policy ==
2446 switches::autoplay::kUserGestureRequiredPolicy) {
2447 prefs.autoplay_policy = AutoplayPolicy::kUserGestureRequired;
2448 } else if (autoplay_policy ==
2449 switches::autoplay::kDocumentUserActivationRequiredPolicy) {
2450 prefs.autoplay_policy = AutoplayPolicy::kDocumentUserActivationRequired;
2451 } else {
2452 NOTREACHED();
2453 }
2454
2455 prefs.dont_send_key_events_to_javascript =
2456 base::FeatureList::IsEnabled(features::kDontSendKeyEventsToJavascript);
2457
2458// TODO(dtapuska): Enable barrel button selection drag support on Android.
2459// crbug.com/758042
2460#if defined(OS_WIN)
2461 prefs.barrel_button_for_drag_enabled =
2462 base::FeatureList::IsEnabled(features::kDirectManipulationStylus);
2463#endif // defined(OS_WIN)
2464
Rakina Zata Amni4029b6d2020-07-28 02:36:202465 prefs.enable_scroll_animator =
2466 command_line.HasSwitch(switches::kEnableSmoothScrolling) ||
2467 (!command_line.HasSwitch(switches::kDisableSmoothScrolling) &&
2468 gfx::Animation::ScrollAnimationsEnabledBySystem());
2469
2470 prefs.prefers_reduced_motion = gfx::Animation::PrefersReducedMotion();
2471
2472 if (ChildProcessSecurityPolicyImpl::GetInstance()->HasWebUIBindings(
2473 GetRenderViewHost()->GetProcess()->GetID())) {
2474 prefs.loads_images_automatically = true;
2475 prefs.javascript_enabled = true;
2476 }
2477
2478 prefs.viewport_enabled = command_line.HasSwitch(switches::kEnableViewport);
2479
2480 if (IsOverridingUserAgent())
2481 prefs.viewport_meta_enabled = false;
2482
2483 prefs.main_frame_resizes_are_orientation_changes =
2484 command_line.HasSwitch(switches::kMainFrameResizesAreOrientationChanges);
2485
2486 prefs.spatial_navigation_enabled =
2487 command_line.HasSwitch(switches::kEnableSpatialNavigation);
2488
2489 if (IsSpatialNavigationDisabled())
2490 prefs.spatial_navigation_enabled = false;
2491
Rakina Zata Amni4029b6d2020-07-28 02:36:202492 prefs.disable_reading_from_canvas =
2493 command_line.HasSwitch(switches::kDisableReadingFromCanvas);
2494
2495 prefs.strict_mixed_content_checking =
2496 command_line.HasSwitch(switches::kEnableStrictMixedContentChecking);
2497
2498 prefs.strict_powerful_feature_restrictions = command_line.HasSwitch(
2499 switches::kEnableStrictPowerfulFeatureRestrictions);
2500
2501 const std::string blockable_mixed_content_group =
2502 base::FieldTrialList::FindFullName("BlockableMixedContent");
2503 prefs.strictly_block_blockable_mixed_content =
2504 blockable_mixed_content_group == "StrictlyBlockBlockableMixedContent";
2505
2506 const std::string plugin_mixed_content_status =
2507 base::FieldTrialList::FindFullName("PluginMixedContentStatus");
2508 prefs.block_mixed_plugin_content =
2509 plugin_mixed_content_status == "BlockableMixedContent";
2510
2511 prefs.v8_cache_options = GetV8CacheOptions();
2512
2513 prefs.user_gesture_required_for_presentation = !command_line.HasSwitch(
2514 switches::kDisableGestureRequirementForPresentation);
2515
2516 if (HideDownloadUI())
2517 prefs.hide_download_ui = true;
2518
2519 // `media_controls_enabled` is `true` by default.
2520 if (HasPersistentVideo())
2521 prefs.media_controls_enabled = false;
2522
2523#if defined(OS_ANDROID)
2524 display::Display display = display::Screen::GetScreen()->GetPrimaryDisplay();
2525 gfx::Size size = display.GetSizeInPixel();
2526 int min_width = size.width() < size.height() ? size.width() : size.height();
2527 prefs.device_scale_adjustment = GetDeviceScaleAdjustment(
2528 static_cast<int>(min_width / display.device_scale_factor()));
2529#endif // OS_ANDROID
2530
2531 GetContentClient()->browser()->OverrideWebkitPrefs(GetRenderViewHost(),
2532 &prefs);
2533 return prefs;
2534}
2535
2536void WebContentsImpl::SetSlowWebPreferences(
2537 const base::CommandLine& command_line,
2538 WebPreferences* prefs) {
Alexander Timin5fdeff22020-09-08 09:20:372539 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetSlowWebPreferences");
2540
Rakina Zata Amni4029b6d2020-07-28 02:36:202541 if (web_preferences_.get()) {
2542#define SET_FROM_CACHE(prefs, field) prefs->field = web_preferences_->field
2543
2544 SET_FROM_CACHE(prefs, touch_event_feature_detection_enabled);
2545 SET_FROM_CACHE(prefs, available_pointer_types);
2546 SET_FROM_CACHE(prefs, available_hover_types);
2547 SET_FROM_CACHE(prefs, primary_pointer_type);
2548 SET_FROM_CACHE(prefs, primary_hover_type);
2549 SET_FROM_CACHE(prefs, pointer_events_max_touch_points);
2550 SET_FROM_CACHE(prefs, number_of_cpu_cores);
2551
2552#if defined(OS_ANDROID)
2553 SET_FROM_CACHE(prefs, video_fullscreen_orientation_lock_enabled);
2554 SET_FROM_CACHE(prefs, video_rotate_to_fullscreen_enabled);
2555#endif
2556
2557#undef SET_FROM_CACHE
2558 } else {
2559 // Every prefs->field modified below should have a SET_FROM_CACHE entry
2560 // above.
2561
2562 // On Android, Touch event feature detection is enabled by default,
2563 // Otherwise default is disabled.
2564 std::string touch_enabled_default_switch =
2565 switches::kTouchEventFeatureDetectionDisabled;
2566#if defined(OS_ANDROID)
2567 touch_enabled_default_switch = switches::kTouchEventFeatureDetectionEnabled;
2568#endif // defined(OS_ANDROID)
2569 const std::string touch_enabled_switch =
2570 command_line.HasSwitch(switches::kTouchEventFeatureDetection)
2571 ? command_line.GetSwitchValueASCII(
2572 switches::kTouchEventFeatureDetection)
2573 : touch_enabled_default_switch;
2574
2575 prefs->touch_event_feature_detection_enabled =
2576 (touch_enabled_switch == switches::kTouchEventFeatureDetectionAuto)
2577 ? (ui::GetTouchScreensAvailability() ==
2578 ui::TouchScreensAvailability::ENABLED)
2579 : (touch_enabled_switch.empty() ||
2580 touch_enabled_switch ==
2581 switches::kTouchEventFeatureDetectionEnabled);
2582
2583 std::tie(prefs->available_pointer_types, prefs->available_hover_types) =
2584 ui::GetAvailablePointerAndHoverTypes();
2585 prefs->primary_pointer_type =
2586 ui::GetPrimaryPointerType(prefs->available_pointer_types);
2587 prefs->primary_hover_type =
2588 ui::GetPrimaryHoverType(prefs->available_hover_types);
2589
2590 prefs->pointer_events_max_touch_points = ui::MaxTouchPoints();
2591
2592 prefs->number_of_cpu_cores = base::SysInfo::NumberOfProcessors();
2593
2594#if defined(OS_ANDROID)
2595 const bool device_is_phone =
2596 ui::GetDeviceFormFactor() == ui::DEVICE_FORM_FACTOR_PHONE;
2597 prefs->video_fullscreen_orientation_lock_enabled = device_is_phone;
2598 prefs->video_rotate_to_fullscreen_enabled = device_is_phone;
2599#endif
2600 }
2601}
2602
2603void WebContentsImpl::OnWebPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372604 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebPreferencesChanged");
2605
Rakina Zata Amni4029b6d2020-07-28 02:36:202606 // This is defensive code to avoid infinite loops due to code run inside
2607 // SetWebPreferences() accidentally updating more preferences and thus
2608 // calling back into this code. See crbug.com/398751 for one past example.
2609 if (updating_web_preferences_)
2610 return;
2611 updating_web_preferences_ = true;
2612 SetWebPreferences(ComputeWebPreferences());
2613#if defined(OS_ANDROID)
2614 for (FrameTreeNode* node : frame_tree_.Nodes()) {
2615 RenderFrameHostImpl* rfh = node->current_frame_host();
2616 if (rfh->is_local_root()) {
2617 if (auto* rwh = rfh->GetRenderWidgetHost())
2618 rwh->SetForceEnableZoom(web_preferences_->force_enable_zoom);
2619 }
2620 }
2621#endif
2622 updating_web_preferences_ = false;
2623}
2624
Ahmed Fakhryd70bf37b2018-04-04 17:07:242625void WebContentsImpl::NotifyPreferencesChanged() {
Alexander Timin5fdeff22020-09-08 09:20:372626 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyPreferencesChanged");
2627
Rakina Zata Amni347b70902020-07-22 10:49:042628 // Recompute the WebPreferences based on the current state of the WebContents,
Rakina Zata Amni4029b6d2020-07-28 02:36:202629 // etc. Note that OnWebPreferencesChanged will also call SetWebPreferences and
2630 // send the updated WebPreferences to all RenderViews for this WebContents.
2631 OnWebPreferencesChanged();
Ahmed Fakhryd70bf37b2018-04-04 17:07:242632}
2633
Bruce Long1e3e1f542019-10-16 17:56:282634void WebContentsImpl::SyncRendererPrefs() {
Alexander Timin5fdeff22020-09-08 09:20:372635 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SyncRendererPrefs");
2636
Peter Marshall2dc74e92020-07-29 20:02:302637 blink::mojom::RendererPreferences renderer_preferences = GetRendererPrefs();
Bruce Long1e3e1f542019-10-16 17:56:282638 RenderViewHostImpl::GetPlatformSpecificPrefs(&renderer_preferences);
2639 SendPageMessage(
2640 new PageMsg_SetRendererPrefs(MSG_ROUTING_NONE, renderer_preferences));
2641}
2642
Alexander Timin1cc31f42020-05-12 16:26:012643void WebContentsImpl::OnCookiesAccessed(NavigationHandle* navigation,
2644 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372645 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2646 "navigation_handle", navigation);
Alexander Timin90c20c32020-08-12 15:28:322647 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2648 observer->OnCookiesAccessed(navigation, details);
2649 });
Alexander Timin1cc31f42020-05-12 16:26:012650}
2651
2652void WebContentsImpl::OnCookiesAccessed(RenderFrameHostImpl* rfh,
2653 const CookieAccessDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372654 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnCookiesAccessed",
2655 "render_frame_host",
2656 base::trace_event::ToTracedValue(rfh));
Alexander Timin90c20c32020-08-12 15:28:322657 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2658 observer->OnCookiesAccessed(rfh, details);
2659 });
Josh Karlindaba39322019-07-17 23:24:332660}
2661
[email protected]b172aee2012-04-10 17:05:262662void WebContentsImpl::Stop() {
Alexander Timin5fdeff22020-09-08 09:20:372663 TRACE_EVENT0("content", "WebContentsImpl::Stop");
dcheng57e39e22016-01-21 00:25:382664 for (FrameTreeNode* node : frame_tree_.Nodes())
2665 node->StopLoading();
Alexander Timin90c20c32020-08-12 15:28:322666 observers_.ForEachObserver(
2667 [&](WebContentsObserver* observer) { observer->NavigationStopped(); });
[email protected]0bfbf882011-12-22 18:19:272668}
2669
Francois Doray47f759d2018-06-11 18:13:512670void WebContentsImpl::SetPageFrozen(bool frozen) {
Alexander Timin5fdeff22020-09-08 09:20:372671 TRACE_EVENT1("content", "WebContentsImpl::SetPageFrozen", "frozen", frozen);
2672
Francois Doray47f759d2018-06-11 18:13:512673 // A visible page is never frozen.
2674 DCHECK_NE(Visibility::VISIBLE, GetVisibility());
2675
Yuzu Saijo4fa1e9a2020-05-20 02:53:262676 for (auto& entry : frame_tree_.render_view_hosts()) {
2677 entry.second->SetIsFrozen(frozen);
2678 }
Fadi Meawada6573e02018-03-10 00:52:112679}
2680
erikchen6c7df7f7a2018-05-03 18:13:592681std::unique_ptr<WebContents> WebContentsImpl::Clone() {
Alexander Timin5fdeff22020-09-08 09:20:372682 TRACE_EVENT0("content", "WebContentsImpl::Clone");
2683
[email protected]14392a52012-05-02 20:28:442684 // We use our current SiteInstance since the cloned entry will use it anyway.
alexmose201c7cd2015-06-10 17:14:212685 // We pass our own opener so that the cloned page can access it if it was set
[email protected]ed245db2012-12-18 08:00:452686 // before.
[email protected]54944cde2012-12-09 09:24:592687 CreateParams create_params(GetBrowserContext(), GetSiteInstance());
Ian Clelland5cbaaf82017-11-27 22:00:032688 FrameTreeNode* opener = frame_tree_.root()->opener();
2689 RenderFrameHostImpl* opener_rfh = nullptr;
2690 if (opener)
2691 opener_rfh = opener->current_frame_host();
erikchen6c7df7f7a2018-05-03 18:13:592692 std::unique_ptr<WebContentsImpl> tc =
erikchen50735fd2018-05-05 15:08:332693 CreateWithOpener(create_params, opener_rfh);
Lucas Furukawa Gadani5553a152019-01-08 18:55:572694 tc->GetController().CopyStateFrom(&controller_, true);
Alexander Timin90c20c32020-08-12 15:28:322695 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2696 observer->DidCloneToNewWebContents(this, tc.get());
2697 });
[email protected]0bfbf882011-12-22 18:19:272698 return tc;
2699}
2700
[email protected]14392a52012-05-02 20:28:442701void WebContentsImpl::Observe(int type,
[email protected]8ff00d72012-10-23 19:12:212702 const NotificationSource& source,
2703 const NotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:372704 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Observe", "type", type);
[email protected]14392a52012-05-02 20:28:442705 switch (type) {
[email protected]8ff00d72012-10-23 19:12:212706 case NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED: {
2707 RenderWidgetHost* host = Source<RenderWidgetHost>(source).ptr();
[email protected]0b431992014-06-24 00:08:032708 RenderWidgetHostView* view = host->GetView();
2709 if (view == GetFullscreenRenderWidgetHostView()) {
2710 // We cannot just call view_->RestoreFocus() here. On some platforms,
2711 // attempting to focus the currently-invisible WebContentsView will be
2712 // flat-out ignored. Therefore, this boolean is used to track whether
2713 // we will request focus after the fullscreen widget has been
2714 // destroyed.
2715 fullscreen_widget_had_focus_at_shutdown_ = (view && view->HasFocus());
2716 } else {
alexmosc2a8cec2016-05-23 22:19:532717 for (auto i = pending_widget_views_.begin();
[email protected]0b431992014-06-24 00:08:032718 i != pending_widget_views_.end(); ++i) {
2719 if (host->GetView() == i->second) {
2720 pending_widget_views_.erase(i);
2721 break;
2722 }
[email protected]bafe6cd2012-05-23 23:09:502723 }
2724 }
2725 break;
2726 }
[email protected]14392a52012-05-02 20:28:442727 default:
2728 NOTREACHED();
2729 }
2730}
2731
[email protected]ec6c05f2013-10-23 18:41:572732WebContents* WebContentsImpl::GetWebContents() {
2733 return this;
2734}
2735
[email protected]54944cde2012-12-09 09:24:592736void WebContentsImpl::Init(const WebContents::CreateParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:372737 TRACE_EVENT0("content", "WebContentsImpl::Init");
2738
[email protected]fa944cb82013-11-15 17:51:212739 // This is set before initializing the render manager since
[email protected]b0936d22013-11-28 06:47:362740 // RenderFrameHostManager::Init calls back into us via its delegate to ask if
[email protected]fa944cb82013-11-15 17:51:212741 // it should be hidden.
Francois Doraye6161152018-03-27 22:05:372742 visibility_ =
2743 params.initially_hidden ? Visibility::HIDDEN : Visibility::VISIBLE;
[email protected]d6fa88f2013-10-18 16:00:432744
Sebastien Marchand28cf23182018-06-20 02:39:352745 if (!params.last_active_time.is_null())
2746 last_active_time_ = params.last_active_time;
2747
dcheng3ce04b62015-10-26 23:30:552748 scoped_refptr<SiteInstance> site_instance = params.site_instance;
2749 if (!site_instance)
2750 site_instance = SiteInstance::Create(params.browser_context);
Lukasz Anforowicz3caa8372018-06-05 17:22:072751 if (params.desired_renderer_state == CreateParams::kNoRendererProcess) {
2752 static_cast<SiteInstanceImpl*>(site_instance.get())
2753 ->PreventAssociationWithSpareProcess();
2754 }
dcheng3ce04b62015-10-26 23:30:552755
Fergal Dalycb0c1fdf2020-03-16 07:13:492756 GetRenderManager()->InitRoot(site_instance.get(),
2757 params.renderer_initiated_creation);
lukasza464d8692016-02-22 19:26:322758
lukasza5140a412016-09-15 21:12:302759 // blink::FrameTree::setName always keeps |unique_name| empty in case of a
2760 // main frame - let's do the same thing here.
2761 std::string unique_name;
lukasza464d8692016-02-22 19:26:322762 frame_tree_.root()->SetFrameName(params.main_frame_name, unique_name);
[email protected]d1198fd2012-08-13 22:50:192763
[email protected]fc2b46b2014-05-03 16:33:452764 WebContentsViewDelegate* delegate =
2765 GetContentClient()->browser()->GetWebContentsViewDelegate(this);
2766
W. James MacLean2539adb32019-12-13 00:40:442767 if (browser_plugin_guest_) {
sky52a39e342016-12-17 17:23:222768 view_.reset(new WebContentsViewChildFrame(
2769 this, delegate, &render_view_host_delegate_view_));
2770 } else {
2771 view_.reset(CreateWebContentsView(this, delegate,
2772 &render_view_host_delegate_view_));
[email protected]d1198fd2012-08-13 22:50:192773 }
[email protected]fc2b46b2014-05-03 16:33:452774 CHECK(render_view_host_delegate_view_);
[email protected]d1198fd2012-08-13 22:50:192775 CHECK(view_.get());
2776
danakjfc5184932019-09-12 18:08:322777 view_->CreateView(params.context);
[email protected]d1198fd2012-08-13 22:50:192778
brettw4b461082016-11-19 18:55:162779#if BUILDFLAG(ENABLE_PLUGINS)
Yuzu Saijoa11069a2020-04-22 10:56:552780 plugin_content_origin_allowlist_.reset(
2781 new PluginContentOriginAllowlist(this));
tommyclieb25b2a2014-11-03 19:45:092782#endif
2783
[email protected]d1198fd2012-08-13 22:50:192784 registrar_.Add(this,
[email protected]8ff00d72012-10-23 19:12:212785 NOTIFICATION_RENDER_WIDGET_HOST_DESTROYED,
2786 NotificationService::AllBrowserContextsAndSources());
[email protected]f28ef9a32014-05-12 16:36:102787
leon.hane4db177a2017-02-07 14:19:162788 screen_orientation_provider_.reset(new ScreenOrientationProvider(this));
[email protected]01f83f92014-06-17 14:41:542789
mfomitchev2b8b066a2016-01-28 19:23:152790#if defined(OS_ANDROID)
Oksana Zhuravlova0b634332019-10-28 23:04:222791 DateTimeChooserAndroid::CreateForWebContents(this);
[email protected]583418cc2013-01-17 14:01:102792#endif
fsamuel7310a4262014-12-05 05:06:442793
2794 // BrowserPluginGuest::Init needs to be called after this WebContents has
W. James MacLean6e78da342019-12-13 15:13:232795 // a RenderWidgetHostViewChildFrame. That is, |view_->CreateView| above.
fsamuel7310a4262014-12-05 05:06:442796 if (browser_plugin_guest_)
2797 browser_plugin_guest_->Init();
nickf9acfbe2014-12-23 19:12:372798
2799 for (size_t i = 0; i < g_created_callbacks.Get().size(); i++)
2800 g_created_callbacks.Get().at(i).Run(this);
naskob21fe4872015-02-24 14:15:562801
2802 // If the WebContents creation was renderer-initiated, it means that the
2803 // corresponding RenderView and main RenderFrame have already been created.
2804 // Ensure observers are notified about this.
2805 if (params.renderer_initiated_creation) {
Fergal Dalybb2d6592020-06-02 05:02:332806 GetRenderViewHost()->GetWidget()->set_renderer_initialized(true);
Alex Moshchuk27caae82017-09-11 23:11:182807 GetRenderViewHost()->DispatchRenderViewCreated();
naskob21fe4872015-02-24 14:15:562808 GetRenderManager()->current_frame_host()->SetRenderFrameCreated(true);
2809 }
naskof5940b9f2015-03-02 23:04:052810
lof84501da082016-05-23 21:22:542811 // Create the renderer process in advance if requested.
Lukasz Anforowicz3caa8372018-06-05 17:22:072812 if (params.desired_renderer_state ==
2813 CreateParams::kInitializeAndWarmupRendererProcess) {
lof84501da082016-05-23 21:22:542814 if (!GetRenderManager()->current_frame_host()->IsRenderFrameLive()) {
2815 GetRenderManager()->InitRenderView(GetRenderViewHost(), nullptr);
2816 }
2817 }
2818
naskof5940b9f2015-03-02 23:04:052819 // Ensure that observers are notified of the creation of this WebContents's
2820 // main RenderFrameHost. It must be done here for main frames, since the
2821 // NotifySwappedFromRenderManager expects view_ to already be created and that
2822 // happens after RenderFrameHostManager::Init.
2823 NotifySwappedFromRenderManager(
2824 nullptr, GetRenderManager()->current_frame_host(), true);
Albert J. Wonge76bf0b82019-09-27 07:47:062825
2826 // For WebContents that are never shown, do critical initialization here which
2827 // would normally only happen when the WebContents is shown.
2828 if (params.is_never_visible) {
2829 // This has just been created so there can only be one frame. Thus it is
2830 // safe to initialize the root.
2831 GetMainFrame()->Init();
2832 }
[email protected]d1198fd2012-08-13 22:50:192833}
2834
[email protected]7fff43e2013-05-21 20:21:102835void WebContentsImpl::OnWebContentsDestroyed(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372836 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnWebContentsDestroyed");
2837
[email protected]7fff43e2013-05-21 20:21:102838 RemoveDestructionObserver(web_contents);
2839
[email protected]ceee8cd2013-03-08 04:59:512840 // Clear a pending contents that has been closed before being shown.
alexmosc2a8cec2016-05-23 22:19:532841 for (auto iter = pending_contents_.begin(); iter != pending_contents_.end();
[email protected]ceee8cd2013-03-08 04:59:512842 ++iter) {
Joel Hockey8c2011b22020-04-30 05:07:192843 if (iter->second.contents.get() != web_contents)
[email protected]ceee8cd2013-03-08 04:59:512844 continue;
erikchenbee5c9622018-04-27 19:30:252845
2846 // Someone else has deleted the WebContents. That should never happen!
2847 // TODO(erikchen): Fix semantics here. https://crbug.com/832879.
Joel Hockey8c2011b22020-04-30 05:07:192848 iter->second.contents.release();
[email protected]ceee8cd2013-03-08 04:59:512849 pending_contents_.erase(iter);
[email protected]ceee8cd2013-03-08 04:59:512850 return;
2851 }
2852 NOTREACHED();
[email protected]14392a52012-05-02 20:28:442853}
2854
[email protected]7fff43e2013-05-21 20:21:102855void WebContentsImpl::AddDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372856 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2857 "WebContentsImpl::AddDestructionObserver");
2858
Jan Wilken Dörrie73c901e2019-06-12 09:02:322859 if (!base::Contains(destruction_observers_, web_contents)) {
[email protected]7fff43e2013-05-21 20:21:102860 destruction_observers_[web_contents] =
Jeremy Roman04f27c372017-10-27 15:20:552861 std::make_unique<DestructionObserver>(this, web_contents);
[email protected]7fff43e2013-05-21 20:21:102862 }
2863}
2864
2865void WebContentsImpl::RemoveDestructionObserver(WebContentsImpl* web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:372866 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2867 "WebContentsImpl::RemoveDestructionObserver");
avia8cf81982016-08-12 20:28:462868 destruction_observers_.erase(web_contents);
[email protected]7fff43e2013-05-21 20:21:102869}
2870
[email protected]b172aee2012-04-10 17:05:262871void WebContentsImpl::AddObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372872 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2873 "WebContentsImpl::AddObserver");
[email protected]be1f56ab2011-12-22 06:55:312874 observers_.AddObserver(observer);
2875}
2876
[email protected]b172aee2012-04-10 17:05:262877void WebContentsImpl::RemoveObserver(WebContentsObserver* observer) {
Alexander Timin5fdeff22020-09-08 09:20:372878 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
2879 "WebContentsImpl::RemoveObserver");
[email protected]be1f56ab2011-12-22 06:55:312880 observers_.RemoveObserver(observer);
2881}
2882
[email protected]948481d2014-06-11 18:32:222883std::set<RenderWidgetHostView*>
2884WebContentsImpl::GetRenderWidgetHostViewsInTree() {
2885 std::set<RenderWidgetHostView*> set;
Carlos IL07f282f2020-05-15 22:58:292886 for (RenderFrameHost* rfh : GetAllFrames()) {
2887 if (RenderWidgetHostView* rwhv = static_cast<RenderFrameHostImpl*>(rfh)
2888 ->frame_tree_node()
2889 ->render_manager()
2890 ->GetRenderWidgetHostView()) {
lfgf949e0e2017-05-10 22:18:112891 set.insert(rwhv);
dchengafb53e22016-02-04 08:11:082892 }
[email protected]948481d2014-06-11 18:32:222893 }
[email protected]de3c5d82014-05-28 22:12:592894 return set;
2895}
2896
Adithya Srinivasane6e7f842019-12-16 18:41:362897std::set<RenderWidgetHostView*>
2898WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree() {
2899 std::set<RenderWidgetHostView*> result;
2900 GetRenderWidgetHostViewsInWebContentsTree(result);
2901 return result;
2902}
2903
2904void WebContentsImpl::GetRenderWidgetHostViewsInWebContentsTree(
2905 std::set<RenderWidgetHostView*>& result) {
2906 std::set<RenderWidgetHostView*> views = GetRenderWidgetHostViewsInTree();
2907 result.insert(views.begin(), views.end());
2908 for (auto* inner_web_contents : GetInnerWebContents()) {
2909 static_cast<WebContentsImpl*>(inner_web_contents)
2910 ->GetRenderWidgetHostViewsInWebContentsTree(result);
2911 }
2912}
2913
[email protected]b172aee2012-04-10 17:05:262914void WebContentsImpl::Activate() {
Alexander Timin5fdeff22020-09-08 09:20:372915 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Activate");
[email protected]d5f942ba2008-09-26 19:30:342916 if (delegate_)
2917 delegate_->ActivateContents(this);
2918}
2919
avi3e4b8512015-11-11 01:55:492920void WebContentsImpl::LostCapture(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372921 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostCapture",
2922 "render_widget_host", render_widget_host);
avi3e4b8512015-11-11 01:55:492923 if (!RenderViewHostImpl::From(render_widget_host))
2924 return;
2925
[email protected]63954792011-07-11 04:17:482926 if (delegate_)
2927 delegate_->LostCapture();
2928}
2929
Yue Ru Sun979c4b162019-11-06 16:11:042930ukm::SourceId
2931WebContentsImpl::GetUkmSourceIdForLastCommittedSourceIncludingSameDocument()
2932 const {
2933 return last_committed_source_id_including_same_document_;
2934}
2935
Ahmed Fakhryfaa32d22018-10-05 15:56:162936void WebContentsImpl::SetTopControlsShownRatio(
2937 RenderWidgetHostImpl* render_widget_host,
2938 float ratio) {
Alexander Timin5fdeff22020-09-08 09:20:372939 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetTopControlsShownRatio",
2940 "render_widget_host", render_widget_host, "ratio",
2941 ratio);
Ahmed Fakhryfaa32d22018-10-05 15:56:162942 if (!delegate_)
2943 return;
2944
2945 RenderFrameHostImpl* rfh = GetMainFrame();
2946 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
2947 return;
2948
2949 delegate_->SetTopControlsShownRatio(this, ratio);
Ahmed Fakhry58e6ef542018-09-04 18:05:382950}
2951
Ahmed Fakhry58e6ef542018-09-04 18:05:382952void WebContentsImpl::SetTopControlsGestureScrollInProgress(bool in_progress) {
Alexander Timin5fdeff22020-09-08 09:20:372953 OPTIONAL_TRACE_EVENT1(
2954 "content", "WebContentsImpl::SetTopControlsGestureScrollInProgress",
2955 "in_progress", in_progress);
Ahmed Fakhry58e6ef542018-09-04 18:05:382956 if (delegate_)
2957 delegate_->SetTopControlsGestureScrollInProgress(in_progress);
2958}
2959
lazyboy63f5b312015-11-23 20:19:522960void WebContentsImpl::RenderWidgetCreated(
2961 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372962 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetCreated",
2963 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522964 created_widgets_.insert(render_widget_host);
2965}
2966
[email protected]b24b68a2012-09-24 21:57:262967void WebContentsImpl::RenderWidgetDeleted(
2968 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:372969 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetDeleted",
2970 "render_widget_host", render_widget_host);
lazyboy63f5b312015-11-23 20:19:522971 // Note that |is_being_destroyed_| can be true at this point as
2972 // ~WebContentsImpl() calls RFHM::ClearRFHsPendingShutdown(), which might lead
2973 // us here.
2974 created_widgets_.erase(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262975
lazyboy63f5b312015-11-23 20:19:522976 if (is_being_destroyed_)
2977 return;
[email protected]44470a22013-01-24 01:21:542978
2979 if (render_widget_host &&
alexmosc9e76ec2016-05-16 22:59:372980 render_widget_host->GetRoutingID() == fullscreen_widget_routing_id_ &&
2981 render_widget_host->GetProcess()->GetID() ==
2982 fullscreen_widget_process_id_) {
[email protected]4aebbca2013-09-17 22:26:492983 if (delegate_ && delegate_->EmbedsFullscreenWidget())
mlamouri7a78d6fd2015-01-17 13:23:532984 delegate_->ExitFullscreenModeForTab(this);
Alexander Timin90c20c32020-08-12 15:28:322985 observers_.ForEachObserver([&](WebContentsObserver* observer) {
2986 observer->DidDestroyFullscreenWidget();
2987 });
alexmosc9e76ec2016-05-16 22:59:372988 fullscreen_widget_process_id_ = ChildProcessHost::kInvalidUniqueID;
[email protected]44470a22013-01-24 01:21:542989 fullscreen_widget_routing_id_ = MSG_ROUTING_NONE;
[email protected]0b431992014-06-24 00:08:032990 if (fullscreen_widget_had_focus_at_shutdown_)
2991 view_->RestoreFocus();
[email protected]44470a22013-01-24 01:21:542992 }
lfgbee1e0a2016-06-08 21:24:212993
lfg7d4caad2017-03-22 09:01:452994 if (render_widget_host == mouse_lock_widget_)
lfgff8dfc8d2016-10-21 17:42:322995 LostMouseLock(mouse_lock_widget_);
Joe Downing192998b22018-03-22 15:51:362996
Joe Downingc1a57efe2018-05-09 18:23:542997 CancelKeyboardLock(render_widget_host);
[email protected]b24b68a2012-09-24 21:57:262998}
2999
miu9e14e492014-10-25 02:39:043000void WebContentsImpl::RenderWidgetGotFocus(
3001 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373002 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetGotFocus",
3003 "render_widget_host", render_widget_host);
calamity7fe55ce2015-04-10 03:59:373004 // Notify the observers if an embedded fullscreen widget was focused.
3005 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
3006 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
Michael Thiessen896405db2017-07-20 17:52:323007 NotifyWebContentsFocused(render_widget_host);
calamity7fe55ce2015-04-10 03:59:373008 }
miu9e14e492014-10-25 02:39:043009}
3010
zijiehe3bee08e22017-05-17 04:14:463011void WebContentsImpl::RenderWidgetLostFocus(
3012 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373013 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderWidgetLostFocus",
3014 "render_widget_host", render_widget_host);
Michael Thiessen896405db2017-07-20 17:52:323015 // Notify the observers if an embedded fullscreen widget lost focus.
3016 if (delegate_ && render_widget_host && delegate_->EmbedsFullscreenWidget() &&
3017 render_widget_host->GetView() == GetFullscreenRenderWidgetHostView()) {
3018 NotifyWebContentsLostFocus(render_widget_host);
3019 }
zijiehe3bee08e22017-05-17 04:14:463020}
3021
estaded0a0c992015-01-21 14:12:063022void WebContentsImpl::RenderWidgetWasResized(
rouslan2f5993f2015-01-29 00:18:313023 RenderWidgetHostImpl* render_widget_host,
3024 bool width_changed) {
Alexander Timin5fdeff22020-09-08 09:20:373025 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderWidgetWasResized",
3026 "render_widget_host", render_widget_host,
3027 "width_changed", width_changed);
creisc014b402015-04-23 16:41:453028 RenderFrameHostImpl* rfh = GetMainFrame();
estadece344ec2015-01-23 00:12:293029 if (!rfh || render_widget_host != rfh->GetRenderWidgetHost())
estaded0a0c992015-01-21 14:12:063030 return;
estaded0a0c992015-01-21 14:12:063031
Alexander Timin90c20c32020-08-12 15:28:323032 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3033 observer->MainFrameWasResized(width_changed);
3034 });
estaded0a0c992015-01-21 14:12:063035}
3036
skyf65d9bb2017-03-24 02:26:393037KeyboardEventProcessingResult WebContentsImpl::PreHandleKeyboardEvent(
3038 const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373039 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3040 "WebContentsImpl::PreHandleKeyboardEvent");
W. James MacLeane1187272019-11-12 03:42:483041 auto* outermost_contents = GetOutermostWebContents();
3042 // TODO(wjmaclean): Generalize this to forward all key events to the outermost
3043 // delegate's handler.
Avi Drissman97aef042020-06-30 21:04:483044 if (outermost_contents != this && IsFullscreen() &&
W. James MacLeane1187272019-11-12 03:42:483045 event.windows_key_code == ui::VKEY_ESCAPE) {
3046 // When an inner WebContents has focus and is fullscreen, redirect <esc>
3047 // key events to the outermost WebContents so it can be handled by that
3048 // WebContents' delegate.
3049 if (outermost_contents->PreHandleKeyboardEvent(event) ==
3050 KeyboardEventProcessingResult::HANDLED) {
3051 return KeyboardEventProcessingResult::HANDLED;
3052 }
3053 }
skyf65d9bb2017-03-24 02:26:393054 return delegate_ ? delegate_->PreHandleKeyboardEvent(this, event)
3055 : KeyboardEventProcessingResult::NOT_HANDLED;
[email protected]63954792011-07-11 04:17:483056}
3057
Dave Tapuska344399e2019-09-09 15:18:263058bool WebContentsImpl::HandleMouseEvent(const blink::WebMouseEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373059 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3060 "WebContentsImpl::HandleMouseEvent");
Dave Tapuska344399e2019-09-09 15:18:263061 // Handle mouse button back/forward in the browser process after the render
3062 // process is done with the event. This ensures all renderer-initiated history
3063 // navigations can be treated consistently.
3064 if (event.GetType() == blink::WebInputEvent::Type::kMouseUp) {
3065 WebContentsImpl* outermost = GetOutermostWebContents();
3066 if (event.button == blink::WebPointerProperties::Button::kBack &&
3067 outermost->controller_.CanGoBack()) {
3068 outermost->controller_.GoBack();
3069 return true;
3070 } else if (event.button == blink::WebPointerProperties::Button::kForward &&
3071 outermost->controller_.CanGoForward()) {
3072 outermost->controller_.GoForward();
3073 return true;
3074 }
3075 }
3076 return false;
3077}
3078
Scott Violetd5caa872018-10-16 22:00:513079bool WebContentsImpl::HandleKeyboardEvent(const NativeWebKeyboardEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373080 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3081 "WebContentsImpl::HandleKeyboardEvent");
[email protected]0b094002014-08-20 18:28:103082 if (browser_plugin_embedder_ &&
3083 browser_plugin_embedder_->HandleKeyboardEvent(event)) {
Scott Violetd5caa872018-10-16 22:00:513084 return true;
[email protected]0b094002014-08-20 18:28:103085 }
Scott Violetd5caa872018-10-16 22:00:513086 return delegate_ && delegate_->HandleKeyboardEvent(this, event);
[email protected]63954792011-07-11 04:17:483087}
3088
Alexander Timin5fdeff22020-09-08 09:20:373089bool WebContentsImpl::HandleWheelEvent(const blink::WebMouseWheelEvent& event) {
3090 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3091 "WebContentsImpl::HandleWheelEvent");
Avi Drissman7c57be72020-07-29 20:09:463092#if !defined(OS_MAC)
lanweia93644f2015-01-21 22:00:333093 // On platforms other than Mac, control+mousewheel may change zoom. On Mac,
3094 // this isn't done for two reasons:
[email protected]bccc4472013-04-18 16:37:193095 // -the OS already has a gesture to do this through pinch-zoom
3096 // -if a user starts an inertial scroll, let's go, and presses control
3097 // (i.e. control+tab) then the OS's buffered scroll events will come in
3098 // with control key set which isn't what the user wants
Blink Reformat1c4d759e2017-04-09 16:34:543099 if (delegate_ && event.wheel_ticks_y &&
Ehsan Karamad0f83cb112018-09-06 22:07:363100 event.event_action == blink::WebMouseWheelEvent::EventAction::kPageZoom) {
w.shackleton49bcd392016-01-06 17:38:223101 // Count only integer cumulative scrolls as zoom events; this handles
3102 // smooth scroll and regular scroll device behavior.
Blink Reformat1c4d759e2017-04-09 16:34:543103 zoom_scroll_remainder_ += event.wheel_ticks_y;
w.shackleton49bcd392016-01-06 17:38:223104 int whole_zoom_scroll_remainder_ = std::lround(zoom_scroll_remainder_);
3105 zoom_scroll_remainder_ -= whole_zoom_scroll_remainder_;
3106 if (whole_zoom_scroll_remainder_ != 0) {
3107 delegate_->ContentsZoomChange(whole_zoom_scroll_remainder_ > 0);
3108 }
[email protected]fb3f066e2013-02-12 19:12:523109 return true;
3110 }
[email protected]bccc4472013-04-18 16:37:193111#endif
[email protected]fb3f066e2013-02-12 19:12:523112 return false;
3113}
3114
[email protected]04bce562014-01-30 05:34:543115bool WebContentsImpl::PreHandleGestureEvent(
3116 const blink::WebGestureEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:373117 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
3118 "WebContentsImpl::PreHandleGestureEvent");
[email protected]28042d32014-02-03 14:10:033119 return delegate_ && delegate_->PreHandleGestureEvent(this, event);
[email protected]04bce562014-01-30 05:34:543120}
3121
kenrb2a565f82015-09-02 20:24:593122RenderWidgetHostInputEventRouter* WebContentsImpl::GetInputEventRouter() {
wjmacleane31234f2015-12-14 17:20:453123 if (!is_being_destroyed_ && GetOuterWebContents())
3124 return GetOuterWebContents()->GetInputEventRouter();
3125
3126 if (!rwh_input_event_router_.get() && !is_being_destroyed_)
kenrb2a565f82015-09-02 20:24:593127 rwh_input_event_router_.reset(new RenderWidgetHostInputEventRouter);
3128 return rwh_input_event_router_.get();
3129}
3130
alexmos3fcd0ca2015-10-23 18:18:333131void WebContentsImpl::ReplicatePageFocus(bool is_focused) {
Alexander Timin5fdeff22020-09-08 09:20:373132 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ReplicatePageFocus",
3133 "is_focused", is_focused);
alexmos3fcd0ca2015-10-23 18:18:333134 // Focus loss may occur while this WebContents is being destroyed. Don't
3135 // send the message in this case, as the main frame's RenderFrameHost and
3136 // other state has already been cleared.
3137 if (is_being_destroyed_)
3138 return;
3139
3140 frame_tree_.ReplicatePageFocus(is_focused);
3141}
3142
alexmosc4cbacb2015-11-21 01:29:223143RenderWidgetHostImpl* WebContentsImpl::GetFocusedRenderWidgetHost(
3144 RenderWidgetHostImpl* receiving_widget) {
alexmosc4cbacb2015-11-21 01:29:223145 // Events for widgets other than the main frame (e.g., popup menus) should be
3146 // forwarded directly to the widget they arrived on.
3147 if (receiving_widget != GetMainFrame()->GetRenderWidgetHost())
3148 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523149
paulmeyerfeafc2d2017-04-25 21:46:403150 // If the focused WebContents is a guest WebContents, then get the focused
3151 // frame in the embedder WebContents instead.
W. James MacLean13d834d2019-12-04 16:06:453152 FrameTreeNode* focused_frame =
3153 GetFocusedWebContents()->frame_tree_.GetFocusedFrame();
lfg1453e412017-04-11 00:48:503154
alexmosc4d183e2015-11-06 00:46:523155 if (!focused_frame)
alexmosc4cbacb2015-11-21 01:29:223156 return receiving_widget;
alexmosc4d183e2015-11-06 00:46:523157
alexmos732ca3a2015-12-08 02:01:023158 // The view may be null if a subframe's renderer process has crashed while
3159 // the subframe has focus. Drop the event in that case. Do not give
3160 // it to the main frame, so that the user doesn't unexpectedly type into the
3161 // wrong frame if a focused subframe renderer crashes while they type.
3162 RenderWidgetHostView* view = focused_frame->current_frame_host()->GetView();
3163 if (!view)
3164 return nullptr;
3165
3166 return RenderWidgetHostImpl::From(view->GetRenderWidgetHost());
alexmosc4d183e2015-11-06 00:46:523167}
3168
avallee9993fca2016-11-17 06:16:503169RenderWidgetHostImpl* WebContentsImpl::GetRenderWidgetHostWithPageFocus() {
lfg1453e412017-04-11 00:48:503170 WebContentsImpl* focused_web_contents = GetFocusedWebContents();
3171
lfg1453e412017-04-11 00:48:503172 return focused_web_contents->GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:503173}
3174
Avi Drissmand1d25652020-03-06 21:28:583175bool WebContentsImpl::CanEnterFullscreenMode() {
Avi Drissman33972942020-06-19 14:16:013176 // It's possible that this WebContents was spawned while blocking UI was on
3177 // the screen, or that it was downstream from a WebContents when UI was
3178 // blocked. Therefore, disqualify it from fullscreen if it or any upstream
3179 // WebContents has an active blocker.
3180 auto openers = GetAllOpeningWebContents(this);
3181 return std::all_of(openers.begin(), openers.end(), [](auto* opener) {
3182 return opener->fullscreen_blocker_count_ == 0;
3183 });
Avi Drissmand1d25652020-03-06 21:28:583184}
3185
Dave Tapuska3ed44192018-05-01 18:53:303186void WebContentsImpl::EnterFullscreenMode(
Mike Wasserman4ca09792020-05-29 17:44:433187 RenderFrameHost* requesting_frame,
Dave Tapuskaa4189512019-10-15 20:27:343188 const blink::mojom::FullscreenOptions& options) {
Alexander Timin5fdeff22020-09-08 09:20:373189 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterFullscreenMode");
Avi Drissmand1d25652020-03-06 21:28:583190 DCHECK(CanEnterFullscreenMode());
3191
mlamouri7a78d6fd2015-01-17 13:23:533192 // This method is being called to enter renderer-initiated fullscreen mode.
3193 // Make sure any existing fullscreen widget is shut down first.
[email protected]4aebbca2013-09-17 22:26:493194 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373195 if (widget_view) {
3196 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3197 ->ShutdownAndDestroyWidget(true);
3198 }
[email protected]4aebbca2013-09-17 22:26:493199
Joe Downing13dd76b2018-04-09 18:32:153200 if (delegate_) {
Mike Wasserman4ca09792020-05-29 17:44:433201 delegate_->EnterFullscreenModeForTab(requesting_frame, options);
mlamouri7a78d6fd2015-01-17 13:23:533202
Joe Downing13dd76b2018-04-09 18:32:153203 if (keyboard_lock_widget_)
3204 delegate_->RequestKeyboardLock(this, esc_key_locked_);
3205 }
3206
Alexander Timin90c20c32020-08-12 15:28:323207 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3208 observer->DidToggleFullscreenModeForTab(IsFullscreen(), false);
3209 });
Avi Drissman33972942020-06-19 14:16:013210 FullscreenContentsSet(GetBrowserContext())->insert(this);
mlamouri7a78d6fd2015-01-17 13:23:533211}
3212
bokanece34a82016-01-28 19:49:463213void WebContentsImpl::ExitFullscreenMode(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:373214 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ExitFullscreenMode",
3215 "will_cause_resize", will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:533216 // This method is being called to leave renderer-initiated fullscreen mode.
3217 // Make sure any existing fullscreen widget is shut down first.
3218 RenderWidgetHostView* const widget_view = GetFullscreenRenderWidgetHostView();
avi85a4cef2015-12-18 20:13:373219 if (widget_view) {
3220 RenderWidgetHostImpl::From(widget_view->GetRenderWidgetHost())
3221 ->ShutdownAndDestroyWidget(true);
3222 }
mlamouri7a78d6fd2015-01-17 13:23:533223
Joe Downing13dd76b2018-04-09 18:32:153224 if (delegate_) {
mlamouri7a78d6fd2015-01-17 13:23:533225 delegate_->ExitFullscreenModeForTab(this);
[email protected]657c8e02014-03-19 19:18:373226
Joe Downing13dd76b2018-04-09 18:32:153227 if (keyboard_lock_widget_)
3228 delegate_->CancelKeyboardLockRequest(this);
3229 }
3230
bokanece34a82016-01-28 19:49:463231 // The fullscreen state is communicated to the renderer through a resize
3232 // message. If the change in fullscreen state doesn't cause a view resize
3233 // then we must ensure web contents exit the fullscreen state by explicitly
3234 // sending a resize message. This is required for the situation of the browser
3235 // moving the view into a "browser fullscreen" state and then the contents
3236 // entering "tab fullscreen". Exiting the contents "tab fullscreen" then won't
3237 // have the side effect of the view resizing, hence the explicit call here is
3238 // required.
3239 if (!will_cause_resize) {
3240 if (RenderWidgetHostView* rwhv = GetRenderWidgetHostView()) {
3241 if (RenderWidgetHost* render_widget_host = rwhv->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:163242 render_widget_host->SynchronizeVisualProperties();
bokanece34a82016-01-28 19:49:463243 }
scheib3dcb6c932015-02-23 10:55:583244 }
3245
Arthur Sonzogni929d29f2018-09-17 14:19:443246 current_fullscreen_frame_ = nullptr;
Becca Hughese9e27952018-06-25 17:08:273247
Alexander Timin90c20c32020-08-12 15:28:323248 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3249 observer->DidToggleFullscreenModeForTab(IsFullscreen(), will_cause_resize);
3250 });
Becca Hughesd11d6502018-07-31 17:01:283251
3252 if (display_cutout_host_impl_)
3253 display_cutout_host_impl_->DidExitFullscreen();
Avi Drissman33972942020-06-19 14:16:013254
3255 FullscreenContentsSet(GetBrowserContext())->erase(this);
[email protected]8a5e0ca2011-08-25 06:30:473256}
3257
Becca Hughesfd5d8f892018-06-14 18:23:363258void WebContentsImpl::FullscreenStateChanged(RenderFrameHost* rfh,
3259 bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:373260 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::FullscreenStateChanged",
3261 "render_frame_host", rfh, "is_fullscreen",
3262 is_fullscreen);
Arthur Sonzogni929d29f2018-09-17 14:19:443263 RenderFrameHostImpl* frame = static_cast<RenderFrameHostImpl*>(rfh);
Becca Hughesfd5d8f892018-06-14 18:23:363264
3265 if (is_fullscreen) {
Jan Wilken Dörrie531be7ca2019-06-07 10:05:573266 if (!base::Contains(fullscreen_frames_, frame)) {
Arthur Sonzogni929d29f2018-09-17 14:19:443267 fullscreen_frames_.insert(frame);
3268 FullscreenFrameSetUpdated();
Becca Hughesfd5d8f892018-06-14 18:23:363269 }
Arthur Sonzogni929d29f2018-09-17 14:19:443270 return;
3271 }
Becca Hughesfd5d8f892018-06-14 18:23:363272
Arthur Sonzogni929d29f2018-09-17 14:19:443273 // If |frame| is no longer in fullscreen, remove it and any descendants.
3274 // See https://fullscreen.spec.whatwg.org.
Arthur Sonzogni969a794e2018-10-11 08:56:093275 size_t size_before_deletion = fullscreen_frames_.size();
3276 base::EraseIf(fullscreen_frames_, [&](RenderFrameHostImpl* current) {
3277 return (current == frame || current->IsDescendantOf(frame));
Arthur Sonzogni929d29f2018-09-17 14:19:443278 });
3279
Arthur Sonzogni969a794e2018-10-11 08:56:093280 if (size_before_deletion != fullscreen_frames_.size())
Arthur Sonzogni929d29f2018-09-17 14:19:443281 FullscreenFrameSetUpdated();
3282}
3283
3284void WebContentsImpl::FullscreenFrameSetUpdated() {
Alexander Timin5fdeff22020-09-08 09:20:373285 OPTIONAL_TRACE_EVENT0("content",
3286 "WebContentsImpl::FullscreenFrameSetUpdated");
Arthur Sonzogni929d29f2018-09-17 14:19:443287 if (fullscreen_frames_.empty()) {
3288 current_fullscreen_frame_ = nullptr;
3289 return;
Becca Hughesfd5d8f892018-06-14 18:23:363290 }
3291
Arthur Sonzogni929d29f2018-09-17 14:19:443292 // Find the current fullscreen frame and call the observers.
3293 // If frame A is fullscreen, then frame B goes into inner fullscreen, then B
3294 // exits fullscreen - that will result in A being fullscreen.
3295 RenderFrameHostImpl* new_fullscreen_frame = *std::max_element(
3296 fullscreen_frames_.begin(), fullscreen_frames_.end(), FrameCompareDepth);
Becca Hughesfd5d8f892018-06-14 18:23:363297
Arthur Sonzogni929d29f2018-09-17 14:19:443298 // If we have already notified observers about this frame then we should not
3299 // fire the observers again.
3300 if (new_fullscreen_frame == current_fullscreen_frame_)
3301 return;
3302 current_fullscreen_frame_ = new_fullscreen_frame;
Becca Hughesfd5d8f892018-06-14 18:23:363303
Alexander Timin90c20c32020-08-12 15:28:323304 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3305 observer->DidAcquireFullscreen(new_fullscreen_frame);
3306 });
Arthur Sonzogni929d29f2018-09-17 14:19:443307 if (display_cutout_host_impl_)
3308 display_cutout_host_impl_->DidAcquireFullscreen(new_fullscreen_frame);
Becca Hughesfd5d8f892018-06-14 18:23:363309}
3310
Collin Baker989e0882019-11-01 01:27:173311void WebContentsImpl::UpdateVisibilityAndNotifyPageAndView(
3312 Visibility new_visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373313 OPTIONAL_TRACE_EVENT1("content",
3314 "WebContentsImpl::UpdateVisibilityAndNotifyPageAndView",
3315 "new_visibility", static_cast<int>(new_visibility));
Collin Baker989e0882019-11-01 01:27:173316 // Only hide the page if there are no entities capturing screenshots
Collin Bakerc5259962019-11-14 17:51:583317 // or video (e.g. mirroring). If there are, apply the correct state of
3318 // kHidden or kHiddenButPainting.
3319 PageVisibilityState page_visibility;
3320 if (new_visibility == Visibility::VISIBLE || visible_capturer_count_ > 0)
3321 page_visibility = PageVisibilityState::kVisible;
3322 else if (hidden_capturer_count_ > 0)
3323 page_visibility = PageVisibilityState::kHiddenButPainting;
3324 else
3325 page_visibility = PageVisibilityState::kHidden;
Collin Baker989e0882019-11-01 01:27:173326 // If there are entities in Picture-in-Picture mode, don't activate
3327 // the "disable rendering" optimization.
Collin Bakerc5259962019-11-14 17:51:583328 const bool view_is_visible =
3329 page_visibility != PageVisibilityState::kHidden ||
3330 HasPictureInPictureVideo();
Collin Baker989e0882019-11-01 01:27:173331
Collin Bakerc5259962019-11-14 17:51:583332 if (page_visibility != PageVisibilityState::kHidden) {
Dana Friedcf3bc8e2019-11-13 20:00:243333 // We cannot show a page or capture video unless there is a valid renderer
3334 // associated with this web contents. The navigation controller for this
3335 // page must be set to active (allowing navigation to complete, a renderer
3336 // and its associated views to be created, etc.) if any of these conditions
3337 // holds.
3338 //
3339 // Previously, it was possible for browser-side code to try to capture video
3340 // from a restored tab (for a variety of reasons, including the browser
3341 // creating preview thumbnails) and the tab would never actually load. By
Collin Bakerc5259962019-11-14 17:51:583342 // keying this behavior off of |page_visibility| instead of just
Dana Friedcf3bc8e2019-11-13 20:00:243343 // |new_visibility| we avoid this case. See crbug.com/1020782 for more
3344 // context.
3345 controller_.SetActive(true);
3346
3347 // This shows the Page before showing the individual RenderWidgets, as
3348 // RenderWidgets will work to produce compositor frames and handle input
3349 // as soon as they are shown. But the Page and other classes do not expect
3350 // to be producing frames when the Page is hidden. So we make sure the Page
3351 // is shown first.
Yuzu Saijo232076f2020-05-29 07:14:023352 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3353 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563354 }
Collin Baker98457b52019-11-06 21:34:293355 }
Collin Baker989e0882019-11-01 01:27:173356
3357 // |GetRenderWidgetHostView()| can be null if the user middle clicks a link to
3358 // open a tab in the background, then closes the tab before selecting it.
3359 // This is because closing the tab calls WebContentsImpl::Destroy(), which
3360 // removes the |GetRenderViewHost()|; then when we actually destroy the
3361 // window, OnWindowPosChanged() notices and calls WasHidden() (which
3362 // calls us).
3363 if (auto* view = GetRenderWidgetHostView()) {
3364 if (view_is_visible) {
3365 view->Show();
Collin Baker989e0882019-11-01 01:27:173366 } else if (new_visibility == Visibility::HIDDEN) {
3367 view->Hide();
3368 } else {
3369 view->WasOccluded();
3370 }
3371 }
3372
Carlos IL07f282f2020-05-15 22:58:293373 SetVisibilityForChildViews(view_is_visible);
Collin Baker989e0882019-11-01 01:27:173374
3375 // Make sure to call SetVisibilityAndNotifyObservers(VISIBLE) before notifying
3376 // the CrossProcessFrameConnector.
3377 if (new_visibility == Visibility::VISIBLE) {
3378 last_active_time_ = base::TimeTicks::Now();
3379 SetVisibilityAndNotifyObservers(new_visibility);
3380 }
3381
Collin Bakerc5259962019-11-14 17:51:583382 if (page_visibility == PageVisibilityState::kHidden) {
Collin Baker989e0882019-11-01 01:27:173383 // Similar to when showing the page, we only hide the page after
3384 // hiding the individual RenderWidgets.
Yuzu Saijo232076f2020-05-29 07:14:023385 for (auto* rvh : GetRenderViewHostsIncludingBackForwardCached()) {
3386 rvh->SetVisibility(page_visibility);
Yuzu Saijobe024af02020-05-11 07:35:563387 }
3388
Collin Baker989e0882019-11-01 01:27:173389 } else {
3390 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3391 RenderFrameProxyHost* parent = node->render_manager()->GetProxyToParent();
3392 if (!parent)
3393 continue;
3394
3395 parent->cross_process_frame_connector()->DelegateWasShown();
3396 }
3397 }
3398
3399 if (new_visibility != Visibility::VISIBLE)
3400 SetVisibilityAndNotifyObservers(new_visibility);
3401}
3402
Clark DuValla0e42992018-09-17 17:00:113403#if defined(OS_ANDROID)
3404void WebContentsImpl::UpdateUserGestureCarryoverInfo() {
Alexander Timin5fdeff22020-09-08 09:20:373405 OPTIONAL_TRACE_EVENT0("content",
3406 "WebContentsImpl::UpdateUserGestureCarryoverInfo");
Clark DuValla0e42992018-09-17 17:00:113407 if (delegate_)
3408 delegate_->UpdateUserGestureCarryoverInfo(this);
3409}
3410#endif
3411
Avi Drissman97aef042020-06-30 21:04:483412bool WebContentsImpl::IsFullscreen() {
[email protected]199bba6e2012-04-04 16:19:383413 return delegate_ ? delegate_->IsFullscreenForTabOrPending(this) : false;
[email protected]5d5f7af2011-10-01 01:38:123414}
3415
Malay Keshav87c42c02019-01-15 08:37:473416bool WebContentsImpl::ShouldShowStaleContentOnEviction() {
3417 return GetDelegate() && GetDelegate()->ShouldShowStaleContentOnEviction(this);
3418}
3419
danakj45d42452020-04-08 17:24:183420blink::mojom::DisplayMode WebContentsImpl::GetDisplayMode() const {
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123421 return delegate_ ? delegate_->GetDisplayMode(this)
Eric Willigers052f0432019-10-04 04:06:573422 : blink::mojom::DisplayMode::kBrowser;
mikhail.pozdnyakovc0e251b2015-04-15 06:51:123423}
3424
avic3aa8422015-11-09 20:57:223425void WebContentsImpl::RequestToLockMouse(
3426 RenderWidgetHostImpl* render_widget_host,
3427 bool user_gesture,
lfgad8244352016-07-13 16:55:513428 bool last_unlocked_by_target,
3429 bool privileged) {
Alexander Timin5fdeff22020-09-08 09:20:373430 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestToLockMouse",
3431 "render_widget_host", render_widget_host, "privileged",
3432 privileged);
lfgf0cd46e2017-01-04 00:05:233433 for (WebContentsImpl* current = this; current;
3434 current = current->GetOuterWebContents()) {
3435 if (current->mouse_lock_widget_) {
James Hollyerd5c9de462020-03-10 19:02:453436 render_widget_host->GotResponseToLockMouseRequest(
3437 blink::mojom::PointerLockResult::kAlreadyLocked);
lfgf0cd46e2017-01-04 00:05:233438 return;
3439 }
[email protected]e9621112011-10-17 05:38:373440 }
avic3aa8422015-11-09 20:57:223441
lfgad8244352016-07-13 16:55:513442 if (privileged) {
lfgf0cd46e2017-01-04 00:05:233443 DCHECK(!GetOuterWebContents());
lfgad8244352016-07-13 16:55:513444 mouse_lock_widget_ = render_widget_host;
James Hollyerd5c9de462020-03-10 19:02:453445 render_widget_host->GotResponseToLockMouseRequest(
3446 blink::mojom::PointerLockResult::kSuccess);
lfgad8244352016-07-13 16:55:513447 return;
3448 }
3449
lfgbee1e0a2016-06-08 21:24:213450 bool widget_in_frame_tree = false;
3451 for (FrameTreeNode* node : frame_tree_.Nodes()) {
3452 if (node->current_frame_host()->GetRenderWidgetHost() ==
3453 render_widget_host) {
3454 widget_in_frame_tree = true;
3455 break;
3456 }
3457 }
3458
3459 if (widget_in_frame_tree && delegate_) {
lfgf0cd46e2017-01-04 00:05:233460 for (WebContentsImpl* current = this; current;
3461 current = current->GetOuterWebContents()) {
3462 current->mouse_lock_widget_ = render_widget_host;
3463 }
3464
avic3aa8422015-11-09 20:57:223465 delegate_->RequestToLockMouse(this, user_gesture, last_unlocked_by_target);
lfgbee1e0a2016-06-08 21:24:213466 } else {
James Hollyerd5c9de462020-03-10 19:02:453467 render_widget_host->GotResponseToLockMouseRequest(
3468 blink::mojom::PointerLockResult::kWrongDocument);
lfgbee1e0a2016-06-08 21:24:213469 }
[email protected]e9621112011-10-17 05:38:373470}
3471
avi3e4b8512015-11-11 01:55:493472void WebContentsImpl::LostMouseLock(RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373473 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LostMouseLock",
3474 "render_widget_host", render_widget_host);
lfgbee1e0a2016-06-08 21:24:213475 CHECK(mouse_lock_widget_);
lfgf0cd46e2017-01-04 00:05:233476
3477 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this)
3478 return mouse_lock_widget_->delegate()->LostMouseLock(render_widget_host);
3479
lfgbee1e0a2016-06-08 21:24:213480 mouse_lock_widget_->SendMouseLockLost();
lfgf0cd46e2017-01-04 00:05:233481 for (WebContentsImpl* current = this; current;
3482 current = current->GetOuterWebContents()) {
3483 current->mouse_lock_widget_ = nullptr;
3484 }
avi3e4b8512015-11-11 01:55:493485
[email protected]e9621112011-10-17 05:38:373486 if (delegate_)
3487 delegate_->LostMouseLock();
3488}
3489
lfgad8244352016-07-13 16:55:513490bool WebContentsImpl::HasMouseLock(RenderWidgetHostImpl* render_widget_host) {
3491 // To verify if the mouse is locked, the mouse_lock_widget_ needs to be
3492 // assigned to the widget that requested the mouse lock, and the top-level
3493 // platform RenderWidgetHostView needs to hold the mouse lock from the OS.
Lucas Gadania0ea0172018-09-20 18:31:373494 auto* widget_host = GetTopLevelRenderWidgetHostView();
3495 return mouse_lock_widget_ == render_widget_host && widget_host &&
3496 widget_host->IsMouseLocked();
lfgad8244352016-07-13 16:55:513497}
3498
lfg84763c92017-02-16 18:55:153499RenderWidgetHostImpl* WebContentsImpl::GetMouseLockWidget() {
Lucas Gadania0ea0172018-09-20 18:31:373500 auto* widget_host = GetTopLevelRenderWidgetHostView();
3501 if ((widget_host && widget_host->IsMouseLocked()) ||
lfge2176fb2017-03-26 00:45:473502 (GetFullscreenRenderWidgetHostView() &&
Lucas Gadania0ea0172018-09-20 18:31:373503 GetFullscreenRenderWidgetHostView()->IsMouseLocked())) {
lfg84763c92017-02-16 18:55:153504 return mouse_lock_widget_;
Lucas Gadania0ea0172018-09-20 18:31:373505 }
lfg84763c92017-02-16 18:55:153506
3507 return nullptr;
3508}
3509
Joe Downing192998b22018-03-22 15:51:363510bool WebContentsImpl::RequestKeyboardLock(
Joe Downing13dd76b2018-04-09 18:32:153511 RenderWidgetHostImpl* render_widget_host,
3512 bool esc_key_locked) {
Alexander Timin5fdeff22020-09-08 09:20:373513 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RequestKeyboardLock",
3514 "render_widget_host", render_widget_host,
3515 "esc_key_locked", esc_key_locked);
Joe Downing192998b22018-03-22 15:51:363516 DCHECK(render_widget_host);
Joe Downing192998b22018-03-22 15:51:363517 if (render_widget_host->delegate()->GetAsWebContents() != this) {
3518 NOTREACHED();
3519 return false;
3520 }
3521
3522 // KeyboardLock is only supported when called by the top-level browsing
3523 // context and is not supported in embedded content scenarios.
3524 if (GetOuterWebContents())
3525 return false;
3526
Joe Downing13dd76b2018-04-09 18:32:153527 esc_key_locked_ = esc_key_locked;
Joe Downing192998b22018-03-22 15:51:363528 keyboard_lock_widget_ = render_widget_host;
3529
Joe Downing13dd76b2018-04-09 18:32:153530 if (delegate_)
3531 delegate_->RequestKeyboardLock(this, esc_key_locked_);
Joe Downing192998b22018-03-22 15:51:363532 return true;
3533}
3534
3535void WebContentsImpl::CancelKeyboardLock(
3536 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:373537 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::CancelKeyboardLockRequest",
3538 "render_widget_host", render_widget_host);
Joe Downing192998b22018-03-22 15:51:363539 if (!keyboard_lock_widget_ || render_widget_host != keyboard_lock_widget_)
3540 return;
3541
3542 RenderWidgetHostImpl* old_keyboard_lock_widget = keyboard_lock_widget_;
3543 keyboard_lock_widget_ = nullptr;
3544
Joe Downing13dd76b2018-04-09 18:32:153545 if (delegate_)
3546 delegate_->CancelKeyboardLockRequest(this);
3547
Joe Downing192998b22018-03-22 15:51:363548 old_keyboard_lock_widget->CancelKeyboardLock();
3549}
3550
3551RenderWidgetHostImpl* WebContentsImpl::GetKeyboardLockWidget() {
3552 return keyboard_lock_widget_;
3553}
3554
Dave Tapuskac3344362019-02-20 17:54:283555void WebContentsImpl::OnRenderFrameProxyVisibilityChanged(
3556 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:373557 OPTIONAL_TRACE_EVENT1("content",
3558 "WebContentsImpl::OnRenderFrameProxyVisibilityChanged",
3559 "visibility", static_cast<int>(visibility));
Dave Tapuskac3344362019-02-20 17:54:283560 switch (visibility) {
3561 case blink::mojom::FrameVisibility::kRenderedInViewport:
3562 WasShown();
3563 break;
3564 case blink::mojom::FrameVisibility::kNotRendered:
3565 WasHidden();
3566 break;
3567 case blink::mojom::FrameVisibility::kRenderedOutOfViewport:
3568 WasOccluded();
3569 break;
3570 }
ekaramada4f42692016-02-11 19:48:373571}
3572
Albert J. Wong65fe64d2019-09-20 02:48:143573RenderFrameHostDelegate* WebContentsImpl::CreateNewWindow(
csharrison95f01e922017-04-24 18:52:353574 RenderFrameHost* opener,
rockot5c478a72016-09-28 23:14:183575 const mojom::CreateNewWindowParams& params,
Albert J. Wong65fe64d2019-09-20 02:48:143576 bool is_new_browsing_instance,
Sergey Kuznetsov32257a22019-02-11 20:26:503577 bool has_user_gesture,
[email protected]97714c82012-06-06 10:15:133578 SessionStorageNamespace* session_storage_namespace) {
Alexander Timin5fdeff22020-09-08 09:20:373579 TRACE_EVENT2("browser,content,navigation", "WebContentsImpl::CreateNewWindow",
3580 "opener", base::trace_event::ToTracedValue(opener), "params",
3581 base::trace_event::ToTracedValue(params));
csharrison95f01e922017-04-24 18:52:353582 DCHECK(opener);
nick5ae4d2d2017-01-06 01:18:353583
csharrison95f01e922017-04-24 18:52:353584 int render_process_id = opener->GetProcess()->GetID();
csharrison95f01e922017-04-24 18:52:353585
Albert J. Wong65fe64d2019-09-20 02:48:143586 SiteInstance* source_site_instance = opener->GetSiteInstance();
nick5ae4d2d2017-01-06 01:18:353587
Aaron Colwelleb219982020-01-16 02:17:273588 const GURL source_site_url = source_site_instance->GetSiteURL();
[email protected]fdac6ade2013-07-20 01:06:303589 const std::string& partition_id =
Aaron Colwelleb219982020-01-16 02:17:273590 GetContentClient()->browser()->GetStoragePartitionIdForSite(
3591 GetBrowserContext(), source_site_url);
3592 {
3593 StoragePartition* partition = BrowserContext::GetStoragePartitionForSite(
3594 GetBrowserContext(), source_site_url);
3595 DOMStorageContextWrapper* dom_storage_context =
3596 static_cast<DOMStorageContextWrapper*>(
3597 partition->GetDOMStorageContext());
3598 SessionStorageNamespaceImpl* session_storage_namespace_impl =
3599 static_cast<SessionStorageNamespaceImpl*>(session_storage_namespace);
3600 CHECK(session_storage_namespace_impl->IsFromContext(dom_storage_context));
3601 }
[email protected]dd6730412013-08-14 15:03:373602
Albert J. Wong1ceccef92019-10-08 08:25:203603 if (delegate_ && delegate_->IsWebContentsCreationOverridden(
3604 source_site_instance, params.window_container_type,
3605 opener->GetLastCommittedURL(), params.frame_name,
3606 params.target_url)) {
3607 return static_cast<WebContentsImpl*>(delegate_->CreateCustomWebContents(
3608 opener, source_site_instance, is_new_browsing_instance,
3609 opener->GetLastCommittedURL(), params.frame_name, params.target_url,
3610 partition_id, session_storage_namespace));
[email protected]dd6730412013-08-14 15:03:373611 }
3612
danakj22b4e8b2019-08-01 23:14:393613 bool renderer_started_hidden =
3614 params.disposition == WindowOpenDisposition::NEW_BACKGROUND_TAB;
3615
Aaron Colwelleb219982020-01-16 02:17:273616 // We usually create the new window in the same BrowsingInstance (group of
3617 // script-related windows), by passing in the current SiteInstance. However,
3618 // if the opener is being suppressed (in a non-guest), we do not provide
3619 // a SiteInstance which causes a new one to get created in its own
3620 // BrowsingInstance.
3621 bool is_guest = BrowserPluginGuest::IsGuest(this);
3622 scoped_refptr<SiteInstance> site_instance =
3623 params.opener_suppressed && !is_guest ? nullptr : source_site_instance;
3624
[email protected]dd6730412013-08-14 15:03:373625 // Create the new web contents. This will automatically create the new
3626 // WebContentsView. In the future, we may want to create the view separately.
[email protected]fc72bb12013-06-02 21:13:463627 CreateParams create_params(GetBrowserContext(), site_instance.get());
nasko48321ca32015-07-02 20:44:123628 create_params.main_frame_name = params.frame_name;
alexmos4cf2aa32015-07-15 23:40:433629 create_params.opener_render_process_id = render_process_id;
csharrison95f01e922017-04-24 18:52:353630 create_params.opener_render_frame_id = opener->GetRoutingID();
[email protected]50d326e2014-05-20 17:59:063631 create_params.opener_suppressed = params.opener_suppressed;
danakj22b4e8b2019-08-01 23:14:393632 create_params.initially_hidden = renderer_started_hidden;
[email protected]50d326e2014-05-20 17:59:063633
Albert J. Wong65fe64d2019-09-20 02:48:143634 // Even though all codepaths leading here are in response to a renderer
3635 // tryng to open a new window, if the new window ends up in a different
3636 // browsing instance, then the RenderViewHost, RenderWidgetHost,
3637 // RenderFrameHost constellation is effectively browser initiated
3638 // the opener's process will not given the routing IDs for the new
3639 // objects.
3640 create_params.renderer_initiated_creation = !is_new_browsing_instance;
Albert J. Wong1ceccef92019-10-08 08:25:203641
Albert J. Wong65fe64d2019-09-20 02:48:143642 std::unique_ptr<WebContentsImpl> new_contents;
[email protected]c4538072013-03-18 02:17:553643 if (!is_guest) {
3644 create_params.context = view_->GetNativeView();
Albert J. Wong65fe64d2019-09-20 02:48:143645 new_contents = WebContentsImpl::Create(create_params);
3646 } else {
3647 new_contents = base::WrapUnique(static_cast<WebContentsImpl*>(
3648 GetBrowserPluginGuest()->CreateNewGuestWindow(create_params)));
[email protected]c4538072013-03-18 02:17:553649 }
Albert J. Wong65fe64d2019-09-20 02:48:143650 auto* new_contents_impl = new_contents.get();
danakje6c01622018-10-05 19:39:263651
3652 new_contents_impl->GetController().SetSessionStorageNamespace(
erikchenbee5c9622018-04-27 19:30:253653 partition_id, session_storage_namespace);
[email protected]d1198fd2012-08-13 22:50:193654
alexmos646fec02015-07-25 00:11:493655 // If the new frame has a name, make sure any SiteInstances that can find
3656 // this named frame have proxies for it. Must be called after
3657 // SetSessionStorageNamespace, since this calls CreateRenderView, which uses
3658 // GetSessionStorageNamespace.
3659 if (!params.frame_name.empty())
danakje6c01622018-10-05 19:39:263660 new_contents_impl->GetRenderManager()->CreateProxiesForNewNamedFrame();
alexmos646fec02015-07-25 00:11:493661
[email protected]c4538072013-03-18 02:17:553662 // Save the window for later if we're not suppressing the opener (since it
[email protected]d70bea92013-04-05 04:23:343663 // will be shown immediately).
3664 if (!params.opener_suppressed) {
3665 if (!is_guest) {
danakje6c01622018-10-05 19:39:263666 WebContentsView* new_view = new_contents_impl->view_.get();
[email protected]bafe6cd2012-05-23 23:09:503667
[email protected]d70bea92013-04-05 04:23:343668 // TODO(brettw): It seems bogus that we have to call this function on the
3669 // newly created object and give it one of its own member variables.
danakj22b4e8b2019-08-01 23:14:393670 RenderWidgetHostView* widget_view = new_view->CreateViewForWidget(
W. James MacLean13d834d2019-12-04 16:06:453671 new_contents_impl->GetRenderViewHost()->GetWidget());
danakj22b4e8b2019-08-01 23:14:393672 if (!renderer_started_hidden) {
3673 // RenderWidgets for frames always initialize as hidden. If the renderer
3674 // created this window as visible, then we show it here.
3675 widget_view->Show();
3676 }
[email protected]d70bea92013-04-05 04:23:343677 }
[email protected]bafe6cd2012-05-23 23:09:503678 // Save the created window associated with the route so we can show it
3679 // later.
Albert J. Wongcb004632018-07-10 22:58:253680 //
3681 // TODO(ajwong): This should be keyed off the RenderFrame routing id or the
3682 // FrameTreeNode id instead of the routing id of the Widget for the main
3683 // frame. https://crbug.com/545684
Fergal Daly052873a82020-03-11 14:45:493684 int32_t main_frame_routing_id = new_contents_impl->GetMainFrame()
3685 ->GetRenderWidgetHost()
3686 ->GetRoutingID();
3687 GlobalRoutingID id(render_process_id, main_frame_routing_id);
Joel Hockey8c2011b22020-04-30 05:07:193688 pending_contents_[id] =
3689 CreatedWindow(std::move(new_contents), params.target_url);
danakje6c01622018-10-05 19:39:263690 AddDestructionObserver(new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503691 }
3692
3693 if (delegate_) {
Bryan McQuaded2b93c02017-07-14 22:26:313694 delegate_->WebContentsCreated(this, render_process_id,
3695 opener->GetRoutingID(), params.frame_name,
danakje6c01622018-10-05 19:39:263696 params.target_url, new_contents_impl);
[email protected]bafe6cd2012-05-23 23:09:503697 }
3698
Alexander Timin90c20c32020-08-12 15:28:323699 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3700 observer->DidOpenRequestedURL(new_contents_impl, opener, params.target_url,
3701 params.referrer.To<Referrer>(),
3702 params.disposition, ui::PAGE_TRANSITION_LINK,
3703 false, // started_from_context_menu
3704 true); // renderer_initiated
3705 });
pnolandaae574e2017-03-06 21:04:213706
[email protected]bafe6cd2012-05-23 23:09:503707 if (params.opener_suppressed) {
3708 // When the opener is suppressed, the original renderer cannot access the
3709 // new window. As a result, we need to show and navigate the window here.
[email protected]eda238a12012-09-07 23:44:003710 bool was_blocked = false;
erikchenbee5c9622018-04-27 19:30:253711
[email protected]eda238a12012-09-07 23:44:003712 if (delegate_) {
danakje6c01622018-10-05 19:39:263713 base::WeakPtr<WebContentsImpl> weak_new_contents =
3714 new_contents_impl->weak_factory_.GetWeakPtr();
nick0d558482017-02-13 22:27:223715
danakje6c01622018-10-05 19:39:263716 gfx::Rect initial_rect; // Report an empty initial rect.
Albert J. Wong65fe64d2019-09-20 02:48:143717 delegate_->AddNewContents(this, std::move(new_contents),
Joel Hockey891e88062020-04-30 05:38:443718 params.target_url, params.disposition,
3719 initial_rect, has_user_gesture, &was_blocked);
danakje6c01622018-10-05 19:39:263720 // The delegate may delete |new_contents_impl| during AddNewContents().
nick0d558482017-02-13 22:27:223721 if (!weak_new_contents)
Albert J. Wong65fe64d2019-09-20 02:48:143722 return nullptr;
[email protected]eda238a12012-09-07 23:44:003723 }
erikchenbee5c9622018-04-27 19:30:253724
[email protected]eda238a12012-09-07 23:44:003725 if (!was_blocked) {
Nasko Oskov83a8cf92018-10-19 14:58:563726 std::unique_ptr<NavigationController::LoadURLParams> load_params =
3727 std::make_unique<NavigationController::LoadURLParams>(
3728 params.target_url);
Nasko Oskov93e7c55c2018-12-19 01:59:293729 load_params->initiator_origin = opener->GetLastCommittedOrigin();
Lukasz Anforowiczd2629b42020-08-11 16:07:313730 // Avoiding setting |load_params->source_site_instance| when
3731 // |opener_suppressed| is true, because in that case we do not want to use
3732 // the old SiteInstance and/or BrowsingInstance. See also the test here:
3733 // NewPopupCOOP_SameOriginPolicyAndCrossOriginIframeSetsNoopener.
Leon Han963dc182018-11-06 05:41:483734 load_params->referrer = params.referrer.To<Referrer>();
Nasko Oskov83a8cf92018-10-19 14:58:563735 load_params->transition_type = ui::PAGE_TRANSITION_LINK;
3736 load_params->is_renderer_initiated = true;
Sergey Kuznetsov32257a22019-02-11 20:26:503737 load_params->has_user_gesture = has_user_gesture;
mariakhomenkoa4971c12015-07-21 19:04:373738
3739 if (delegate_ && !is_guest &&
3740 !delegate_->ShouldResumeRequestsForCreatedWindow()) {
Nasko Oskov83a8cf92018-10-19 14:58:563741 // We are in asynchronous add new contents path, delay navigation.
3742 DCHECK(!new_contents_impl->delayed_open_url_params_);
3743 new_contents_impl->delayed_load_url_params_ = std::move(load_params);
mariakhomenkoa4971c12015-07-21 19:04:373744 } else {
Nasko Oskov83a8cf92018-10-19 14:58:563745 new_contents_impl->controller_.LoadURLWithParams(*load_params.get());
Nasko Oskov28ebd5b2018-12-07 22:29:333746 if (!is_guest)
3747 new_contents_impl->Focus();
mariakhomenkoa4971c12015-07-21 19:04:373748 }
[email protected]eda238a12012-09-07 23:44:003749 }
[email protected]bafe6cd2012-05-23 23:09:503750 }
Albert J. Wong65fe64d2019-09-20 02:48:143751 return new_contents_impl;
[email protected]bafe6cd2012-05-23 23:09:503752}
3753
Dave Tapuskad9835622020-03-10 17:32:313754void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053755 AgentSchedulingGroupHost& agent_scheduling_group,
3756 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303757 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3758 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053759 CreateNewWidget(agent_scheduling_group, route_id,
3760 /*is_fullscreen=*/false, std::move(blink_widget_host),
3761 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503762}
3763
Julie Jeongeun Kimcaacf9102019-09-12 02:13:053764void WebContentsImpl::CreateNewFullscreenWidget(
Tal Pressman5dcd2382020-08-26 07:13:053765 AgentSchedulingGroupHost& agent_scheduling_group,
3766 int32_t route_id,
Dave Tapuska8499eec2020-03-16 17:54:303767 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3768 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Tal Pressman5dcd2382020-08-26 07:13:053769 CreateNewWidget(agent_scheduling_group, route_id,
3770 /*is_fullscreen=*/true, std::move(blink_widget_host),
3771 std::move(blink_widget));
[email protected]bafe6cd2012-05-23 23:09:503772}
3773
Dave Tapuskad9835622020-03-10 17:32:313774void WebContentsImpl::CreateNewWidget(
Tal Pressman5dcd2382020-08-26 07:13:053775 AgentSchedulingGroupHost& agent_scheduling_group,
Dave Tapuskad9835622020-03-10 17:32:313776 int32_t route_id,
3777 bool is_fullscreen,
Dave Tapuska8499eec2020-03-16 17:54:303778 mojo::PendingAssociatedReceiver<blink::mojom::WidgetHost> blink_widget_host,
3779 mojo::PendingAssociatedRemote<blink::mojom::Widget> blink_widget) {
Alexander Timin5fdeff22020-09-08 09:20:373780 OPTIONAL_TRACE_EVENT1(
3781 "content", "WebContentsImpl::CreateNewWidget", "params",
3782 base::trace_event::TracedValue::Build(
3783 {{"route_id", route_id}, {"is_fullscreen", is_fullscreen}}));
Tal Pressman5dcd2382020-08-26 07:13:053784 RenderProcessHost* process = agent_scheduling_group.GetProcess();
kenrbb46f86a2015-12-07 07:53:233785 // A message to create a new widget can only come from an active process for
[email protected]a8504022013-12-04 20:23:513786 // this WebContentsImpl instance. If any other process sends the request,
3787 // it is invalid and the process must be terminated.
Tal Pressman5dcd2382020-08-26 07:13:053788 if (!HasMatchingProcess(&frame_tree_, process->GetID())) {
Lukasz Anforowicz6f746282018-01-04 23:24:513789 ReceivedBadMessage(process, bad_message::WCI_NEW_WIDGET_PROCESS_MISMATCH);
[email protected]a8504022013-12-04 20:23:513790 return;
3791 }
3792
Tal Pressman5dcd2382020-08-26 07:13:053793 RenderWidgetHostImpl* widget_host = new RenderWidgetHostImpl(
3794 this, agent_scheduling_group, route_id, IsHidden(),
3795 std::make_unique<FrameTokenMessageQueue>());
Dave Tapuska8499eec2020-03-16 17:54:303796
3797 widget_host->BindWidgetInterfaces(std::move(blink_widget_host),
3798 std::move(blink_widget));
[email protected]cfd80b02014-05-01 17:46:483799 RenderWidgetHostViewBase* widget_view =
3800 static_cast<RenderWidgetHostViewBase*>(
danakj0b246942018-09-17 21:30:273801 view_->CreateViewForChildWidget(widget_host));
[email protected]83918ec2013-01-10 15:37:193802 if (!widget_view)
3803 return;
danakj0b246942018-09-17 21:30:273804 // Fullscreen child widgets are frames, other child widgets are popups, and
3805 // popups should not get activated.
3806 if (!is_fullscreen)
3807 widget_view->SetWidgetType(WidgetType::kPopup);
[email protected]bafe6cd2012-05-23 23:09:503808 // Save the created widget associated with the route so we can show it later.
Tal Pressman5dcd2382020-08-26 07:13:053809 pending_widget_views_[GlobalRoutingID(process->GetID(), route_id)] =
alexmosc2a8cec2016-05-23 22:19:533810 widget_view;
[email protected]bafe6cd2012-05-23 23:09:503811}
3812
Mike Wassermandabad612020-08-13 04:26:273813void WebContentsImpl::ShowCreatedWindow(RenderFrameHost* opener,
nick5ae4d2d2017-01-06 01:18:353814 int main_frame_widget_route_id,
[email protected]bafe6cd2012-05-23 23:09:503815 WindowOpenDisposition disposition,
bokan107a47f2015-02-03 23:23:393816 const gfx::Rect& initial_rect,
[email protected]bafe6cd2012-05-23 23:09:503817 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:373818 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWindow",
3819 "opener", base::trace_event::ToTracedValue(opener),
3820 "main_frame_widget_route_id",
3821 main_frame_widget_route_id);
danakje6c01622018-10-05 19:39:263822 // This method is the renderer requesting an existing top level window to
3823 // show a new top level window that the renderer created. Each top level
3824 // window is associated with a WebContents. In this case it was created
3825 // earlier but showing it was deferred until the renderer requested for it
3826 // to be shown. We find that previously created WebContents here.
3827 // TODO(danakj): Why do we defer this show step until the renderer asks for it
3828 // when it will always do so. What needs to happen in the renderer before we
3829 // reach here?
Mike Wassermandabad612020-08-13 04:26:273830 base::Optional<CreatedWindow> owned_created = GetCreatedWindow(
3831 opener->GetProcess()->GetID(), main_frame_widget_route_id);
Joel Hockey8c2011b22020-04-30 05:07:193832
danakje6c01622018-10-05 19:39:263833 // The browser may have rejected the request to make a new window, or the
3834 // renderer could be sending an invalid route id. Ignore the request then.
Joel Hockey8c2011b22020-04-30 05:07:193835 if (!owned_created || !owned_created->contents)
danakje6c01622018-10-05 19:39:263836 return;
mariakhomenko44bdc4732015-04-29 01:55:383837
Joel Hockey8c2011b22020-04-30 05:07:193838 WebContentsImpl* created = owned_created->contents.get();
3839
danakje6c01622018-10-05 19:39:263840 // This uses the delegate for the WebContents where the window was created
3841 // from, to control how to show the newly created window.
3842 WebContentsDelegate* delegate = GetDelegate();
nick5ae4d2d2017-01-06 01:18:353843
Mike Wassermanb6bc0152020-08-25 22:46:203844 // Individual members of |initial_rect| may be 0 to indicate that the
3845 // window.open() feature string did not specify a value. This code does not
3846 // have the ability to distinguish between an unspecified value and 0.
3847 // Assume that if any single value is non-zero, all values should be used.
3848 // TODO(crbug.com/897300): Plumb values as specified; set defaults here?
3849 gfx::Rect adjusted_rect = initial_rect;
3850 int64_t display_id = display::kInvalidDisplayId;
3851 if (adjusted_rect != gfx::Rect())
3852 display_id = AdjustRequestedWindowBounds(&adjusted_rect, opener);
3853
3854 // Drop fullscreen when opening a WebContents to prohibit deceptive behavior.
3855 // Only drop fullscreen on the specific destination display, if it is known.
3856 // This supports sites using cross-screen window placement capabilities to
3857 // retain fullscreen and open a window on another screen.
3858 ForSecurityDropFullscreen(display_id).RunAndReset();
3859
danakje6c01622018-10-05 19:39:263860 // The delegate can be null in tests, so we must check for it :(.
3861 if (delegate) {
3862 // Mark the web contents as pending resume, then immediately do
3863 // the resume if the delegate wants it.
3864 created->is_resume_pending_ = true;
3865 if (delegate->ShouldResumeRequestsForCreatedWindow())
3866 created->ResumeLoadingCreatedWebContents();
3867
3868 base::WeakPtr<WebContentsImpl> weak_created =
3869 created->weak_factory_.GetWeakPtr();
Joel Hockey8c2011b22020-04-30 05:07:193870 delegate->AddNewContents(this, std::move(owned_created->contents),
Joel Hockey891e88062020-04-30 05:38:443871 std::move(owned_created->target_url), disposition,
Mike Wassermandabad612020-08-13 04:26:273872 adjusted_rect, user_gesture, nullptr);
danakje6c01622018-10-05 19:39:263873 // The delegate may delete |created| during AddNewContents().
3874 if (!weak_created)
3875 return;
[email protected]eda238a12012-09-07 23:44:003876 }
danakje6c01622018-10-05 19:39:263877
3878 RenderWidgetHostImpl* rwh = created->GetMainFrame()->GetRenderWidgetHost();
3879 DCHECK_EQ(main_frame_widget_route_id, rwh->GetRoutingID());
3880 rwh->Send(new WidgetMsg_SetBounds_ACK(rwh->GetRoutingID()));
[email protected]bafe6cd2012-05-23 23:09:503881}
3882
alexmosc2a8cec2016-05-23 22:19:533883void WebContentsImpl::ShowCreatedWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473884 int widget_route_id,
bokan107a47f2015-02-03 23:23:393885 const gfx::Rect& initial_rect) {
Alexander Timin5fdeff22020-09-08 09:20:373886 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShowCreatedWidget",
3887 "process_id", process_id, "widget_route_id",
3888 widget_route_id);
Albert J. Wongf6e13ed2018-09-18 15:25:473889 ShowCreatedWidget(process_id, widget_route_id, false, initial_rect);
[email protected]bafe6cd2012-05-23 23:09:503890}
3891
alexmosc2a8cec2016-05-23 22:19:533892void WebContentsImpl::ShowCreatedFullscreenWidget(int process_id,
Albert J. Wongf6e13ed2018-09-18 15:25:473893 int widget_route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373894 OPTIONAL_TRACE_EVENT2(
3895 "content", "WebContentsImpl::ShowCreatedFullscreenWidget", "process_id",
3896 process_id, "widget_route_id", widget_route_id);
Albert J. Wongf6e13ed2018-09-18 15:25:473897 ShowCreatedWidget(process_id, widget_route_id, true, gfx::Rect());
[email protected]bafe6cd2012-05-23 23:09:503898}
3899
alexmosc2a8cec2016-05-23 22:19:533900void WebContentsImpl::ShowCreatedWidget(int process_id,
3901 int route_id,
[email protected]bafe6cd2012-05-23 23:09:503902 bool is_fullscreen,
bokan107a47f2015-02-03 23:23:393903 const gfx::Rect& initial_rect) {
[email protected]cfd80b02014-05-01 17:46:483904 RenderWidgetHostViewBase* widget_host_view =
alexmosc2a8cec2016-05-23 22:19:533905 static_cast<RenderWidgetHostViewBase*>(
3906 GetCreatedWidget(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:503907 if (!widget_host_view)
3908 return;
[email protected]cfd80b02014-05-01 17:46:483909
W. James MacLeanec4125c2019-09-27 18:56:003910 // GetOutermostWebContents() returns |this| if there are no outer WebContents.
W. James MacLean3c5f50462019-10-28 16:24:213911 auto* outer_web_contents = GetOuterWebContents();
3912 auto* outermost_web_contents = GetOutermostWebContents();
W. James MacLeanec4125c2019-09-27 18:56:003913 RenderWidgetHostView* view =
W. James MacLean3c5f50462019-10-28 16:24:213914 outermost_web_contents->GetRenderWidgetHostView();
3915 // It's not entirely obvious why we need the transform only in the case where
3916 // the outer webcontents is not the same as the outermost webcontents. It may
3917 // be due to the fact that oopifs that are children of the mainframe get
3918 // correct values for their screenrects, but deeper cross-process frames do
3919 // not. Hopefully this can be resolved with https://crbug.com/928825.
3920 // Handling these cases separately is needed for http://crbug.com/1015298.
3921 bool needs_transform = this != outermost_web_contents &&
3922 outermost_web_contents != outer_web_contents;
W. James MacLeanec4125c2019-09-27 18:56:003923
3924 gfx::Rect transformed_rect(initial_rect);
3925 RenderWidgetHostView* this_view = GetRenderWidgetHostView();
W. James MacLean3c5f50462019-10-28 16:24:213926 if (needs_transform) {
W. James MacLeanec4125c2019-09-27 18:56:003927 // We need to transform the coordinates of initial_rect.
3928 gfx::Point origin =
3929 this_view->TransformPointToRootCoordSpace(initial_rect.origin());
3930 gfx::Point bottom_right =
3931 this_view->TransformPointToRootCoordSpace(initial_rect.bottom_right());
3932 transformed_rect =
3933 gfx::Rect(origin.x(), origin.y(), bottom_right.x() - origin.x(),
3934 bottom_right.y() - origin.y());
[email protected]cfd80b02014-05-01 17:46:483935 }
3936
danakj0b246942018-09-17 21:30:273937 // Fullscreen child widgets are frames, other child widgets are popups.
[email protected]4aebbca2013-09-17 22:26:493938 if (is_fullscreen) {
[email protected]d7f80ba2013-10-12 07:42:313939 DCHECK_EQ(MSG_ROUTING_NONE, fullscreen_widget_routing_id_);
[email protected]0b431992014-06-24 00:08:033940 view_->StoreFocus();
alexmosc9e76ec2016-05-16 22:59:373941 fullscreen_widget_process_id_ =
3942 widget_host_view->GetRenderWidgetHost()->GetProcess()->GetID();
[email protected]d7f80ba2013-10-12 07:42:313943 fullscreen_widget_routing_id_ = route_id;
[email protected]4aebbca2013-09-17 22:26:493944 if (delegate_ && delegate_->EmbedsFullscreenWidget()) {
3945 widget_host_view->InitAsChild(GetRenderWidgetHostView()->GetNativeView());
Mike Wasserman4ca09792020-05-29 17:44:433946 delegate_->EnterFullscreenModeForTab(GetMainFrame(),
Dave Tapuskaa4189512019-10-15 20:27:343947 blink::mojom::FullscreenOptions());
[email protected]4aebbca2013-09-17 22:26:493948 } else {
[email protected]cfd80b02014-05-01 17:46:483949 widget_host_view->InitAsFullscreen(view);
[email protected]4aebbca2013-09-17 22:26:493950 }
Alexander Timin90c20c32020-08-12 15:28:323951 observers_.ForEachObserver([&](WebContentsObserver* observer) {
3952 observer->DidShowFullscreenWidget();
3953 });
[email protected]4aebbca2013-09-17 22:26:493954 if (!widget_host_view->HasFocus())
3955 widget_host_view->Focus();
3956 } else {
W. James MacLeanec4125c2019-09-27 18:56:003957 widget_host_view->InitAsPopup(view, transformed_rect);
[email protected]4aebbca2013-09-17 22:26:493958 }
[email protected]89054502012-06-03 10:29:243959
yiyixcb1fbc4f2018-03-16 19:54:083960 RenderWidgetHostImpl* render_widget_host_impl = widget_host_view->host();
[email protected]89054502012-06-03 10:29:243961 render_widget_host_impl->Init();
[email protected]d7f80ba2013-10-12 07:42:313962 // Only allow privileged mouse lock for fullscreen render widget, which is
3963 // used to implement Pepper Flash fullscreen.
3964 render_widget_host_impl->set_allow_privileged_mouse_lock(is_fullscreen);
[email protected]bafe6cd2012-05-23 23:09:503965}
3966
Joel Hockey8c2011b22020-04-30 05:07:193967base::Optional<CreatedWindow> WebContentsImpl::GetCreatedWindow(
nick5ae4d2d2017-01-06 01:18:353968 int process_id,
3969 int main_frame_widget_route_id) {
Alexander Timin5fdeff22020-09-08 09:20:373970 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWindow",
3971 "process_id", process_id, "main_frame_widget_route_id",
3972 main_frame_widget_route_id);
3973
Lukasz Anforowicz09060bdf72018-08-23 15:53:173974 auto key = GlobalRoutingID(process_id, main_frame_widget_route_id);
nick5ae4d2d2017-01-06 01:18:353975 auto iter = pending_contents_.find(key);
[email protected]bafe6cd2012-05-23 23:09:503976
3977 // Certain systems can block the creation of new windows. If we didn't succeed
3978 // in creating one, just return NULL.
alexmosc2a8cec2016-05-23 22:19:533979 if (iter == pending_contents_.end())
Joel Hockey8c2011b22020-04-30 05:07:193980 return base::nullopt;
[email protected]bafe6cd2012-05-23 23:09:503981
Joel Hockey8c2011b22020-04-30 05:07:193982 CreatedWindow result = std::move(iter->second);
3983 WebContentsImpl* new_contents = result.contents.get();
nick5ae4d2d2017-01-06 01:18:353984 pending_contents_.erase(key);
Joel Hockey8c2011b22020-04-30 05:07:193985 RemoveDestructionObserver(new_contents);
[email protected]bafe6cd2012-05-23 23:09:503986
[email protected]d70bea92013-04-05 04:23:343987 // Don't initialize the guest WebContents immediately.
Joel Hockey8c2011b22020-04-30 05:07:193988 if (BrowserPluginGuest::IsGuest(new_contents))
3989 return result;
[email protected]d70bea92013-04-05 04:23:343990
Lukasz Anforowicz5510ed652018-06-06 16:16:193991 if (!new_contents->GetMainFrame()->GetProcess()->IsInitializedAndNotDead() ||
nick5ae4d2d2017-01-06 01:18:353992 !new_contents->GetMainFrame()->GetView()) {
Joel Hockey8c2011b22020-04-30 05:07:193993 return base::nullopt;
nick5ae4d2d2017-01-06 01:18:353994 }
[email protected]bafe6cd2012-05-23 23:09:503995
Joel Hockey8c2011b22020-04-30 05:07:193996 return result;
[email protected]bafe6cd2012-05-23 23:09:503997}
3998
alexmosc2a8cec2016-05-23 22:19:533999RenderWidgetHostView* WebContentsImpl::GetCreatedWidget(int process_id,
4000 int route_id) {
Alexander Timin5fdeff22020-09-08 09:20:374001 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::GetCreatedWidget",
4002 "process_id", process_id, "route_id", route_id);
4003
Lukasz Anforowicz09060bdf72018-08-23 15:53:174004 auto iter = pending_widget_views_.find(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:504005 if (iter == pending_widget_views_.end()) {
4006 DCHECK(false);
alexmosc2a8cec2016-05-23 22:19:534007 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:504008 }
4009
4010 RenderWidgetHostView* widget_host_view = iter->second;
Lukasz Anforowicz09060bdf72018-08-23 15:53:174011 pending_widget_views_.erase(GlobalRoutingID(process_id, route_id));
[email protected]bafe6cd2012-05-23 23:09:504012
4013 RenderWidgetHost* widget_host = widget_host_view->GetRenderWidgetHost();
Lukasz Anforowicz5510ed652018-06-06 16:16:194014 if (!widget_host->GetProcess()->IsInitializedAndNotDead()) {
[email protected]bafe6cd2012-05-23 23:09:504015 // The view has gone away or the renderer crashed. Nothing to do.
alexmosc2a8cec2016-05-23 22:19:534016 return nullptr;
[email protected]bafe6cd2012-05-23 23:09:504017 }
4018
4019 return widget_host_view;
4020}
4021
[email protected]f13b4202012-06-12 23:53:234022void WebContentsImpl::RequestMediaAccessPermission(
[email protected]33662e52013-01-07 21:31:094023 const MediaStreamRequest& request,
Mark Pilgrim57499082018-06-12 12:38:304024 MediaResponseCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374025 OPTIONAL_TRACE_EVENT2("content",
4026 "WebContentsImpl::RequestMediaAccessPermission",
4027 "render_process_id", request.render_process_id,
4028 "render_frame_id", request.render_frame_id);
4029
[email protected]d19b84b2014-03-14 11:52:374030 if (delegate_) {
Mark Pilgrim57499082018-06-12 12:38:304031 delegate_->RequestMediaAccessPermission(this, request, std::move(callback));
[email protected]d19b84b2014-03-14 11:52:374032 } else {
Antonio Gomes0d42960a2019-06-05 12:35:514033 std::move(callback).Run(
4034 blink::MediaStreamDevices(),
4035 blink::mojom::MediaStreamRequestResult::FAILED_DUE_TO_SHUTDOWN,
4036 std::unique_ptr<MediaStreamUI>());
[email protected]d19b84b2014-03-14 11:52:374037 }
[email protected]f13b4202012-06-12 23:53:234038}
4039
Chandan Padhia4b8bcb72017-09-12 16:41:044040bool WebContentsImpl::CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:584041 RenderFrameHost* render_frame_host,
Chandan Padhia4b8bcb72017-09-12 16:41:044042 const url::Origin& security_origin,
Antonio Gomesc8b734b2019-06-05 18:22:164043 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:374044 OPTIONAL_TRACE_EVENT2("content",
4045 "WebContentsImpl::CheckMediaAccessPermission",
4046 "render_frame_host", render_frame_host,
4047 "security_origin", security_origin.Serialize());
4048
Antonio Gomesc8b734b2019-06-05 18:22:164049 DCHECK(type == blink::mojom::MediaStreamType::DEVICE_AUDIO_CAPTURE ||
4050 type == blink::mojom::MediaStreamType::DEVICE_VIDEO_CAPTURE);
Chandan Padhia4b8bcb72017-09-12 16:41:044051 return delegate_ && delegate_->CheckMediaAccessPermission(
Raymes Khouryad7c24a12018-03-05 23:22:584052 render_frame_host, security_origin.GetURL(), type);
grunell657d4d82014-09-18 00:09:434053}
4054
Guido Urdaneta73fa6632019-01-14 18:46:264055std::string WebContentsImpl::GetDefaultMediaDeviceID(
Antonio Gomesc8b734b2019-06-05 18:22:164056 blink::mojom::MediaStreamType type) {
Alexander Timin5fdeff22020-09-08 09:20:374057 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GetDefaultMediaDeviceID",
4058 "type", static_cast<int>(type));
4059
guidou8a440b842017-01-30 13:58:434060 if (!delegate_)
4061 return std::string();
4062 return delegate_->GetDefaultMediaDeviceID(this, type);
4063}
4064
[email protected]cc9200432013-07-23 23:02:404065SessionStorageNamespace* WebContentsImpl::GetSessionStorageNamespace(
4066 SiteInstance* instance) {
4067 return controller_.GetSessionStorageNamespace(instance);
4068}
4069
[email protected]6de7fc482014-06-06 10:46:444070SessionStorageNamespaceMap WebContentsImpl::GetSessionStorageNamespaceMap() {
4071 return controller_.GetSessionStorageNamespaceMap();
4072}
4073
[email protected]9b159a52013-10-03 17:24:554074FrameTree* WebContentsImpl::GetFrameTree() {
4075 return &frame_tree_;
4076}
4077
aelias5252baa2016-04-10 01:18:024078bool WebContentsImpl::IsOverridingUserAgent() {
4079 return GetController().GetVisibleEntry() &&
4080 GetController().GetVisibleEntry()->GetIsOverridingUserAgent();
4081}
4082
avi85ee8362016-10-08 02:09:084083bool WebContentsImpl::IsJavaScriptDialogShowing() const {
4084 return is_showing_javascript_dialog_;
4085}
4086
avic031d392017-03-03 03:09:424087bool WebContentsImpl::ShouldIgnoreUnresponsiveRenderer() {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:004088 if (suppress_unresponsive_renderer_count_ > 0)
4089 return true;
4090
avic031d392017-03-03 03:09:424091 // Ignore unresponsive renderers if the debugger is attached to them since the
4092 // unresponsiveness might be a result of the renderer sitting on a breakpoint.
4093 //
David Bienvenu525f8a02019-02-15 02:02:424094#ifdef OS_WIN
4095 // Check if a windows debugger is attached to the renderer process.
4096 base::ProcessHandle process_handle =
4097 GetMainFrame()->GetProcess()->GetProcess().Handle();
4098 BOOL debugger_present = FALSE;
4099 if (CheckRemoteDebuggerPresent(process_handle, &debugger_present) &&
4100 debugger_present)
4101 return true;
4102#endif // OS_WIN
4103
avic031d392017-03-03 03:09:424104 // TODO(pfeldman): Fix this to only return true if the renderer is *actually*
4105 // sitting on a breakpoint. https://crbug.com/684202
4106 return DevToolsAgentHost::IsDebuggerAttached(this);
4107}
4108
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414109ui::AXMode WebContentsImpl::GetAccessibilityMode() {
[email protected]95640212014-07-26 18:14:304110 return accessibility_mode_;
4111}
4112
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404113void WebContentsImpl::AXTreeIDForMainFrameHasChanged() {
Alexander Timin5fdeff22020-09-08 09:20:374114 OPTIONAL_TRACE_EVENT0("content",
4115 "WebContentsImpl::AXTreeIDForMainFrameHasChanged");
4116
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404117 RenderWidgetHostViewBase* rwhv =
4118 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
4119 if (rwhv)
4120 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
4121
Alexander Timin90c20c32020-08-12 15:28:324122 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4123 observer->AXTreeIDForMainFrameHasChanged();
4124 });
Mario Sanchez Prada5d7f1ac2020-07-16 17:18:404125}
4126
Dominic Mazzonia7b0edb22017-08-09 16:32:514127void WebContentsImpl::AccessibilityEventReceived(
Dominic Mazzoniccbaa9b2018-06-06 07:44:234128 const AXEventNotificationDetails& details) {
Alexander Timin5fdeff22020-09-08 09:20:374129 OPTIONAL_TRACE_EVENT0("content",
4130 "WebContentsImpl::AccessibilityEventReceived");
Alexander Timin90c20c32020-08-12 15:28:324131 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4132 observer->AccessibilityEventReceived(details);
4133 });
[email protected]31a71eaf2014-03-13 01:47:364134}
4135
dmazzoni2400c462016-08-23 15:07:134136void WebContentsImpl::AccessibilityLocationChangesReceived(
4137 const std::vector<AXLocationChangeNotificationDetails>& details) {
Alexander Timin5fdeff22020-09-08 09:20:374138 OPTIONAL_TRACE_EVENT0(
4139 "content", "WebContentsImpl::AccessibilityLocationChangesReceived");
Alexander Timin90c20c32020-08-12 15:28:324140 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4141 observer->AccessibilityLocationChangesReceived(details);
4142 });
dmazzoni2400c462016-08-23 15:07:134143}
4144
Alexander Surkov2ab51622020-09-02 12:01:424145std::string WebContentsImpl::DumpAccessibilityTree(
Abigail Kleinabb428332019-09-13 18:26:214146 bool internal,
4147 std::vector<AccessibilityTreeFormatter::PropertyFilter> property_filters) {
Alexander Timin5fdeff22020-09-08 09:20:374148 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DumpAccessibilityTree");
James Wallace-Leeeafc94cb92018-07-23 21:35:094149 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4150 DCHECK(ax_mgr);
Lei Zhangc98caa3822019-11-07 19:17:274151 return AccessibilityTreeFormatterBase::DumpAccessibilityTreeFromManager(
Abigail Kleinabb428332019-09-13 18:26:214152 ax_mgr, internal, property_filters);
James Wallace-Leeeafc94cb92018-07-23 21:35:094153}
4154
Abigail Kleinaa898742019-11-01 02:31:254155void WebContentsImpl::RecordAccessibilityEvents(
Abigail Kleinbb8304bd2020-05-18 21:44:184156 bool start_recording,
4157 base::Optional<AccessibilityEventCallback> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374158 OPTIONAL_TRACE_EVENT0("content",
4159 "WebContentsImpl::RecordAccessibilityEvents");
Abigail Kleinbb8304bd2020-05-18 21:44:184160 // Only pass a callback to RecordAccessibilityEvents when starting to record.
4161 DCHECK_EQ(start_recording, callback.has_value());
4162 if (start_recording) {
Abigail Kleinaa898742019-11-01 02:31:254163 SetAccessibilityMode(ui::AXMode::kWebContents);
4164 auto* ax_mgr = GetOrCreateRootBrowserAccessibilityManager();
4165 DCHECK(ax_mgr);
4166 base::ProcessId pid = base::Process::Current().Pid();
4167 event_recorder_ = content::AccessibilityEventRecorder::Create(
4168 ax_mgr, pid, base::StringPiece{});
Abigail Kleinbb8304bd2020-05-18 21:44:184169 event_recorder_->ListenToEvents(*callback);
Abigail Kleinaa898742019-11-01 02:31:254170 } else {
Abigail Kleinbb8304bd2020-05-18 21:44:184171 if (event_recorder_) {
4172 event_recorder_->FlushAsyncEvents();
4173 event_recorder_.reset(nullptr);
4174 }
Abigail Kleinaa898742019-11-01 02:31:254175 }
4176}
4177
dmazzonia656928e2014-09-15 20:28:544178RenderFrameHost* WebContentsImpl::GetGuestByInstanceID(
fsamuel833ee7c2015-02-13 23:40:404179 RenderFrameHost* render_frame_host,
dmazzonia656928e2014-09-15 20:28:544180 int browser_plugin_instance_id) {
Alexander Timin5fdeff22020-09-08 09:20:374181 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetGuestByInstanceID");
dmazzonia656928e2014-09-15 20:28:544182 BrowserPluginGuestManager* guest_manager =
4183 GetBrowserContext()->GetGuestManager();
fsamuel9cbc00a2015-04-17 20:30:204184 if (!guest_manager)
4185 return nullptr;
4186
dmazzonia656928e2014-09-15 20:28:544187 WebContents* guest = guest_manager->GetGuestByInstanceID(
fsamuel2e9413d2015-02-25 01:25:444188 render_frame_host->GetProcess()->GetID(), browser_plugin_instance_id);
dmazzonia656928e2014-09-15 20:28:544189 if (!guest)
fsamuel9cbc00a2015-04-17 20:30:204190 return nullptr;
4191
dmazzonia656928e2014-09-15 20:28:544192 return guest->GetMainFrame();
4193}
4194
Ke He7319dbe2017-11-09 05:54:444195device::mojom::GeolocationContext* WebContentsImpl::GetGeolocationContext() {
Alexander Timin5fdeff22020-09-08 09:20:374196 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetGeolocationContext");
Ella Ge3e375b702020-06-05 15:57:164197 if (delegate_) {
4198 auto* installed_webapp_context =
4199 delegate_->GetInstalledWebappGeolocationContext();
4200 if (installed_webapp_context)
4201 return installed_webapp_context;
4202 }
4203
Ken Rockotce010f02019-12-12 23:32:324204 if (!geolocation_context_) {
4205 GetDeviceService().BindGeolocationContext(
4206 geolocation_context_.BindNewPipeAndPassReceiver());
4207 }
Conley Owens6894c4f2017-07-10 19:29:134208 return geolocation_context_.get();
blundellc57b93f2014-10-29 13:19:574209}
4210
ke.he98b761e2017-05-09 05:59:174211device::mojom::WakeLockContext* WebContentsImpl::GetWakeLockContext() {
blundelld8cd72b2017-03-28 07:18:384212 if (!wake_lock_context_host_)
4213 wake_lock_context_host_.reset(new WakeLockContextHost(this));
blundelle75a8f92017-03-27 08:11:174214 return wake_lock_context_host_->GetWakeLockContext();
alogvinovf50445a2015-10-30 13:00:124215}
4216
blundellf5316fc2017-05-15 11:49:034217#if defined(OS_ANDROID)
Miyoung Shin59f39ff2019-09-17 07:23:204218void WebContentsImpl::GetNFC(
Reilly Grantafbe2242020-02-20 21:14:554219 RenderFrameHost* render_frame_host,
Miyoung Shin59f39ff2019-09-17 07:23:204220 mojo::PendingReceiver<device::mojom::NFC> receiver) {
Reilly Grantafbe2242020-02-20 21:14:554221 if (!nfc_host_)
4222 nfc_host_ = std::make_unique<NFCHost>(this);
4223 nfc_host_->GetNFC(render_frame_host, std::move(receiver));
blundellf5316fc2017-05-15 11:49:034224}
4225#endif
4226
Evan Stade5e750ad02017-08-07 21:59:274227void WebContentsImpl::SetNotWaitingForResponse() {
Alexander Timin5fdeff22020-09-08 09:20:374228 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetNotWaitingForResponse",
4229 "was_waiting_for_response", waiting_for_response_);
Evan Stade5e750ad02017-08-07 21:59:274230 if (waiting_for_response_ == false)
4231 return;
4232
4233 waiting_for_response_ = false;
4234 if (delegate_)
4235 delegate_->LoadingStateChanged(this, is_load_to_different_document_);
Alexander Timin90c20c32020-08-12 15:28:324236 observers_.ForEachObserver(
4237 [&](WebContentsObserver* observer) { observer->DidReceiveResponse(); });
Evan Stade5e750ad02017-08-07 21:59:274238}
4239
lfgbb9c28a2016-03-01 03:19:494240void WebContentsImpl::SendScreenRects() {
Alexander Timin5fdeff22020-09-08 09:20:374241 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SendScreenRects");
kenrbc52e1b4e2016-03-20 01:03:374242 for (FrameTreeNode* node : frame_tree_.Nodes()) {
kenrb0e8dc202016-05-30 19:51:404243 if (node->current_frame_host()->is_local_root())
kenrbc52e1b4e2016-03-20 01:03:374244 node->current_frame_host()->GetRenderWidgetHost()->SendScreenRects();
4245 }
[email protected]32deec62013-05-15 23:55:044246}
4247
ekaramadadd882292016-06-08 15:22:564248TextInputManager* WebContentsImpl::GetTextInputManager() {
4249 if (GetOuterWebContents())
4250 return GetOuterWebContents()->GetTextInputManager();
4251
Ehsan Karamadc179dc02018-12-15 03:09:294252 if (!text_input_manager_ && !browser_plugin_guest_) {
Darren Shenca53d5f2018-05-15 04:56:014253 text_input_manager_.reset(new TextInputManager(
4254 GetBrowserContext() &&
4255 !GetBrowserContext()->IsOffTheRecord()) /* should_do_learning */);
4256 }
ekaramadadd882292016-06-08 15:22:564257
4258 return text_input_manager_.get();
4259}
4260
paulmeyer7f6f1d4f2016-11-15 00:00:274261bool WebContentsImpl::OnUpdateDragCursor() {
Alexander Timin5fdeff22020-09-08 09:20:374262 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnUpdateDragCursor");
Lei Zhang6410ec1a2019-01-31 21:38:584263 return browser_plugin_embedder_ &&
4264 browser_plugin_embedder_->OnUpdateDragCursor();
paulmeyer7f6f1d4f2016-11-15 00:00:274265}
4266
kenrb11f213a2017-03-24 18:12:064267bool WebContentsImpl::IsWidgetForMainFrame(
4268 RenderWidgetHostImpl* render_widget_host) {
4269 return render_widget_host == GetMainFrame()->GetRenderWidgetHost();
4270}
4271
[email protected]95640212014-07-26 18:14:304272BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374273WebContentsImpl::GetRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394274 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454275 return rfh ? rfh->browser_accessibility_manager() : nullptr;
[email protected]95640212014-07-26 18:14:304276}
4277
4278BrowserAccessibilityManager*
Alexander Timin5fdeff22020-09-08 09:20:374279WebContentsImpl::GetOrCreateRootBrowserAccessibilityManager() {
Carlos ILd51e7702020-05-07 18:51:394280 RenderFrameHostImpl* rfh = static_cast<RenderFrameHostImpl*>(GetMainFrame());
creisc014b402015-04-23 16:41:454281 return rfh ? rfh->GetOrCreateBrowserAccessibilityManager() : nullptr;
[email protected]95640212014-07-26 18:14:304282}
4283
Dave Tapuskab336b922017-07-06 19:24:054284void WebContentsImpl::ExecuteEditCommand(
4285 const std::string& command,
4286 const base::Optional<base::string16>& value) {
Alexander Timin5fdeff22020-09-08 09:20:374287 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExecuteEditCommand");
Dave Tapuska58a099e2020-06-08 21:48:404288 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514289 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054290 return;
4291
Dave Tapuskae782bea2019-07-09 16:21:514292 input_handler->ExecuteEditCommand(command, value);
Dave Tapuskab336b922017-07-06 19:24:054293}
4294
mohsen7ab1ec16ec2015-07-02 18:26:234295void WebContentsImpl::MoveRangeSelectionExtent(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374296 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MoveRangeSelectionExtent");
Dave Tapuska58a099e2020-06-08 21:48:404297 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514298 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234299 return;
4300
Dave Tapuskae782bea2019-07-09 16:21:514301 input_handler->MoveRangeSelectionExtent(extent);
mohsen7ab1ec16ec2015-07-02 18:26:234302}
4303
4304void WebContentsImpl::SelectRange(const gfx::Point& base,
4305 const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374306 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectRange");
Dave Tapuska58a099e2020-06-08 21:48:404307 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514308 if (!input_handler)
mohsen7ab1ec16ec2015-07-02 18:26:234309 return;
4310
Dave Tapuskae782bea2019-07-09 16:21:514311 input_handler->SelectRange(base, extent);
mohsen7ab1ec16ec2015-07-02 18:26:234312}
4313
Dave Tapuskab336b922017-07-06 19:24:054314void WebContentsImpl::MoveCaret(const gfx::Point& extent) {
Alexander Timin5fdeff22020-09-08 09:20:374315 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4316 "WebContentsImpl::MoveCaret");
Dave Tapuska58a099e2020-06-08 21:48:404317 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514318 if (!input_handler)
Dave Tapuskab336b922017-07-06 19:24:054319 return;
4320
Dave Tapuskae782bea2019-07-09 16:21:514321 input_handler->MoveCaret(extent);
Dave Tapuskab336b922017-07-06 19:24:054322}
4323
Shimi Zhang37deeb22017-09-28 00:59:014324void WebContentsImpl::AdjustSelectionByCharacterOffset(
4325 int start_adjust,
4326 int end_adjust,
4327 bool show_selection_menu) {
Alexander Timin5fdeff22020-09-08 09:20:374328 OPTIONAL_TRACE_EVENT0("content",
4329 "WebContentsImpl::AdjustSelectionByCharacterOffset");
Dave Tapuska58a099e2020-06-08 21:48:404330 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514331 if (!input_handler)
aurimasab0319022015-07-10 21:57:384332 return;
4333
Shimi Zhang37deeb22017-09-28 00:59:014334 using blink::mojom::SelectionMenuBehavior;
Dave Tapuskae782bea2019-07-09 16:21:514335 input_handler->AdjustSelectionByCharacterOffset(
Shimi Zhang37deeb22017-09-28 00:59:014336 start_adjust, end_adjust,
4337 show_selection_menu ? SelectionMenuBehavior::kShow
4338 : SelectionMenuBehavior::kHide);
aurimasab0319022015-07-10 21:57:384339}
4340
[email protected]b172aee2012-04-10 17:05:264341void WebContentsImpl::UpdatePreferredSize(const gfx::Size& pref_size) {
Alexander Timin5fdeff22020-09-08 09:20:374342 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::UpdatePreferredSize");
[email protected]222f5822014-02-05 23:40:494343 const gfx::Size old_size = GetPreferredSize();
[email protected]bcd2815602012-01-14 18:17:234344 preferred_size_ = pref_size;
[email protected]222f5822014-02-05 23:40:494345 OnPreferredSizeChanged(old_size);
[email protected]0548c5352011-09-07 00:33:334346}
4347
avic3aa8422015-11-09 20:57:224348void WebContentsImpl::ResizeDueToAutoResize(
4349 RenderWidgetHostImpl* render_widget_host,
Fady Samuel97947112018-05-05 16:24:544350 const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:374351 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ResizeDueToAutoResize",
4352 "render_widget_host", render_widget_host);
avic3aa8422015-11-09 20:57:224353 if (render_widget_host != GetRenderViewHost()->GetWidget())
4354 return;
4355
[email protected]61e2b3cc2012-03-02 16:13:344356 if (delegate_)
4357 delegate_->ResizeDueToAutoResize(this, new_size);
4358}
4359
[email protected]b172aee2012-04-10 17:05:264360WebContents* WebContentsImpl::OpenURL(const OpenURLParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:374361 TRACE_EVENT1("content", "WebContentsImpl::OpenURL", "url",
4362 base::trace_event::ValueToString(params.url));
Aaron Colwell9dab1652019-12-09 18:29:494363#if DCHECK_IS_ON()
4364 DCHECK(params.Valid());
4365#endif
4366
Bo Liu300c6052018-06-12 04:46:074367 if (!delegate_) {
4368 // Embedder can delay setting a delegate on new WebContents with
4369 // WebContentsDelegate::ShouldResumeRequestsForCreatedWindow. In the mean
4370 // time, navigations, including the initial one, that goes through OpenURL
4371 // should be delayed until embedder is ready to resume loading.
4372 delayed_open_url_params_ = std::make_unique<OpenURLParams>(params);
Nasko Oskov83a8cf92018-10-19 14:58:564373
4374 // If there was a navigation deferred when creating the window through
4375 // CreateNewWindow, drop it in favor of this navigation.
4376 delayed_load_url_params_.reset();
4377
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284378 return nullptr;
Bo Liu300c6052018-06-12 04:46:074379 }
[email protected]00c37fc2011-08-02 00:22:504380
[email protected]e5d549d2011-12-28 01:29:204381 WebContents* new_contents = delegate_->OpenURLFromTab(this, params);
pnoland488944652017-02-22 18:58:544382
4383 RenderFrameHost* source_render_frame_host = RenderFrameHost::FromID(
4384 params.source_render_process_id, params.source_render_frame_id);
4385
4386 if (source_render_frame_host && params.source_site_instance) {
4387 CHECK_EQ(source_render_frame_host->GetSiteInstance(),
4388 params.source_site_instance.get());
4389 }
4390
4391 if (new_contents && source_render_frame_host && new_contents != this) {
Alexander Timin90c20c32020-08-12 15:28:324392 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4393 observer->DidOpenRequestedURL(
Lukasz Anforowicz48c9f872018-08-01 00:58:414394 new_contents, source_render_frame_host, params.url, params.referrer,
4395 params.disposition, params.transition,
4396 params.started_from_context_menu, params.is_renderer_initiated);
Alexander Timin90c20c32020-08-12 15:28:324397 });
pnoland488944652017-02-22 18:58:544398 }
4399
[email protected]e5d549d2011-12-28 01:29:204400 return new_contents;
[email protected]d5f942ba2008-09-26 19:30:344401}
4402
avi2b177592014-12-10 02:08:024403void WebContentsImpl::SetHistoryOffsetAndLength(int history_offset,
4404 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374405 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHistoryOffsetAndLength",
4406 "history_offset", history_offset, "history_length",
4407 history_length);
alexmos136fd6e62016-08-15 20:58:414408 SendPageMessage(new PageMsg_SetHistoryOffsetAndLength(
4409 MSG_ROUTING_NONE, history_offset, history_length));
avi2b177592014-12-10 02:08:024410}
4411
4412void WebContentsImpl::SetHistoryOffsetAndLengthForView(
4413 RenderViewHost* render_view_host,
4414 int history_offset,
4415 int history_length) {
Alexander Timin5fdeff22020-09-08 09:20:374416 OPTIONAL_TRACE_EVENT2(
4417 "content", "WebContentsImpl::SetHistoryOffsetAndLengthForView",
4418 "history_offset", history_offset, "history_length", history_length);
alexmos136fd6e62016-08-15 20:58:414419 render_view_host->Send(new PageMsg_SetHistoryOffsetAndLength(
avi2b177592014-12-10 02:08:024420 render_view_host->GetRoutingID(), history_offset, history_length));
[email protected]796931a92011-08-10 01:32:144421}
4422
arthursonzogni818c2642019-09-27 12:18:104423void WebContentsImpl::ReloadFocusedFrame() {
Alexander Timin5fdeff22020-09-08 09:20:374424 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReloadFocusedFrame");
[email protected]1f3fc1d2014-04-03 14:50:174425 RenderFrameHost* focused_frame = GetFocusedFrame();
4426 if (!focused_frame)
4427 return;
4428
yilkal921048bd2019-10-09 23:51:044429 focused_frame->Reload();
[email protected]959be4c2014-04-08 15:01:334430}
4431
4432void WebContentsImpl::Undo() {
Alexander Timin5fdeff22020-09-08 09:20:374433 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Undo");
Dave Tapuska58a099e2020-06-08 21:48:404434 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514435 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334436 return;
4437
Dave Tapuskae782bea2019-07-09 16:21:514438 input_handler->Undo();
[email protected]959be4c2014-04-08 15:01:334439 RecordAction(base::UserMetricsAction("Undo"));
4440}
4441
4442void WebContentsImpl::Redo() {
Alexander Timin5fdeff22020-09-08 09:20:374443 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Redo");
Dave Tapuska58a099e2020-06-08 21:48:404444 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514445 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334446 return;
Dave Tapuskae782bea2019-07-09 16:21:514447
4448 input_handler->Redo();
[email protected]959be4c2014-04-08 15:01:334449 RecordAction(base::UserMetricsAction("Redo"));
4450}
4451
4452void WebContentsImpl::Cut() {
Alexander Timin5fdeff22020-09-08 09:20:374453 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Cut");
Dave Tapuska58a099e2020-06-08 21:48:404454 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514455 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334456 return;
4457
Dave Tapuskae782bea2019-07-09 16:21:514458 input_handler->Cut();
[email protected]959be4c2014-04-08 15:01:334459 RecordAction(base::UserMetricsAction("Cut"));
4460}
4461
4462void WebContentsImpl::Copy() {
Alexander Timin5fdeff22020-09-08 09:20:374463 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Copy");
Dave Tapuska58a099e2020-06-08 21:48:404464 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514465 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334466 return;
4467
Dave Tapuskae782bea2019-07-09 16:21:514468 input_handler->Copy();
[email protected]959be4c2014-04-08 15:01:334469 RecordAction(base::UserMetricsAction("Copy"));
4470}
4471
4472void WebContentsImpl::CopyToFindPboard() {
Alexander Timin5fdeff22020-09-08 09:20:374473 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CopyToFindPboard");
Avi Drissman7c57be72020-07-29 20:09:464474#if defined(OS_MAC)
Dave Tapuska58a099e2020-06-08 21:48:404475 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514476 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334477 return;
4478
4479 // Windows/Linux don't have the concept of a find pasteboard.
Dave Tapuskae782bea2019-07-09 16:21:514480 input_handler->CopyToFindPboard();
[email protected]959be4c2014-04-08 15:01:334481 RecordAction(base::UserMetricsAction("CopyToFindPboard"));
4482#endif
4483}
4484
4485void WebContentsImpl::Paste() {
Alexander Timin5fdeff22020-09-08 09:20:374486 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Paste");
Dave Tapuska58a099e2020-06-08 21:48:404487 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514488 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334489 return;
4490
Dave Tapuskae782bea2019-07-09 16:21:514491 input_handler->Paste();
Alexander Timin90c20c32020-08-12 15:28:324492 observers_.ForEachObserver(
4493 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334494 RecordAction(base::UserMetricsAction("Paste"));
4495}
4496
4497void WebContentsImpl::PasteAndMatchStyle() {
Alexander Timin5fdeff22020-09-08 09:20:374498 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::PasteAndMatchStyle");
Dave Tapuska58a099e2020-06-08 21:48:404499 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514500 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334501 return;
4502
Dave Tapuskae782bea2019-07-09 16:21:514503 input_handler->PasteAndMatchStyle();
Alexander Timin90c20c32020-08-12 15:28:324504 observers_.ForEachObserver(
4505 [&](WebContentsObserver* observer) { observer->OnPaste(); });
[email protected]959be4c2014-04-08 15:01:334506 RecordAction(base::UserMetricsAction("PasteAndMatchStyle"));
4507}
4508
4509void WebContentsImpl::Delete() {
Alexander Timin5fdeff22020-09-08 09:20:374510 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Delete");
Dave Tapuska58a099e2020-06-08 21:48:404511 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514512 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334513 return;
4514
Dave Tapuskae782bea2019-07-09 16:21:514515 input_handler->Delete();
[email protected]959be4c2014-04-08 15:01:334516 RecordAction(base::UserMetricsAction("DeleteSelection"));
4517}
4518
4519void WebContentsImpl::SelectAll() {
Alexander Timin5fdeff22020-09-08 09:20:374520 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SelectAll");
Dave Tapuska58a099e2020-06-08 21:48:404521 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514522 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334523 return;
4524
Dave Tapuskae782bea2019-07-09 16:21:514525 input_handler->SelectAll();
[email protected]959be4c2014-04-08 15:01:334526 RecordAction(base::UserMetricsAction("SelectAll"));
4527}
4528
yabinh351e7ec2017-03-10 02:43:244529void WebContentsImpl::CollapseSelection() {
Alexander Timin5fdeff22020-09-08 09:20:374530 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CollapseSelection");
Dave Tapuska58a099e2020-06-08 21:48:404531 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514532 if (!input_handler)
[email protected]959be4c2014-04-08 15:01:334533 return;
4534
Dave Tapuskae782bea2019-07-09 16:21:514535 input_handler->CollapseSelection();
[email protected]1f3fc1d2014-04-03 14:50:174536}
4537
4538void WebContentsImpl::Replace(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374539 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Replace");
Dave Tapuska58a099e2020-06-08 21:48:404540 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514541 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174542 return;
4543
Dave Tapuskae782bea2019-07-09 16:21:514544 input_handler->Replace(word);
[email protected]1f3fc1d2014-04-03 14:50:174545}
4546
4547void WebContentsImpl::ReplaceMisspelling(const base::string16& word) {
Alexander Timin5fdeff22020-09-08 09:20:374548 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ReplaceMisspelling");
Dave Tapuska58a099e2020-06-08 21:48:404549 auto* input_handler = GetFocusedFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:514550 if (!input_handler)
[email protected]1f3fc1d2014-04-03 14:50:174551 return;
4552
Dave Tapuskae782bea2019-07-09 16:21:514553 input_handler->ReplaceMisspelling(word);
[email protected]959be4c2014-04-08 15:01:334554}
4555
4556void WebContentsImpl::NotifyContextMenuClosed(
4557 const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374558 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyContextMenuClosed");
[email protected]959be4c2014-04-08 15:01:334559 RenderFrameHost* focused_frame = GetFocusedFrame();
4560 if (!focused_frame)
4561 return;
4562
4563 focused_frame->Send(new FrameMsg_ContextMenuClosed(
4564 focused_frame->GetRoutingID(), context));
4565}
4566
4567void WebContentsImpl::ExecuteCustomContextMenuCommand(
4568 int action, const CustomContextMenuContext& context) {
Alexander Timin5fdeff22020-09-08 09:20:374569 OPTIONAL_TRACE_EVENT1("content",
4570 "WebContentsImpl::ExecuteCustomContextMenuCommand",
4571 "action", action);
[email protected]959be4c2014-04-08 15:01:334572 RenderFrameHost* focused_frame = GetFocusedFrame();
4573 if (!focused_frame)
4574 return;
4575
4576 focused_frame->Send(new FrameMsg_CustomContextMenuAction(
4577 focused_frame->GetRoutingID(), context, action));
[email protected]4fed3702014-04-01 09:08:004578}
4579
[email protected]fc2b46b2014-05-03 16:33:454580gfx::NativeView WebContentsImpl::GetNativeView() {
4581 return view_->GetNativeView();
4582}
4583
4584gfx::NativeView WebContentsImpl::GetContentNativeView() {
4585 return view_->GetContentNativeView();
4586}
4587
4588gfx::NativeWindow WebContentsImpl::GetTopLevelNativeWindow() {
4589 return view_->GetTopLevelNativeWindow();
4590}
4591
4592gfx::Rect WebContentsImpl::GetViewBounds() {
4593 return view_->GetViewBounds();
4594}
4595
4596gfx::Rect WebContentsImpl::GetContainerBounds() {
Jeremy Roman352239c2020-05-21 16:31:324597 return view_->GetContainerBounds();
[email protected]fc2b46b2014-05-03 16:33:454598}
4599
4600DropData* WebContentsImpl::GetDropData() {
4601 return view_->GetDropData();
4602}
4603
4604void WebContentsImpl::Focus() {
Alexander Timin5fdeff22020-09-08 09:20:374605 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Focus");
miu9e14e492014-10-25 02:39:044606 view_->Focus();
[email protected]fc2b46b2014-05-03 16:33:454607}
4608
4609void WebContentsImpl::SetInitialFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374610 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetInitialFocus");
miu9e14e492014-10-25 02:39:044611 view_->SetInitialFocus();
[email protected]fc2b46b2014-05-03 16:33:454612}
4613
4614void WebContentsImpl::StoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374615 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StoreFocus");
miu9e14e492014-10-25 02:39:044616 view_->StoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454617}
4618
4619void WebContentsImpl::RestoreFocus() {
Alexander Timin5fdeff22020-09-08 09:20:374620 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RestoreFocus");
miu9e14e492014-10-25 02:39:044621 view_->RestoreFocus();
[email protected]fc2b46b2014-05-03 16:33:454622}
4623
[email protected]b172aee2012-04-10 17:05:264624void WebContentsImpl::FocusThroughTabTraversal(bool reverse) {
Alexander Timin5fdeff22020-09-08 09:20:374625 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusThroughTabTraversal",
4626 "reverse", reverse);
Maxim Podgorodskiya926c4ff2017-11-20 02:06:394627 view_->FocusThroughTabTraversal(reverse);
[email protected]96d185d2009-04-24 03:28:544628}
4629
[email protected]b172aee2012-04-10 17:05:264630bool WebContentsImpl::IsSavable() {
[email protected]a53209b2012-01-20 16:48:164631 // WebKit creates Document object when MIME type is application/xhtml+xml,
4632 // so we also support this MIME type.
Yuzu Saijoc23e9b72020-06-25 07:21:274633 std::string mime_type = GetContentsMimeType();
4634 return mime_type == "text/html" || mime_type == "text/xml" ||
4635 mime_type == "application/xhtml+xml" || mime_type == "text/plain" ||
4636 mime_type == "text/css" ||
4637 blink::IsSupportedJavascriptMimeType(mime_type);
[email protected]a53209b2012-01-20 16:48:164638}
4639
[email protected]b172aee2012-04-10 17:05:264640void WebContentsImpl::OnSavePage() {
Alexander Timin5fdeff22020-09-08 09:20:374641 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnSavePage");
[email protected]c7dd2f62011-07-18 15:57:594642 // If we can not save the page, try to download it.
[email protected]a53209b2012-01-20 16:48:164643 if (!IsSavable()) {
Min Qinda0ed2062018-02-23 22:00:534644 download::RecordSavePackageEvent(
4645 download::SAVE_PACKAGE_DOWNLOAD_ON_NON_HTML);
nasko89ad7742015-03-05 22:14:194646 SaveFrame(GetLastCommittedURL(), Referrer());
[email protected]27678b2a2012-02-04 22:09:144647 return;
[email protected]c7dd2f62011-07-18 15:57:594648 }
4649
4650 Stop();
4651
4652 // Create the save package and possibly prompt the user for the name to save
4653 // the page as. The user prompt is an asynchronous operation that runs on
4654 // another thread.
4655 save_package_ = new SavePackage(this);
4656 save_package_->GetSaveInfo();
4657}
4658
4659// Used in automated testing to bypass prompting the user for file names.
4660// Instead, the names and paths are hard coded rather than running them through
4661// file name sanitation and extension / mime checking.
[email protected]2dec8ec2013-02-07 19:20:344662bool WebContentsImpl::SavePage(const base::FilePath& main_file,
4663 const base::FilePath& dir_path,
[email protected]8ff00d72012-10-23 19:12:214664 SavePageType save_type) {
Alexander Timin5fdeff22020-09-08 09:20:374665 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SavePage", "main_file",
4666 base::trace_event::ValueToString(main_file), "dir_path",
4667 base::trace_event::ValueToString(dir_path));
[email protected]c7dd2f62011-07-18 15:57:594668 // Stop the page from navigating.
4669 Stop();
4670
4671 save_package_ = new SavePackage(this, save_type, main_file, dir_path);
[email protected]8ff00d72012-10-23 19:12:214672 return save_package_->Init(SavePackageDownloadCreatedCallback());
[email protected]c7dd2f62011-07-18 15:57:594673}
4674
Alexander Timin5fdeff22020-09-08 09:20:374675void WebContentsImpl::SaveFrame(const GURL& url, const Referrer& referrer) {
4676 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SaveFrame");
Xing Liu10329bf2018-03-20 19:22:144677 SaveFrameWithHeaders(url, referrer, std::string(), base::string16());
kundaji6c7f9692015-03-09 18:00:374678}
4679
Xing Liu10329bf2018-03-20 19:22:144680void WebContentsImpl::SaveFrameWithHeaders(
4681 const GURL& url,
4682 const Referrer& referrer,
4683 const std::string& headers,
4684 const base::string16& suggested_filename) {
Alexander Timin5fdeff22020-09-08 09:20:374685 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SaveFrameWithHeaders",
4686 "url", base::trace_event::ValueToString(url), "headers",
4687 headers);
Lei Zhang13a42e42019-02-19 23:28:114688 // Check and see if the guest can handle this.
4689 if (delegate_) {
4690 WebContents* guest_web_contents = nullptr;
4691 if (browser_plugin_embedder_) {
4692 BrowserPluginGuest* guest = browser_plugin_embedder_->GetFullPageGuest();
4693 if (guest)
4694 guest_web_contents = guest->GetWebContents();
4695 } else if (browser_plugin_guest_) {
4696 guest_web_contents = this;
4697 }
4698
4699 if (guest_web_contents && delegate_->GuestSaveFrame(guest_web_contents))
4700 return;
4701 }
4702
nasko89ad7742015-03-05 22:14:194703 if (!GetLastCommittedURL().is_valid())
[email protected]3c71576ce2013-07-23 02:00:014704 return;
sammc92af61552014-11-19 23:27:404705 if (delegate_ && delegate_->SaveFrame(url, referrer))
4706 return;
4707
nasko89ad7742015-03-05 22:14:194708 // TODO(nasko): This check for main frame is incorrect and should be fixed
brettw760f7442016-05-23 21:19:224709 // by explicitly passing in which frame this method should target. This would
4710 // indicate whether it's the main frame, and also tell us the frame pointer
4711 // to use for routing.
nasko89ad7742015-03-05 22:14:194712 bool is_main_frame = (url == GetLastCommittedURL());
brettw760f7442016-05-23 21:19:224713 RenderFrameHost* frame_host = GetMainFrame();
[email protected]3c71576ce2013-07-23 02:00:014714
avib7348942015-12-25 20:57:104715 int64_t post_id = -1;
[email protected]3c71576ce2013-07-23 02:00:014716 if (is_main_frame) {
Lucas Furukawa Gadani5553a152019-01-08 18:55:574717 NavigationEntry* entry = controller_.GetLastCommittedEntry();
[email protected]3c71576ce2013-07-23 02:00:014718 if (entry)
4719 post_id = entry->GetPostID();
4720 }
Ramin Halavati24e21012017-07-10 12:56:064721 net::NetworkTrafficAnnotationTag traffic_annotation =
4722 net::DefineNetworkTrafficAnnotation("download_web_contents_frame", R"(
4723 semantics {
4724 sender: "Save Page Action"
4725 description:
4726 "Saves the given frame's URL to the local file system."
4727 trigger:
4728 "The user has triggered a save operation on the frame through a "
4729 "context menu or other mechanism."
4730 data: "None."
4731 destination: WEBSITE
4732 }
4733 policy {
Ramin Halavati3b979782017-07-21 11:40:264734 cookies_allowed: YES
Ramin Halavati24e21012017-07-10 12:56:064735 cookies_store: "user"
4736 setting:
4737 "This feature cannot be disabled by settings, but it's is only "
4738 "triggered by user request."
4739 policy_exception_justification: "Not implemented."
4740 })");
Min Qina904f3302018-02-13 23:33:344741 auto params = std::make_unique<download::DownloadUrlParameters>(
brettw760f7442016-05-23 21:19:224742 url, frame_host->GetProcess()->GetID(),
4743 frame_host->GetRenderViewHost()->GetRoutingID(),
Matt Menke0dcaebc32020-03-06 17:00:104744 frame_host->GetRoutingID(), traffic_annotation);
Min Qina904f3302018-02-13 23:33:344745 params->set_referrer(referrer.url);
4746 params->set_referrer_policy(
4747 Referrer::ReferrerPolicyForUrlRequest(referrer.policy));
[email protected]3c71576ce2013-07-23 02:00:014748 params->set_post_id(post_id);
[email protected]3c71576ce2013-07-23 02:00:014749 if (post_id >= 0)
4750 params->set_method("POST");
4751 params->set_prompt(true);
kundaji6c7f9692015-03-09 18:00:374752
4753 if (headers.empty()) {
4754 params->set_prefer_cache(true);
4755 } else {
Min Qina904f3302018-02-13 23:33:344756 for (download::DownloadUrlParameters::RequestHeadersNameValuePair
4757 key_value : ParseDownloadHeaders(headers)) {
Megan Jablonski2f6a4c52017-07-10 23:01:254758 params->add_request_header(key_value.first, key_value.second);
kundaji6c7f9692015-03-09 18:00:374759 }
4760 }
Xing Liu10329bf2018-03-20 19:22:144761 params->set_suggested_name(suggested_filename);
Min Qin0ca8e1ee2018-01-31 00:49:354762 params->set_download_source(download::DownloadSource::WEB_CONTENTS_API);
thestig859c78892017-05-15 21:17:064763 BrowserContext::GetDownloadManager(GetBrowserContext())
Ramin Halavati03efa732017-06-12 09:28:204764 ->DownloadUrl(std::move(params));
[email protected]3c71576ce2013-07-23 02:00:014765}
4766
[email protected]b172aee2012-04-10 17:05:264767void WebContentsImpl::GenerateMHTML(
dewittj6dc5747a2016-05-17 01:48:474768 const MHTMLGenerationParams& params,
Avi Drissman149b7832018-03-23 14:31:494769 base::OnceCallback<void(int64_t)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374770 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTML");
Angel Alvarez902496682019-08-27 22:58:424771 base::OnceCallback<void(const MHTMLGenerationResult&)> wrapper_callback =
4772 base::BindOnce(
4773 [](base::OnceCallback<void(int64_t)> size_callback,
4774 const MHTMLGenerationResult& result) {
4775 std::move(size_callback).Run(result.file_size);
4776 },
4777 std::move(callback));
4778 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4779 std::move(wrapper_callback));
4780}
4781
4782void WebContentsImpl::GenerateMHTMLWithResult(
4783 const MHTMLGenerationParams& params,
4784 MHTMLGenerationResult::GenerateMHTMLCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:374785 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GenerateMHTMLWithResult");
Avi Drissman149b7832018-03-23 14:31:494786 MHTMLGenerationManager::GetInstance()->SaveMHTML(this, params,
4787 std::move(callback));
[email protected]aa4f3972012-03-01 18:12:124788}
4789
Tsuyoshi Horob0d8d902020-03-12 00:09:394790void WebContentsImpl::GenerateWebBundle(
4791 const base::FilePath& file_path,
4792 base::OnceCallback<void(uint64_t /* file_size */,
4793 data_decoder::mojom::WebBundlerError)> callback) {
Alexander Timin5fdeff22020-09-08 09:20:374794 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::GenerateWebBundle",
4795 "file_path",
4796 base::trace_event::ValueToString(file_path));
Tsuyoshi Horob0d8d902020-03-12 00:09:394797 SaveAsWebBundleJob::Start(this, file_path, std::move(callback));
4798}
4799
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414800const std::string& WebContentsImpl::GetContentsMimeType() {
Yuzu Saijoc23e9b72020-06-25 07:21:274801 return GetRenderViewHost()->contents_mime_type();
[email protected]0bfbf882011-12-22 18:19:274802}
4803
Leon Hanc819dc62019-01-28 04:30:194804blink::mojom::RendererPreferences* WebContentsImpl::GetMutableRendererPrefs() {
[email protected]0bfbf882011-12-22 18:19:274805 return &renderer_preferences_;
4806}
4807
[email protected]e35ccd52012-05-23 16:22:474808void WebContentsImpl::Close() {
Alexander Timin5fdeff22020-09-08 09:20:374809 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Close");
[email protected]e35ccd52012-05-23 16:22:474810 Close(GetRenderViewHost());
4811}
4812
Ella Ge80a52dce2017-11-15 18:01:524813void WebContentsImpl::DragSourceEndedAt(float client_x,
4814 float client_y,
4815 float screen_x,
4816 float screen_y,
Paul Meyer0c58c3712016-11-17 22:59:514817 blink::WebDragOperation operation,
4818 RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374819 OPTIONAL_TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("content.verbose"),
4820 "WebContentsImpl::DragSourceEndedAt");
Lei Zhang6410ec1a2019-01-31 21:38:584821 if (browser_plugin_embedder_) {
W. James MacLean9437b5bf2019-12-06 17:33:444822 browser_plugin_embedder_->DragSourceEndedAt(client_x, client_y, screen_x,
4823 screen_y, operation);
Lei Zhang6410ec1a2019-01-31 21:38:584824 }
Paul Meyer0c58c3712016-11-17 22:59:514825 if (source_rwh) {
Ella Ge80a52dce2017-11-15 18:01:524826 source_rwh->DragSourceEndedAt(gfx::PointF(client_x, client_y),
4827 gfx::PointF(screen_x, screen_y), operation);
Paul Meyer0c58c3712016-11-17 22:59:514828 }
[email protected]cf200a562013-05-03 16:24:294829}
4830
jam73f892642016-09-11 06:04:064831void WebContentsImpl::LoadStateChanged(
Charles Harrison911fa062018-03-06 21:01:464832 const std::string& host,
jam73f892642016-09-11 06:04:064833 const net::LoadStateWithParam& load_state,
4834 uint64_t upload_position,
4835 uint64_t upload_size) {
Alexander Timin5fdeff22020-09-08 09:20:374836 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::LoadStateChanged", "host",
4837 host, "load_state", static_cast<int>(load_state.state));
Charles Harrison911fa062018-03-06 21:01:464838 base::string16 host16 = url_formatter::IDNToUnicode(host);
Elly Fong-Jonescad9c3d12018-01-31 17:26:104839 // Drop no-op updates.
4840 if (load_state_.state == load_state.state &&
4841 load_state_.param == load_state.param &&
4842 upload_position_ == upload_position && upload_size_ == upload_size &&
Charles Harrison911fa062018-03-06 21:01:464843 load_state_host_ == host16) {
Elly Fong-Jonescad9c3d12018-01-31 17:26:104844 return;
4845 }
jam73f892642016-09-11 06:04:064846 load_state_ = load_state;
4847 upload_position_ = upload_position;
4848 upload_size_ = upload_size;
Charles Harrison911fa062018-03-06 21:01:464849 load_state_host_ = host16;
jam73f892642016-09-11 06:04:064850 if (load_state_.state == net::LOAD_STATE_READING_RESPONSE)
4851 SetNotWaitingForResponse();
Yuheng Huang5ed78432020-09-03 20:57:324852 if (IsLoading()) {
4853 NotifyNavigationStateChanged(static_cast<InvalidateTypes>(
4854 INVALIDATE_TYPE_LOAD | INVALIDATE_TYPE_TAB));
4855 }
jam73f892642016-09-11 06:04:064856}
4857
Collin Baker989e0882019-11-01 01:27:174858void WebContentsImpl::SetVisibilityAndNotifyObservers(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:374859 OPTIONAL_TRACE_EVENT1("content",
4860 "WebContentsImpl::SetVisibilityAndNotifyObservers",
4861 "visibility", static_cast<int>(visibility));
Francois Doraye6161152018-03-27 22:05:374862 const Visibility previous_visibility = visibility_;
4863 visibility_ = visibility;
4864
Francois Dorayfe4a1772018-02-17 04:17:094865 // Notify observers if the visibility changed or if WasShown() is being called
4866 // for the first time.
Francois Dorayfe4a1772018-02-17 04:17:094867 if (visibility != previous_visibility ||
4868 (visibility == Visibility::VISIBLE && !did_first_set_visible_)) {
Alexander Timin90c20c32020-08-12 15:28:324869 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4870 observer->OnVisibilityChanged(visibility);
4871 });
Francois Dorayfe4a1772018-02-17 04:17:094872 }
4873}
4874
Michael Thiessen896405db2017-07-20 17:52:324875void WebContentsImpl::NotifyWebContentsFocused(
4876 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374877 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::NotifyWebContentsFocused",
4878 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324879 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4880 observer->OnWebContentsFocused(render_widget_host);
4881 });
calamity7fe55ce2015-04-10 03:59:374882}
4883
Michael Thiessen896405db2017-07-20 17:52:324884void WebContentsImpl::NotifyWebContentsLostFocus(
4885 RenderWidgetHost* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:374886 OPTIONAL_TRACE_EVENT1("content",
4887 "WebContentsImpl::NotifyWebContentsLostFocus",
4888 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:324889 observers_.ForEachObserver([&](WebContentsObserver* observer) {
4890 observer->OnWebContentsLostFocus(render_widget_host);
4891 });
zijiehe3bee08e22017-05-17 04:14:464892}
4893
Paul Meyer0c58c3712016-11-17 22:59:514894void WebContentsImpl::SystemDragEnded(RenderWidgetHost* source_rwh) {
Alexander Timin5fdeff22020-09-08 09:20:374895 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SystemDragEnded",
4896 "render_widget_host", source_rwh);
Paul Meyer0c58c3712016-11-17 22:59:514897 if (source_rwh)
4898 source_rwh->DragSourceSystemDragEnded();
Lei Zhang6410ec1a2019-01-31 21:38:584899 if (browser_plugin_embedder_)
[email protected]cf200a562013-05-03 16:24:294900 browser_plugin_embedder_->SystemDragEnded();
[email protected]7813bd72011-02-05 02:19:344901}
4902
[email protected]b172aee2012-04-10 17:05:264903void WebContentsImpl::SetClosedByUserGesture(bool value) {
Alexander Timin5fdeff22020-09-08 09:20:374904 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetClosedByUserGesture",
4905 "value", value);
[email protected]0bfbf882011-12-22 18:19:274906 closed_by_user_gesture_ = value;
4907}
4908
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414909bool WebContentsImpl::GetClosedByUserGesture() {
[email protected]0bfbf882011-12-22 18:19:274910 return closed_by_user_gesture_;
4911}
4912
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414913int WebContentsImpl::GetMinimumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274914 return minimum_zoom_percent_;
4915}
4916
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414917int WebContentsImpl::GetMaximumZoomPercent() {
[email protected]0bfbf882011-12-22 18:19:274918 return maximum_zoom_percent_;
4919}
4920
Dave Tapuska8f7c3872020-02-07 01:16:384921void WebContentsImpl::SetPageScale(float scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:374922 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetPageScale",
4923 "scale_factor", scale_factor);
Dave Tapuska8f7c3872020-02-07 01:16:384924 GetMainFrame()->GetAssociatedLocalMainFrame()->SetScaleFactor(scale_factor);
ccameronb7c1d6c2015-03-09 17:08:244925}
4926
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414927gfx::Size WebContentsImpl::GetPreferredSize() {
Francois Doray24fc62c2017-12-11 17:27:334928 return IsBeingCaptured() ? preferred_size_for_capture_ : preferred_size_;
[email protected]bcd2815602012-01-14 18:17:234929}
4930
James Hollyerd5c9de462020-03-10 19:02:454931bool WebContentsImpl::GotResponseToLockMouseRequest(
4932 blink::mojom::PointerLockResult result) {
Alexander Timin5fdeff22020-09-08 09:20:374933 OPTIONAL_TRACE_EVENT0("content",
4934 "WebContentsImpl::GotResponseToLockMouseRequest");
lfgf0cd46e2017-01-04 00:05:234935 if (mouse_lock_widget_) {
4936 if (mouse_lock_widget_->delegate()->GetAsWebContents() != this) {
4937 return mouse_lock_widget_->delegate()
4938 ->GetAsWebContents()
James Hollyerd5c9de462020-03-10 19:02:454939 ->GotResponseToLockMouseRequest(result);
lfgf0cd46e2017-01-04 00:05:234940 }
lfgad8244352016-07-13 16:55:514941
James Hollyerd5c9de462020-03-10 19:02:454942 if (mouse_lock_widget_->GotResponseToLockMouseRequest(result))
lfgf0cd46e2017-01-04 00:05:234943 return true;
4944 }
4945
4946 for (WebContentsImpl* current = this; current;
4947 current = current->GetOuterWebContents()) {
4948 current->mouse_lock_widget_ = nullptr;
4949 }
4950
lfgbee1e0a2016-06-08 21:24:214951 return false;
[email protected]0bfbf882011-12-22 18:19:274952}
4953
James Hollyerd5c9de462020-03-10 19:02:454954void WebContentsImpl::GotLockMousePermissionResponse(bool allowed) {
4955 GotResponseToLockMouseRequest(
4956 allowed ? blink::mojom::PointerLockResult::kSuccess
4957 : blink::mojom::PointerLockResult::kPermissionDenied);
4958}
4959
Joe Downing13dd76b2018-04-09 18:32:154960bool WebContentsImpl::GotResponseToKeyboardLockRequest(bool allowed) {
Alexander Timin5fdeff22020-09-08 09:20:374961 OPTIONAL_TRACE_EVENT1("content",
4962 "WebContentsImpl::GotResponseToKeyboardLockRequest",
4963 "allowed", allowed);
4964
Joe Downing13dd76b2018-04-09 18:32:154965 if (!keyboard_lock_widget_)
4966 return false;
4967
4968 if (keyboard_lock_widget_->delegate()->GetAsWebContents() != this) {
4969 NOTREACHED();
4970 return false;
4971 }
4972
4973 // KeyboardLock is only supported when called by the top-level browsing
4974 // context and is not supported in embedded content scenarios.
4975 if (GetOuterWebContents())
4976 return false;
4977
4978 keyboard_lock_widget_->GotResponseToKeyboardLockRequest(allowed);
4979 return true;
4980}
4981
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414982bool WebContentsImpl::HasOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284983 return GetOpener() != nullptr;
[email protected]a0358d72012-03-09 14:06:504984}
4985
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414986RenderFrameHostImpl* WebContentsImpl::GetOpener() {
alexmose201c7cd2015-06-10 17:14:214987 FrameTreeNode* opener_ftn = frame_tree_.root()->opener();
lukasza6f8ac622017-06-06 03:10:204988 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen55ff3502014-12-18 20:52:574989}
4990
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414991bool WebContentsImpl::HasOriginalOpener() {
Ivan Kotenkov2c0d2bb32017-11-01 15:41:284992 return GetOriginalOpener() != nullptr;
jochen6004a362017-02-04 00:11:404993}
4994
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:414995RenderFrameHostImpl* WebContentsImpl::GetOriginalOpener() {
jochen6004a362017-02-04 00:11:404996 FrameTreeNode* opener_ftn = frame_tree_.root()->original_opener();
lukasza6f8ac622017-06-06 03:10:204997 return opener_ftn ? opener_ftn->current_frame_host() : nullptr;
jochen6004a362017-02-04 00:11:404998}
4999
[email protected]cb805452013-05-22 15:16:215000void WebContentsImpl::DidChooseColorInColorChooser(SkColor color) {
Alexander Timin5fdeff22020-09-08 09:20:375001 OPTIONAL_TRACE_EVENT1("content",
5002 "WebContentsImpl::DidChooseColorInColorChooser",
5003 "color", color);
Joel Hockey85b379d2017-12-11 10:42:135004 color_chooser_->DidChooseColorInColorChooser(color);
[email protected]da8543762012-03-20 08:52:205005}
5006
[email protected]cb805452013-05-22 15:16:215007void WebContentsImpl::DidEndColorChooser() {
Alexander Timin5fdeff22020-09-08 09:20:375008 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidEndColorChooser");
Joel Hockey85b379d2017-12-11 10:42:135009 color_chooser_.reset();
[email protected]da8543762012-03-20 08:52:205010}
5011
halton.huoca2eabd2015-07-06 08:17:405012int WebContentsImpl::DownloadImage(
5013 const GURL& url,
5014 bool is_favicon,
Fredrik Söderquistb2b39eb92019-11-18 16:16:505015 uint32_t preferred_size,
halton.huoca2eabd2015-07-06 08:17:405016 uint32_t max_bitmap_size,
5017 bool bypass_cache,
Avi Drissmana5a52dd2018-03-27 03:39:025018 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375019 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DownloadImage", "url",
5020 base::trace_event::ValueToString(url));
Danyao Wanga78f3dd22020-03-05 05:31:275021 return DownloadImageInFrame(GlobalFrameRoutingId(), url, is_favicon,
5022 preferred_size, max_bitmap_size, bypass_cache,
5023 std::move(callback));
5024}
5025
5026int WebContentsImpl::DownloadImageInFrame(
5027 const GlobalFrameRoutingId& initiator_frame_routing_id,
5028 const GURL& url,
5029 bool is_favicon,
5030 uint32_t preferred_size,
5031 uint32_t max_bitmap_size,
5032 bool bypass_cache,
5033 WebContents::ImageDownloadCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375034 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DownloadImageInFrame");
amistry9f01b772015-07-29 01:54:555035 DCHECK_CURRENTLY_ON(BrowserThread::UI);
halton.huoca2eabd2015-07-06 08:17:405036 static int next_image_download_id = 0;
Danyao Wanga78f3dd22020-03-05 05:31:275037
5038 RenderFrameHostImpl* initiator_frame =
5039 initiator_frame_routing_id.child_id
5040 ? RenderFrameHostImpl::FromID(initiator_frame_routing_id)
5041 : GetMainFrame();
Julie Jeongeun Kimb1473572019-08-15 05:59:135042 const mojo::Remote<blink::mojom::ImageDownloader>& mojo_image_downloader =
Danyao Wanga78f3dd22020-03-05 05:31:275043 initiator_frame->GetMojoImageDownloader();
amistry9f01b772015-07-29 01:54:555044 const int download_id = ++next_image_download_id;
5045 if (!mojo_image_downloader) {
5046 // If the renderer process is dead (i.e. crash, or memory pressure on
5047 // Android), the downloader service will be invalid. Pre-Mojo, this would
Avi Drissmana5a52dd2018-03-27 03:39:025048 // hang the callback indefinitely since the IPC would be dropped. Now,
amistry9f01b772015-07-29 01:54:555049 // respond with a 400 HTTP error code to indicate that something went wrong.
Gabriel Charettee7cdc5cd2020-05-27 23:35:055050 GetUIThreadTaskRunner({})->PostTask(
5051 FROM_HERE,
tzike2aca992017-09-05 08:50:545052 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:025053 weak_factory_.GetWeakPtr(), std::move(callback),
5054 download_id, url, 400, std::vector<SkBitmap>(),
5055 std::vector<gfx::Size>()));
amistry9f01b772015-07-29 01:54:555056 return download_id;
5057 }
5058
halton.huoca2eabd2015-07-06 08:17:405059 mojo_image_downloader->DownloadImage(
Fredrik Söderquistb2b39eb92019-11-18 16:16:505060 url, is_favicon, preferred_size, max_bitmap_size, bypass_cache,
tzike2aca992017-09-05 08:50:545061 base::BindOnce(&WebContentsImpl::OnDidDownloadImage,
Avi Drissmana5a52dd2018-03-27 03:39:025062 weak_factory_.GetWeakPtr(), std::move(callback),
5063 download_id, url));
amistry9f01b772015-07-29 01:54:555064 return download_id;
[email protected]795c28972012-12-06 06:13:395065}
5066
[email protected]36ec24f2014-01-09 00:32:085067void WebContentsImpl::Find(int request_id,
5068 const base::string16& search_text,
Rakina Zata Amni3f77dff2018-09-08 16:19:435069 blink::mojom::FindOptionsPtr options) {
Alexander Timin5fdeff22020-09-08 09:20:375070 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Find");
thestig6057a6b22015-11-12 23:01:335071 // Cowardly refuse to search for no text.
5072 if (search_text.empty()) {
5073 NOTREACHED();
5074 return;
5075 }
5076
Rakina Zata Amni3f77dff2018-09-08 16:19:435077 GetOrCreateFindRequestManager()->Find(request_id, search_text,
5078 std::move(options));
[email protected]36ec24f2014-01-09 00:32:085079}
5080
5081void WebContentsImpl::StopFinding(StopFindAction action) {
Alexander Timin5fdeff22020-09-08 09:20:375082 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::StopFinding");
paulmeyerfeafc2d2017-04-25 21:46:405083 if (FindRequestManager* manager = GetFindRequestManager())
5084 manager->StopFinding(action);
[email protected]36ec24f2014-01-09 00:32:085085}
5086
Tommy Steimel18360512017-11-01 00:38:195087bool WebContentsImpl::WasEverAudible() {
5088 return was_ever_audible_;
5089}
5090
Avi Drissmana5a52dd2018-03-27 03:39:025091void WebContentsImpl::GetManifest(GetManifestCallback callback) {
Alexander Timin5fdeff22020-09-08 09:20:375092 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetManifest");
Yuzu Saijofce18322020-05-14 05:02:095093 // TODO(yuzus, 1061899): Move this function to RenderFrameHostImpl.
5094 ManifestManagerHost* manifest_manager_host =
5095 ManifestManagerHost::GetOrCreateForCurrentDocument(GetMainFrame());
5096 manifest_manager_host->GetManifest(std::move(callback));
mlamouriefdca9d2014-09-16 16:55:405097}
5098
bokanece34a82016-01-28 19:49:465099void WebContentsImpl::ExitFullscreen(bool will_cause_resize) {
Alexander Timin5fdeff22020-09-08 09:20:375100 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitFullscreen");
mlamouri7a78d6fd2015-01-17 13:23:535101 // Clean up related state and initiate the fullscreen exit.
James Hollyerd5c9de462020-03-10 19:02:455102 GetRenderViewHost()->GetWidget()->RejectMouseLockOrUnlockIfNecessary(
5103 blink::mojom::PointerLockResult::kUserRejected);
bokanece34a82016-01-28 19:49:465104 ExitFullscreenMode(will_cause_resize);
mlamouri7a78d6fd2015-01-17 13:23:535105}
5106
Mike Wassermanb6bc0152020-08-25 22:46:205107base::ScopedClosureRunner WebContentsImpl::ForSecurityDropFullscreen(
5108 int64_t display_id) {
Alexander Timin5fdeff22020-09-08 09:20:375109 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ForSecurityDropFullscreen",
5110 "display_id", display_id);
Avi Drissman33972942020-06-19 14:16:015111 // Kick WebContentses that are "related" to this WebContents out of
5112 // fullscreen. This needs to be done with two passes, because it is simple to
5113 // walk _up_ the chain of openers and outer contents, but it not simple to
5114 // walk _down_ the chain.
5115
5116 // First, determine if any WebContents that is in fullscreen has this
5117 // WebContents as an upstream contents. Drop that WebContents out of
5118 // fullscreen if it does. This is theoretically quadratic-ish (fullscreen
5119 // contentses x each one's opener length) but neither of those is expected to
5120 // ever be a large number.
5121
Mike Wassermanb6bc0152020-08-25 22:46:205122 auto* screen = display::Screen::GetScreen();
5123
Avi Drissman33972942020-06-19 14:16:015124 auto fullscreen_set_copy = *FullscreenContentsSet(GetBrowserContext());
5125 for (auto* fullscreen_contents : fullscreen_set_copy) {
Avi Drissman97aef042020-06-30 21:04:485126 // Checking IsFullscreen() for tabs in the fullscreen set may seem
5127 // redundant, but teeeeechnically fullscreen is run by the delegate, and
5128 // it's possible that the delegate's notion of fullscreen may have changed
5129 // outside of WebContents's notice.
Mike Wassermanb6bc0152020-08-25 22:46:205130 if (fullscreen_contents->IsFullscreen() &&
5131 (display_id == display::kInvalidDisplayId || !screen ||
5132 display_id ==
5133 screen->GetDisplayNearestView(fullscreen_contents->GetNativeView())
5134 .id())) {
Avi Drissman33972942020-06-19 14:16:015135 auto opener_contentses = GetAllOpeningWebContents(fullscreen_contents);
5136 if (opener_contentses.count(this))
5137 fullscreen_contents->ExitFullscreen(true);
5138 }
5139 }
5140
5141 // Second, walk upstream from this WebContents, and drop the fullscreen of
5142 // all WebContentses that are in fullscreen. Block all the WebContentses in
5143 // the chain from entering fullscreen while the returned closure runner is
5144 // alive. It's OK that this set doesn't contain downstream WebContentses, as
5145 // any request to enter fullscreen will have the upstream of the WebContents
5146 // checked. (See CanEnterFullscreenMode().)
Avi Drissmanced52b62019-08-14 21:25:465147
Avi Drissman1a55a9d62020-03-10 18:56:455148 std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses;
5149
Avi Drissman33972942020-06-19 14:16:015150 for (auto* opener : GetAllOpeningWebContents(this)) {
Avi Drissman1a55a9d62020-03-10 18:56:455151 // Drop fullscreen if the WebContents is in it, and...
Mike Wassermanb6bc0152020-08-25 22:46:205152 if (opener->IsFullscreen() &&
5153 (display_id == display::kInvalidDisplayId || !screen ||
5154 display_id ==
5155 screen->GetDisplayNearestView(opener->GetNativeView()).id()))
Avi Drissman33972942020-06-19 14:16:015156 opener->ExitFullscreen(true);
Avi Drissmanced52b62019-08-14 21:25:465157
Avi Drissman1a55a9d62020-03-10 18:56:455158 // ...block the WebContents from entering fullscreen until further notice.
Avi Drissman33972942020-06-19 14:16:015159 ++opener->fullscreen_blocker_count_;
5160 blocked_contentses.push_back(opener->weak_factory_.GetWeakPtr());
Avi Drissmanced52b62019-08-14 21:25:465161 }
Avi Drissman1a55a9d62020-03-10 18:56:455162
5163 return base::ScopedClosureRunner(base::BindOnce(
5164 [](std::vector<base::WeakPtr<WebContentsImpl>> blocked_contentses) {
5165 for (base::WeakPtr<WebContentsImpl>& web_contents :
5166 blocked_contentses) {
5167 if (web_contents) {
5168 DCHECK_GT(web_contents->fullscreen_blocker_count_, 0);
5169 --web_contents->fullscreen_blocker_count_;
5170 }
5171 }
5172 },
5173 std::move(blocked_contentses)));
Avi Drissmanced52b62019-08-14 21:25:465174}
5175
mariakhomenko44bdc4732015-04-29 01:55:385176void WebContentsImpl::ResumeLoadingCreatedWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:375177 OPTIONAL_TRACE_EVENT0("content",
5178 "WebContentsImpl::ResumeLoadingCreatedWebContents");
Nasko Oskov83a8cf92018-10-19 14:58:565179 if (delayed_load_url_params_.get()) {
5180 DCHECK(!delayed_open_url_params_);
5181 controller_.LoadURLWithParams(*delayed_load_url_params_.get());
5182 delayed_load_url_params_.reset(nullptr);
5183 return;
5184 }
5185
mariakhomenkoa4971c12015-07-21 19:04:375186 if (delayed_open_url_params_.get()) {
5187 OpenURL(*delayed_open_url_params_.get());
5188 delayed_open_url_params_.reset(nullptr);
5189 return;
5190 }
5191
mariakhomenko44bdc4732015-04-29 01:55:385192 // Resume blocked requests for both the RenderViewHost and RenderFrameHost.
5193 // TODO(brettw): It seems bogus to reach into here and initialize the host.
dfalcantarae6b7b46752015-07-10 18:14:165194 if (is_resume_pending_) {
5195 is_resume_pending_ = false;
avi0f1bbc9712015-11-17 02:58:135196 GetRenderViewHost()->GetWidget()->Init();
dfalcantarae6b7b46752015-07-10 18:14:165197 GetMainFrame()->Init();
5198 }
mariakhomenko44bdc4732015-04-29 01:55:385199}
5200
[email protected]b172aee2012-04-10 17:05:265201bool WebContentsImpl::FocusLocationBarByDefault() {
Alexander Timin5fdeff22020-09-08 09:20:375202 OPTIONAL_TRACE_EVENT0("content",
5203 "WebContentsImpl::FocusLocationBarByDefault");
Xiyuan Xia2a66b112018-12-06 15:52:165204 if (should_focus_location_bar_by_default_)
[email protected]0c9406632013-02-08 01:13:335205 return true;
Xiyuan Xia2a66b112018-12-06 15:52:165206
[email protected]0c9406632013-02-08 01:13:335207 return delegate_ && delegate_->ShouldFocusLocationBarByDefault(this);
[email protected]0bfbf882011-12-22 18:19:275208}
5209
Tommy C. Li8bb5bf42019-01-18 18:45:515210void WebContentsImpl::SetFocusToLocationBar() {
Alexander Timin5fdeff22020-09-08 09:20:375211 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetFocusToLocationBar");
[email protected]0bfbf882011-12-22 18:19:275212 if (delegate_)
Tommy C. Li8bb5bf42019-01-18 18:45:515213 delegate_->SetFocusToLocationBar();
[email protected]c40d6232011-03-25 00:16:215214}
5215
clamy0e119882015-07-31 16:12:335216void WebContentsImpl::DidStartNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485217 TRACE_EVENT1("navigation", "WebContentsImpl::DidStartNavigation",
5218 "navigation_handle", navigation_handle);
Alan Cutterab48fc02020-02-24 12:26:425219 if (navigation_handle->IsInMainFrame())
5220 favicon_urls_.clear();
Mounir Lamouri7b4a1f232019-12-23 16:32:105221
Alexander Timin90c20c32020-08-12 15:28:325222 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5223 observer->DidStartNavigation(navigation_handle);
5224 });
Xiyuan Xia2a66b112018-12-06 15:52:165225 if (navigation_handle->IsInMainFrame()) {
5226 // When the browser is started with about:blank as the startup URL, focus
5227 // the location bar (which will also select its contents) so people can
5228 // simply begin typing to navigate elsewhere.
5229 //
5230 // We need to be careful not to trigger this for anything other than the
5231 // startup navigation. In particular, if we allow an attacker to open a
5232 // popup to about:blank, then navigate, focusing the Omnibox will cause the
5233 // end of the new URL to be scrolled into view instead of the start,
5234 // allowing the attacker to spoof other URLs. The conditions checked here
5235 // are all aimed at ensuring no such attacker-controlled navigation can
5236 // trigger this.
5237 should_focus_location_bar_by_default_ =
5238 controller_.IsInitialNavigation() &&
5239 !navigation_handle->IsRendererInitiated() &&
5240 navigation_handle->GetURL() == url::kAboutBlankURL;
5241 }
clamy0e119882015-07-31 16:12:335242}
5243
5244void WebContentsImpl::DidRedirectNavigation(
5245 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485246 TRACE_EVENT1("navigation", "WebContentsImpl::DidRedirectNavigation",
5247 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325248 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5249 observer->DidRedirectNavigation(navigation_handle);
5250 });
jam5f358e52017-02-13 16:37:035251 // Notify accessibility if this is a reload. This has to called on the
5252 // BrowserAccessibilityManager associated with the old RFHI.
5253 if (navigation_handle->GetReloadType() != ReloadType::NONE) {
Mohamed Abdelhalim95794962019-09-20 11:16:495254 NavigationRequest* request = NavigationRequest::From(navigation_handle);
jam5f358e52017-02-13 16:37:035255 BrowserAccessibilityManager* manager =
Mohamed Abdelhalim95794962019-09-20 11:16:495256 request->frame_tree_node()
jam5f358e52017-02-13 16:37:035257 ->current_frame_host()
5258 ->browser_accessibility_manager();
5259 if (manager)
5260 manager->UserIsReloading();
5261 }
clamy0e119882015-07-31 16:12:335262}
5263
clamyefca29e2015-09-17 00:22:115264void WebContentsImpl::ReadyToCommitNavigation(
5265 NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485266 TRACE_EVENT1("navigation", "WebContentsImpl::ReadyToCommitNavigation",
5267 "navigation_handle", navigation_handle);
Alexander Timin90c20c32020-08-12 15:28:325268 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5269 observer->ReadyToCommitNavigation(navigation_handle);
5270 });
Kenneth Russell954ed9ce2018-04-12 23:07:015271 // If any domains are blocked from accessing 3D APIs because they may
5272 // have caused the GPU to reset recently, unblock them here if the user
5273 // initiated this navigation. This implies that the user was involved in
5274 // the decision to navigate, so there's no concern about
5275 // denial-of-service issues. Want to do this as early as
5276 // possible to avoid race conditions with pages attempting to access
5277 // WebGL early on.
5278 //
5279 // TODO(crbug.com/617904): currently navigations initiated by the browser
5280 // (reload button, reload menu option, pressing return in the Omnibox)
5281 // return false from HasUserGesture(). If or when that is addressed,
5282 // remove the check for IsRendererInitiated() below.
5283 //
5284 // TODO(crbug.com/832180): HasUserGesture comes from the renderer
5285 // process and isn't validated. Until it is, don't trust it.
5286 if (!navigation_handle->IsRendererInitiated()) {
5287 GpuDataManagerImpl::GetInstance()->UnblockDomainFrom3DAPIs(
5288 navigation_handle->GetURL());
5289 }
5290
John Abd-El-Malekfde08e6da2017-12-05 04:06:245291 if (navigation_handle->IsSameDocument())
5292 return;
5293
Livvie Lin139bf442018-08-10 00:18:545294 // SSLInfo is not needed on subframe navigations since the main-frame
5295 // certificate is the only one that can be inspected (using the info
5296 // bubble) without refreshing the page with DevTools open.
Carlos ILaed1e7b2019-03-12 19:27:215297 // We don't call DidStartResourceResponse on net errors, since that results on
5298 // existing cert exceptions being revoked, which leads to weird behavior with
5299 // committed interstitials or while offline. We only need the error check for
5300 // the main frame case because unlike this method, SubresourceResponseStarted
5301 // does not get called on network errors.
5302 if (navigation_handle->IsInMainFrame() &&
5303 navigation_handle->GetNetErrorCode() == net::OK) {
Livvie Lin139bf442018-08-10 00:18:545304 controller_.ssl_manager()->DidStartResourceResponse(
Lukasz Anforowiczd334bba2020-02-10 23:32:555305 navigation_handle->GetURL(),
Camille Lamy62b826012019-02-26 09:15:475306 navigation_handle->GetSSLInfo().has_value()
5307 ? net::IsCertStatusError(
5308 navigation_handle->GetSSLInfo()->cert_status)
5309 : false);
5310 }
John Abd-El-Malekfde08e6da2017-12-05 04:06:245311
5312 SetNotWaitingForResponse();
clamyefca29e2015-09-17 00:22:115313}
5314
clamy0e119882015-07-31 16:12:335315void WebContentsImpl::DidFinishNavigation(NavigationHandle* navigation_handle) {
Charles Harrison53096ba2017-12-15 15:39:485316 TRACE_EVENT1("navigation", "WebContentsImpl::DidFinishNavigation",
5317 "navigation_handle", navigation_handle);
Steven Holte38041342018-06-22 22:00:575318
Alexander Timin90c20c32020-08-12 15:28:325319 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5320 observer->DidFinishNavigation(navigation_handle);
5321 });
Becca Hughesd11d6502018-07-31 17:01:285322 if (display_cutout_host_impl_)
5323 display_cutout_host_impl_->DidFinishNavigation(navigation_handle);
5324
jam5f358e52017-02-13 16:37:035325 if (navigation_handle->HasCommitted()) {
Ian Prestcdd843d2020-01-28 18:59:585326 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
5327 // https://crbug.com/981271.
5328 BrowserAccessibilityManager* manager =
5329 static_cast<RenderFrameHostImpl*>(
5330 navigation_handle->GetRenderFrameHost())
5331 ->browser_accessibility_manager();
5332 if (manager) {
5333 if (navigation_handle->IsErrorPage()) {
5334 manager->NavigationFailed();
5335 } else {
5336 manager->NavigationSucceeded();
5337 }
5338 }
5339
Yue Ru Sun979c4b162019-11-06 16:11:045340 if (navigation_handle->IsInMainFrame()) {
5341 last_committed_source_id_including_same_document_ =
Steven Holte38041342018-06-22 22:00:575342 ukm::ConvertToSourceId(navigation_handle->GetNavigationId(),
5343 ukm::SourceIdType::NAVIGATION_ID);
Yue Ru Sun979c4b162019-11-06 16:11:045344
5345 if (!navigation_handle->IsSameDocument()) {
5346 was_ever_audible_ = false;
Yue Ru Sun979c4b162019-11-06 16:11:045347 }
Tommy Steimel18360512017-11-01 00:38:195348 }
Lan Weif81c6e7c2020-02-12 16:46:095349
5350 if (!navigation_handle->IsSameDocument())
5351 last_screen_orientation_change_time_ = base::TimeTicks();
dmazzonibf8cec42015-02-08 08:28:085352 }
Xiyuan Xia2a66b112018-12-06 15:52:165353
5354 // If we didn't end up on about:blank after setting this in DidStartNavigation
5355 // then don't focus the location bar.
5356 if (should_focus_location_bar_by_default_ &&
5357 navigation_handle->GetURL() != url::kAboutBlankURL) {
5358 should_focus_location_bar_by_default_ = false;
5359 }
yilkal796e89e2019-10-02 23:58:285360
yilkal172da772019-11-06 22:49:075361 if (navigation_handle->IsInMainFrame() && first_navigation_completed_)
5362 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:285363
yilkal172da772019-11-06 22:49:075364 // If navigation has successfully finished in the main frame, set
5365 // |first_navigation_completed_| to true so that we will record
5366 // |max_loaded_frame_count_| above when future main frame navigations finish.
5367 if (navigation_handle->IsInMainFrame() && !navigation_handle->IsErrorPage()) {
5368 first_navigation_completed_ = true;
5369
5370 // Navigation has completed in main frame. Reset |max_loaded_frame_count_|.
5371 // |max_loaded_frame_count_| is not necessarily 1 if the navigation was
5372 // served from BackForwardCache.
5373 max_loaded_frame_count_ =
5374 GetMainFrame()->frame_tree_node()->GetFrameTreeSize();
yilkal796e89e2019-10-02 23:58:285375 }
Rakina Zata Amni347b70902020-07-22 10:49:045376
5377 if (web_preferences_) {
5378 // Update the WebPreferences for this WebContents that depends on changes
5379 // that might occur during navigation. This will only update the preferences
5380 // that needs to be updated (and won't cause an update/overwrite preferences
5381 // that needs to stay the same after navigations).
5382 bool value_changed_due_to_override =
5383 GetContentClient()->browser()->OverrideWebPreferencesAfterNavigation(
5384 this, web_preferences_.get());
5385 // We need to update the WebPreferences value on the renderer if the value
5386 // is changed due to the override above, or if the navigation is served from
5387 // the back-forward cache, because the WebPreferences value stored in the
5388 // renderer might be stale (because we don't send WebPreferences updates to
5389 // bfcached renderers).
5390 // TODO(rakina): Maybe handle the back-forward cache case in
5391 // ReadyToCommitNavigation instead?
5392 if (value_changed_due_to_override ||
5393 NavigationRequest::From(navigation_handle)
5394 ->IsServedFromBackForwardCache()) {
5395 SetWebPreferences(*web_preferences_.get());
5396 }
5397 }
[email protected]400992b2012-06-14 00:03:545398}
5399
[email protected]b80624c2014-02-09 02:46:555400void WebContentsImpl::DidFailLoadWithError(
5401 RenderFrameHostImpl* render_frame_host,
[email protected]b80624c2014-02-09 02:46:555402 const GURL& url,
Dave Tapuska924ef3c2020-01-22 18:20:595403 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:375404 TRACE_EVENT2("content,navigation", "WebContentsImpl::DidFailLoadWithError",
5405 "render_frame_host",
5406 base::trace_event::ToTracedValue(render_frame_host), "url",
5407 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325408 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5409 observer->DidFailLoad(render_frame_host, url, error_code);
5410 });
[email protected]b80624c2014-02-09 02:46:555411}
5412
[email protected]52913802013-12-10 05:52:185413void WebContentsImpl::NotifyChangedNavigationState(
5414 InvalidateTypes changed_flags) {
5415 NotifyNavigationStateChanged(changed_flags);
5416}
5417
lukasza1d025732016-09-28 21:36:085418bool WebContentsImpl::ShouldTransferNavigation(bool is_main_frame_navigation) {
Alexander Timin5fdeff22020-09-08 09:20:375419 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShouldTransferNavigation",
5420 "is_main_frame_navigation", is_main_frame_navigation);
creis29460272015-12-16 04:38:225421 if (!delegate_)
5422 return true;
lukasza1d025732016-09-28 21:36:085423 return delegate_->ShouldTransferNavigation(is_main_frame_navigation);
creis29460272015-12-16 04:38:225424}
5425
[email protected]aa62afd2014-04-22 19:22:465426bool WebContentsImpl::ShouldPreserveAbortedURLs() {
Alexander Timin5fdeff22020-09-08 09:20:375427 OPTIONAL_TRACE_EVENT0("content",
5428 "WebContentsImpl::ShouldPreserveAbortedURLs");
[email protected]aa62afd2014-04-22 19:22:465429 if (!delegate_)
5430 return false;
5431 return delegate_->ShouldPreserveAbortedURLs(this);
5432}
5433
[email protected]0d0f4c492014-04-02 06:42:575434void WebContentsImpl::DidNavigateMainFramePreCommit(
[email protected]5cfbddc2014-06-23 23:52:235435 bool navigation_is_within_page) {
Alexander Timin5fdeff22020-09-08 09:20:375436 TRACE_EVENT1("content,navigation",
5437 "WebContentsImpl::DidNavigateMainFramePreCommit",
5438 "navigation_is_within_page", navigation_is_within_page);
[email protected]0d0f4c492014-04-02 06:42:575439 // Ensure fullscreen mode is exited before committing the navigation to a
5440 // different page. The next page will not start out assuming it is in
5441 // fullscreen mode.
[email protected]5cfbddc2014-06-23 23:52:235442 if (navigation_is_within_page) {
[email protected]dfc39cb2014-04-09 22:58:195443 // No page change? Then, the renderer and browser can remain in fullscreen.
[email protected]0d0f4c492014-04-02 06:42:575444 return;
5445 }
Avi Drissman97aef042020-06-30 21:04:485446 if (IsFullscreen())
bokanece34a82016-01-28 19:49:465447 ExitFullscreen(false);
Avi Drissman97aef042020-06-30 21:04:485448 DCHECK(!IsFullscreen());
Joe Downingc1a57efe2018-05-09 18:23:545449
5450 // Clean up keyboard lock state when navigating.
5451 CancelKeyboardLock(keyboard_lock_widget_);
[email protected]0d0f4c492014-04-02 06:42:575452}
5453
[email protected]37567b432014-02-12 01:12:225454void WebContentsImpl::DidNavigateMainFramePostCommit(
sky8b00392d2015-01-10 00:30:285455 RenderFrameHostImpl* render_frame_host,
[email protected]37567b432014-02-12 01:12:225456 const LoadCommittedDetails& details,
5457 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375458 OPTIONAL_TRACE_EVENT1(
5459 "content,navigation", "WebContentsImpl::DidNavigateMainFramePostCommit",
5460 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]37567b432014-02-12 01:12:225461 if (details.is_navigation_to_different_page()) {
5462 // Clear the status bubble. This is a workaround for a bug where WebKit
5463 // doesn't let us know that the cursor left an element during a
5464 // transition (this is also why the mouse cursor remains as a hand after
5465 // clicking on a link); see bugs 1184641 and 980803. We don't want to
5466 // clear the bubble when a user navigates to a named anchor in the same
5467 // page.
Lukasz Anforowiczfd707142018-02-07 19:46:135468 ClearTargetURL();
lanwei9d343ad22015-02-11 01:46:005469
5470 RenderWidgetHostViewBase* rwhvb =
5471 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
5472 if (rwhvb)
5473 rwhvb->OnDidNavigateMainFrameToNewPage();
[email protected]37567b432014-02-12 01:12:225474 }
5475
[email protected]e85165c642014-06-10 14:34:315476 if (delegate_)
[email protected]37567b432014-02-12 01:12:225477 delegate_->DidNavigateMainFramePostCommit(this);
[email protected]e85165c642014-06-10 14:34:315478 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
Shivani Sharma985474f2019-05-23 21:36:475479
Alan Cutterd73a15d92020-08-21 07:12:455480 // The following events will not fire again if the page is restored from the
5481 // BackForwardCache. So fire them ourselves if needed.
Carlos Caballero91fffb22019-10-29 15:24:305482 if (details.is_navigation_to_different_page() &&
5483 GetRenderViewHost()->did_first_visually_non_empty_paint()) {
Carlos Caballero91fffb22019-10-29 15:24:305484 DidFirstVisuallyNonEmptyPaint(GetRenderViewHost());
5485 }
Alan Cutterd73a15d92020-08-21 07:12:455486 if (GetRenderViewHost()->theme_color() != last_sent_theme_color_)
Carlos Caballero1215f882019-10-29 15:58:435487 OnThemeColorChanged(GetRenderViewHost());
Alan Cutterd73a15d92020-08-21 07:12:455488 if (GetRenderViewHost()->background_color() != last_sent_background_color_)
5489 OnBackgroundColorChanged(GetRenderViewHost());
[email protected]37567b432014-02-12 01:12:225490}
5491
5492void WebContentsImpl::DidNavigateAnyFramePostCommit(
5493 RenderFrameHostImpl* render_frame_host,
5494 const LoadCommittedDetails& details,
5495 const FrameHostMsg_DidCommitProvisionalLoad_Params& params) {
Alexander Timin5fdeff22020-09-08 09:20:375496 OPTIONAL_TRACE_EVENT1(
5497 "content,navigation", "WebContentsImpl::DidNavigateAnyFramePostCommit",
5498 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
[email protected]b4c84012014-04-28 19:51:105499 // Now that something has committed, we don't need to track whether the
5500 // initial page has been accessed.
5501 has_accessed_initial_document_ = false;
5502
[email protected]37567b432014-02-12 01:12:225503 // If we navigate off the page, close all JavaScript dialogs.
eugenebutee08663a2017-04-27 17:43:125504 if (!details.is_same_document)
creis89a0f782015-05-27 16:13:175505 CancelActiveAndPendingDialogs();
[email protected]37567b432014-02-12 01:12:225506
avid53461d2016-02-25 17:15:045507 // If this is a user-initiated navigation, start allowing JavaScript dialogs
5508 // again.
avi5d3b8692016-10-12 22:00:465509 if (params.gesture == NavigationGestureUser && dialog_manager_) {
avi6879fcf2017-01-21 05:27:535510 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:465511 }
[email protected]37567b432014-02-12 01:12:225512}
5513
[email protected]277857a2014-06-03 10:38:015514bool WebContentsImpl::CanOverscrollContent() const {
Alexander Timin5fdeff22020-09-08 09:20:375515 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::CanOverscrollContent");
[email protected]e85165c642014-06-10 14:34:315516 // Disable overscroll when touch emulation is on. See crbug.com/369938.
[email protected]34ff1cfc2014-08-20 06:16:055517 if (force_disable_overscroll_content_)
[email protected]e85165c642014-06-10 14:34:315518 return false;
5519
[email protected]37567b432014-02-12 01:12:225520 if (delegate_)
5521 return delegate_->CanOverscrollContent();
5522
5523 return false;
5524}
5525
Carlos Caballero1215f882019-10-29 15:58:435526void WebContentsImpl::OnThemeColorChanged(RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375527 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnThemeColorChanged",
5528 "render_view_host", source);
Carlos Caballero1215f882019-10-29 15:58:435529 if (source->did_first_visually_non_empty_paint() &&
5530 last_sent_theme_color_ != source->theme_color()) {
Alexander Timin90c20c32020-08-12 15:28:325531 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5532 observer->DidChangeThemeColor();
5533 });
Matt Jones36fc2882020-08-25 14:25:125534 last_sent_theme_color_ = source->theme_color();
peter90afaba2015-06-01 12:05:295535 }
[email protected]e7104762014-06-20 19:17:255536}
5537
Alan Cutterd73a15d92020-08-21 07:12:455538void WebContentsImpl::OnBackgroundColorChanged(RenderViewHostImpl* source) {
5539 if (source->did_first_visually_non_empty_paint() &&
5540 last_sent_background_color_ != source->background_color()) {
5541 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5542 observer->OnBackgroundColorChanged();
5543 });
5544 last_sent_background_color_ = source->background_color();
5545 }
5546}
5547
Gyuyoung Kim1905f7c2020-05-02 00:00:245548void WebContentsImpl::DidLoadResourceFromMemoryCache(
nicka0ac8382016-12-15 23:59:235549 RenderFrameHostImpl* source,
[email protected]724159a2010-12-30 01:11:185550 const GURL& url,
[email protected]70435962011-08-02 20:13:285551 const std::string& http_method,
[email protected]6d6cfb3a2012-05-23 22:53:185552 const std::string& mime_type,
Kinuko Yasuda433f710a2020-02-14 02:11:585553 network::mojom::RequestDestination request_destination) {
Alexander Timin5fdeff22020-09-08 09:20:375554 OPTIONAL_TRACE_EVENT2(
5555 "content", "WebContentsImpl::DidLoadResourceFromMemoryCache",
5556 "render_frame_host", base::trace_event::ToTracedValue(source), "url",
5557 base::trace_event::ValueToString(url));
Alexander Timin90c20c32020-08-12 15:28:325558 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5559 observer->DidLoadResourceFromMemoryCache(url, mime_type,
5560 request_destination);
5561 });
[email protected]b0f724c2013-09-05 04:21:135562
Steven Bingler674fb0822018-12-12 18:04:525563 if (url.is_valid() && url.SchemeIsHTTPOrHTTPS()) {
nicka0ac8382016-12-15 23:59:235564 StoragePartition* partition = source->GetProcess()->GetStoragePartition();
John Abd-El-Malekf4fe9d82019-07-31 04:05:595565 partition->GetNetworkContext()->NotifyExternalCacheHit(
Matt Menke2a33dee2019-12-02 17:01:545566 url, http_method, source->GetNetworkIsolationKey());
[email protected]8bfc8272013-09-09 20:10:535567 }
[email protected]724159a2010-12-30 01:11:185568}
5569
carloskd9d97942017-02-16 08:58:095570void WebContentsImpl::DidDisplayInsecureContent() {
Alexander Timin5fdeff22020-09-08 09:20:375571 OPTIONAL_TRACE_EVENT0("content",
5572 "WebContentsImpl::DidDisplayInsecureContent");
estarkc2273502016-10-12 22:03:025573 controller_.ssl_manager()->DidDisplayMixedContent();
[email protected]724159a2010-12-30 01:11:185574}
5575
Dave Tapuskaa657d872019-10-21 20:23:215576void WebContentsImpl::DidContainInsecureFormAction() {
Alexander Timin5fdeff22020-09-08 09:20:375577 OPTIONAL_TRACE_EVENT0("content",
5578 "WebContentsImpl::DidContainInsecureFormAction");
elawrenceb2ac2a232017-03-27 21:46:255579 controller_.ssl_manager()->DidContainInsecureFormAction();
5580}
5581
Julie Jeongeun Kim0b103492020-01-29 05:30:515582void WebContentsImpl::DocumentAvailableInMainFrame() {
Alexander Timin5fdeff22020-09-08 09:20:375583 OPTIONAL_TRACE_EVENT0("content",
5584 "WebContentsImpl::DocumentAvailableInMainFrame");
Alexander Timin90c20c32020-08-12 15:28:325585 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5586 observer->DocumentAvailableInMainFrame();
5587 });
Julie Jeongeun Kim0b103492020-01-29 05:30:515588}
5589
nicka0ac8382016-12-15 23:59:235590void WebContentsImpl::OnDidRunInsecureContent(RenderFrameHostImpl* source,
5591 const GURL& security_origin,
estark910b4572015-12-09 20:55:415592 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375593 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidRunInsecureContent",
5594 "render_frame_host",
5595 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:235596 // TODO(nick, estark): Should we call FilterURL using |source|'s process on
5597 // these parameters? |target_url| seems unused, except for a log message. And
5598 // |security_origin| might be replaceable with the origin of the main frame.
carloskd9d97942017-02-16 08:58:095599 DidRunInsecureContent(security_origin, target_url);
5600}
5601
5602void WebContentsImpl::DidRunInsecureContent(const GURL& security_origin,
5603 const GURL& target_url) {
Alexander Timin5fdeff22020-09-08 09:20:375604 OPTIONAL_TRACE_EVENT2(
5605 "content", "WebContentsImpl::DidRunInsecureContent", "security_origin",
5606 base::trace_event::ValueToString(security_origin), "target_url",
5607 base::trace_event::ValueToString(target_url));
[email protected]9450c462013-11-23 01:22:585608 LOG(WARNING) << security_origin << " ran insecure content from "
5609 << target_url.possibly_invalid_spec();
[email protected]e6e30ac2014-01-13 21:24:395610 RecordAction(base::UserMetricsAction("SSL.RanInsecureContent"));
estark910b4572015-12-09 20:55:415611 if (base::EndsWith(security_origin.spec(), kDotGoogleDotCom,
brettwa7ff1b292015-07-16 17:49:295612 base::CompareCase::INSENSITIVE_ASCII))
[email protected]e6e30ac2014-01-13 21:24:395613 RecordAction(base::UserMetricsAction("SSL.RanInsecureContentGoogle"));
estarkc2273502016-10-12 22:03:025614 controller_.ssl_manager()->DidRunMixedContent(security_origin);
[email protected]724159a2010-12-30 01:11:185615}
5616
carloskd9d97942017-02-16 08:58:095617void WebContentsImpl::PassiveInsecureContentFound(const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375618 OPTIONAL_TRACE_EVENT1(
5619 "content", "WebContentsImpl::PassiveInsecureContentFound", "resource_url",
5620 base::trace_event::ValueToString(resource_url));
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365621 if (delegate_) {
5622 delegate_->PassiveInsecureContentFound(resource_url);
5623 }
carloskd9d97942017-02-16 08:58:095624}
5625
5626bool WebContentsImpl::ShouldAllowRunningInsecureContent(
carloskd9d97942017-02-16 08:58:095627 bool allowed_per_prefs,
5628 const url::Origin& origin,
5629 const GURL& resource_url) {
Alexander Timin5fdeff22020-09-08 09:20:375630 OPTIONAL_TRACE_EVENT0("content",
5631 "WebContentsImpl::ShouldAllowRunningInsecureContent");
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365632 if (delegate_) {
Carlos IL29294a62020-05-15 00:21:165633 return delegate_->ShouldAllowRunningInsecureContent(this, allowed_per_prefs,
5634 origin, resource_url);
Sergey Kuznetsov3ebc01b2018-02-01 04:57:365635 }
5636
5637 return allowed_per_prefs;
carloskd9d97942017-02-16 08:58:095638}
5639
Lukasz Anforowicze1b954d92017-10-30 21:28:065640void WebContentsImpl::ViewSource(RenderFrameHostImpl* frame) {
Alexander Timin5fdeff22020-09-08 09:20:375641 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ViewSource",
5642 "render_frame_host",
5643 base::trace_event::ToTracedValue(frame));
Lukasz Anforowicze1b954d92017-10-30 21:28:065644 DCHECK_EQ(this, WebContents::FromRenderFrameHost(frame));
5645
5646 // Don't do anything if there is no |delegate_| that could accept and show the
5647 // new WebContents containing the view-source.
5648 if (!delegate_)
5649 return;
5650
5651 // Use the last committed entry, since the pending entry hasn't loaded yet and
5652 // won't be copied into the cloned tab.
5653 NavigationEntryImpl* last_committed_entry =
Fergal Daly09d6c762020-05-29 02:05:185654 GetController().GetLastCommittedEntry();
Lukasz Anforowicze1b954d92017-10-30 21:28:065655 if (!last_committed_entry)
5656 return;
5657
5658 FrameNavigationEntry* frame_entry =
5659 last_committed_entry->GetFrameEntry(frame->frame_tree_node());
5660 if (!frame_entry)
5661 return;
5662
5663 // Any new WebContents opened while this WebContents is in fullscreen can be
5664 // used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:455665 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5666 // The new view source contents will be independent of this contents, so
5667 // release the fullscreen block.
5668 fullscreen_block.RunAndReset();
Lukasz Anforowicze1b954d92017-10-30 21:28:065669
5670 // We intentionally don't share the SiteInstance with the original frame so
5671 // that view source has a consistent process model and always ends up in a new
5672 // process (https://crbug.com/699493).
5673 scoped_refptr<SiteInstanceImpl> site_instance_for_view_source = nullptr;
Lukasz Anforowicz435bcb582019-07-12 20:50:065674 // Referrer and initiator are not important, because view-source should not
5675 // hit the network, but should be served from the cache instead.
Lukasz Anforowicze1b954d92017-10-30 21:28:065676 Referrer referrer_for_view_source;
Lukasz Anforowicz435bcb582019-07-12 20:50:065677 base::Optional<url::Origin> initiator_for_view_source = base::nullopt;
Lukasz Anforowicze1b954d92017-10-30 21:28:065678 // Do not restore title, derive it from the url.
5679 base::string16 title_for_view_source;
5680 auto navigation_entry = std::make_unique<NavigationEntryImpl>(
5681 site_instance_for_view_source, frame_entry->url(),
Lukasz Anforowicz435bcb582019-07-12 20:50:065682 referrer_for_view_source, initiator_for_view_source,
5683 title_for_view_source, ui::PAGE_TRANSITION_LINK,
Marijn Kruisselbrink7a0d5e182018-05-24 22:55:095684 /* is_renderer_initiated = */ false,
5685 /* blob_url_loader_factory = */ nullptr);
Joel Hockey891e88062020-04-30 05:38:445686 const GURL url(content::kViewSourceScheme + std::string(":") +
5687 frame_entry->url().spec());
5688 navigation_entry->SetVirtualURL(url);
Matt Menkea56c5992020-04-10 20:53:565689 navigation_entry->set_isolation_info(
5690 frame->GetIsolationInfoForSubresources());
Yao Xiaof68f57d2019-10-03 04:20:055691
Lukasz Anforowicze1b954d92017-10-30 21:28:065692 // Do not restore scroller position.
5693 // TODO(creis, lukasza, arthursonzogni): Do not reuse the original PageState,
5694 // but start from a new one and only copy the needed data.
5695 const PageState& new_page_state =
5696 frame_entry->page_state().RemoveScrollOffset();
5697
5698 scoped_refptr<FrameNavigationEntry> new_frame_entry =
5699 navigation_entry->root_node()->frame_entry;
5700 new_frame_entry->set_method(frame_entry->method());
5701 new_frame_entry->SetPageState(new_page_state);
5702
5703 // Create a new WebContents, which is used to display the source code.
erikchenbee5c9622018-04-27 19:30:255704 std::unique_ptr<WebContents> view_source_contents =
Erik Chenbb8e738e2018-04-28 14:10:435705 Create(CreateParams(GetBrowserContext()));
Lukasz Anforowicze1b954d92017-10-30 21:28:065706
5707 // Restore the previously created NavigationEntry.
5708 std::vector<std::unique_ptr<NavigationEntry>> navigation_entries;
5709 navigation_entries.push_back(std::move(navigation_entry));
5710 view_source_contents->GetController().Restore(0, RestoreType::CURRENT_SESSION,
5711 &navigation_entries);
5712
5713 // Add |view_source_contents| as a new tab.
5714 gfx::Rect initial_rect;
5715 constexpr bool kUserGesture = true;
5716 bool ignored_was_blocked;
Joel Hockey891e88062020-04-30 05:38:445717 delegate_->AddNewContents(this, std::move(view_source_contents), url,
Lukasz Anforowicze1b954d92017-10-30 21:28:065718 WindowOpenDisposition::NEW_FOREGROUND_TAB,
5719 initial_rect, kUserGesture, &ignored_was_blocked);
5720 // Note that the |delegate_| could have deleted |view_source_contents| during
5721 // AddNewContents method call.
5722}
5723
Lukasz Anforowiczd334bba2020-02-10 23:32:555724void WebContentsImpl::SubresourceResponseStarted(const GURL& url,
5725 net::CertStatus cert_status) {
Alexander Timin5fdeff22020-09-08 09:20:375726 OPTIONAL_TRACE_EVENT1("content",
5727 "WebContentsImpl::SubresourceResponseStarted", "url",
5728 base::trace_event::ValueToString(url));
Lukasz Anforowiczd334bba2020-02-10 23:32:555729 controller_.ssl_manager()->DidStartResourceResponse(url, cert_status);
Jay Civellid5904f02018-03-23 19:43:575730 SetNotWaitingForResponse();
5731}
5732
Jay Civelli116683f2018-03-27 19:56:235733void WebContentsImpl::ResourceLoadComplete(
Jay Civelli52a63302018-04-30 22:39:555734 RenderFrameHost* render_frame_host,
Clark DuVall36164bd2018-08-09 22:49:085735 const GlobalRequestID& request_id,
Minggang Wangee5af392020-02-05 02:55:285736 blink::mojom::ResourceLoadInfoPtr resource_load_info) {
Alexander Timin5fdeff22020-09-08 09:20:375737 OPTIONAL_TRACE_EVENT2(
5738 "content", "WebContentsImpl::ResourceLoadComplete", "render_frame_host",
5739 base::trace_event::ToTracedValue(render_frame_host), "request_id",
5740 base::trace_event::TracedValue::Build(
5741 {{"child_id", request_id.child_id},
5742 {"request_id", request_id.request_id}}));
Alexander Timin90c20c32020-08-12 15:28:325743 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5744 observer->ResourceLoadComplete(render_frame_host, request_id,
5745 *resource_load_info);
5746 });
John Abd-El-Malekd4882642017-12-04 21:45:195747}
5748
Rakina Zata Amni347b70902020-07-22 10:49:045749const WebPreferences& WebContentsImpl::GetOrCreateWebPreferences() {
Alexander Timin5fdeff22020-09-08 09:20:375750 OPTIONAL_TRACE_EVENT0("content",
5751 "WebContentsImpl::GetOrCreateWebPreferences");
Rakina Zata Amni347b70902020-07-22 10:49:045752 // Compute WebPreferences based on the current state if it's null.
5753 if (!web_preferences_)
Rakina Zata Amni4029b6d2020-07-28 02:36:205754 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045755 return *web_preferences_.get();
5756}
5757
5758bool WebContentsImpl::IsWebPreferencesSet() const {
5759 return web_preferences_.get();
5760}
5761
5762void WebContentsImpl::SetWebPreferences(const WebPreferences& prefs) {
Alexander Timin5fdeff22020-09-08 09:20:375763 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetWebPreferences");
Rakina Zata Amni347b70902020-07-22 10:49:045764 web_preferences_ = std::make_unique<WebPreferences>(prefs);
5765 // Get all the RenderViewHosts (except the ones for currently back-forward
5766 // cached pages), and make them send the current WebPreferences
5767 // to the renderer. WebPreferences updates for back-forward cached pages will
5768 // be sent when we restore those pages from the back-forward cache.
5769 for (auto& rvh : frame_tree_.render_view_hosts()) {
5770 rvh.second->SendWebPreferencesToRenderer();
5771 }
5772}
5773
5774void WebContentsImpl::RecomputeWebPreferencesSlow() {
Alexander Timin5fdeff22020-09-08 09:20:375775 OPTIONAL_TRACE_EVENT0("content",
5776 "WebContentsImpl::RecomputeWebPreferencesSlow");
Rakina Zata Amni4029b6d2020-07-28 02:36:205777 // OnWebPreferencesChanged is a no-op when this is true.
5778 if (updating_web_preferences_)
5779 return;
Rakina Zata Amni347b70902020-07-22 10:49:045780 // Resets |web_preferences_| so that we won't have any cached value for slow
5781 // attributes (which won't get recomputed if we have pre-existing values for
5782 // them).
5783 web_preferences_.reset();
Rakina Zata Amni4029b6d2020-07-28 02:36:205784 OnWebPreferencesChanged();
Rakina Zata Amni347b70902020-07-22 10:49:045785}
5786
Wei Li5bb659742018-02-14 03:07:585787void WebContentsImpl::PrintCrossProcessSubframe(
5788 const gfx::Rect& rect,
5789 int document_cookie,
5790 RenderFrameHost* subframe_host) {
Alexander Timin5fdeff22020-09-08 09:20:375791 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::PrintCrossProcessSubframe",
5792 "subframe",
5793 base::trace_event::ToTracedValue(subframe_host));
Wei Li5c0b4d12018-03-22 15:05:225794 auto* outer_contents = GetOuterWebContents();
5795 if (outer_contents) {
5796 // When an extension or app page is printed, the content should be
5797 // composited with outer content, so the outer contents should handle the
5798 // print request.
5799 outer_contents->PrintCrossProcessSubframe(rect, document_cookie,
5800 subframe_host);
5801 return;
5802 }
5803
Wei Li5bb659742018-02-14 03:07:585804 // If there is no delegate such as in tests or during deletion, do nothing.
5805 if (!delegate_)
5806 return;
5807
5808 delegate_->PrintCrossProcessSubframe(this, rect, document_cookie,
5809 subframe_host);
5810}
5811
ckitagawa8695799b2020-02-05 16:08:495812void WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe(
5813 const gfx::Rect& rect,
5814 const base::UnguessableToken& guid,
5815 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375816 OPTIONAL_TRACE_EVENT1(
5817 "content", "WebContentsImpl::CapturePaintPreviewOfCrossProcessSubframe",
5818 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
ckitagawa8695799b2020-02-05 16:08:495819 if (!delegate_)
5820 return;
ckitagawac43ac982020-07-07 17:41:175821 delegate_->CapturePaintPreviewOfSubframe(this, rect, guid, render_frame_host);
ckitagawa8695799b2020-02-05 16:08:495822}
5823
rob.buis300b0872017-03-10 20:43:585824#if defined(OS_ANDROID)
5825base::android::ScopedJavaLocalRef<jobject>
5826WebContentsImpl::GetJavaRenderFrameHostDelegate() {
5827 return GetJavaWebContents();
5828}
5829#endif
5830
Hiroki Nakagawa39d1bbe2020-07-14 16:15:525831void WebContentsImpl::OnDidDisplayContentWithCertificateErrors() {
Alexander Timin5fdeff22020-09-08 09:20:375832 OPTIONAL_TRACE_EVENT0(
5833 "content", "WebContentsImpl::OnDidDisplayContentWithCertificateErrors");
estarkc2273502016-10-12 22:03:025834 controller_.ssl_manager()->DidDisplayContentWithCertErrors();
estark910b4572015-12-09 20:55:415835}
5836
5837void WebContentsImpl::OnDidRunContentWithCertificateErrors(
Zhuoyu Qian4353f7f2018-01-08 05:33:005838 RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:375839 OPTIONAL_TRACE_EVENT1(
5840 "content", "WebContentsImpl::OnDidRunContentWithCertificateErrors",
5841 "render_frame_host", base::trace_event::ToTracedValue(source));
Emily Starkabbdd662020-06-05 02:40:135842 // For RenderFrameHosts that are inactive and going to be discarded, we can
5843 // disregard this message; there's no need to update the UI if the UI will
5844 // never be shown again.
5845 //
5846 // We still process this message for speculative RenderFrameHosts. This can
5847 // happen when a subframe's main resource has a certificate error. The
5848 // currently committed navigation entry will get marked as having run insecure
5849 // content and that will carry over to the navigation entry for the
5850 // speculative RFH when it commits.
5851 if (source->lifecycle_state() !=
5852 RenderFrameHostImpl::LifecycleState::kSpeculative &&
5853 source->IsInactiveAndDisallowReactivation()) {
estarkaeda1422016-05-10 02:31:125854 return;
Emily Starkabbdd662020-06-05 02:40:135855 }
estarkcd2e30c2016-08-12 06:51:155856 controller_.ssl_manager()->DidRunContentWithCertErrors(
Emily Starkabbdd662020-06-05 02:40:135857 source->GetMainFrame()->GetLastCommittedOrigin().GetURL());
estark910b4572015-12-09 20:55:415858}
5859
Kouhei Ueno97e0990d2019-09-25 02:57:275860void WebContentsImpl::DOMContentLoaded(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:375861 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DOMContentLoaded",
5862 "render_frame_host",
5863 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:325864 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5865 observer->DOMContentLoaded(render_frame_host);
5866 });
[email protected]724159a2010-12-30 01:11:185867}
5868
Gyuyoung Kim525e0c5d2020-03-09 15:04:195869void WebContentsImpl::OnDidFinishLoad(RenderFrameHost* render_frame_host,
nicka0ac8382016-12-15 23:59:235870 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:375871 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnDidFinishLoad",
5872 "render_frame_host",
5873 base::trace_event::ToTracedValue(render_frame_host),
5874 "url", base::trace_event::ValueToString(url));
[email protected]8b3af1e2014-01-24 13:29:125875 GURL validated_url(url);
Gyuyoung Kim525e0c5d2020-03-09 15:04:195876 render_frame_host->GetProcess()->FilterURL(false, &validated_url);
[email protected]028053d42014-03-05 22:20:375877
Alexander Timin90c20c32020-08-12 15:28:325878 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5879 observer->DidFinishLoad(render_frame_host, validated_url);
5880 });
yilkal172da772019-11-06 22:49:075881 size_t tree_size = frame_tree_.root()->GetFrameTreeSize();
5882 if (max_loaded_frame_count_ < tree_size)
5883 max_loaded_frame_count_ = tree_size;
5884
Gyuyoung Kim525e0c5d2020-03-09 15:04:195885 if (!render_frame_host->GetParent())
yilkal172da772019-11-06 22:49:075886 UMA_HISTOGRAM_COUNTS_1000("Navigation.MainFrame.FrameCount", tree_size);
[email protected]1a55c5be2011-11-29 11:36:315887}
5888
Dave Tapuska549baab2019-03-19 15:52:405889void WebContentsImpl::OnGoToEntryAtOffset(RenderFrameHostImpl* source,
Julie Jeongeun Kim144f8192020-01-18 06:59:035890 int32_t offset,
Dave Tapuska043b94a2019-09-10 14:14:355891 bool has_user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375892 OPTIONAL_TRACE_EVENT2(
5893 "content", "WebContentsImpl::OnGoToEntryAtOffset", "render_frame_host",
5894 base::trace_event::ToTracedValue(source), "offset", offset);
Arthur Sonzognia7d715a2018-09-20 16:11:135895 // Non-user initiated navigations coming from the renderer should be ignored
5896 // if there is an ongoing browser-initiated navigation.
5897 // See https://crbug.com/879965.
5898 // TODO(arthursonzogni): See if this should check for ongoing navigations in
5899 // the frame(s) affected by the session history navigation, rather than just
5900 // the main frame.
Kevin McNee96851e12020-07-16 03:43:225901 if (Navigator::ShouldIgnoreIncomingRendererRequest(
5902 frame_tree_.root()->navigation_request(), has_user_gesture))
5903 return;
Arthur Sonzognia7d715a2018-09-20 16:11:135904
nicka0ac8382016-12-15 23:59:235905 // All frames are allowed to navigate the global history.
Dave Tapuska8bfd84c2019-03-26 20:47:165906 if (!delegate_ || delegate_->OnGoToEntryOffset(offset)) {
arthursonzognib93a4472020-04-10 07:38:005907 if (source->IsSandboxed(network::mojom::WebSandboxFlags::kTopNavigation)) {
Dave Tapuska8bfd84c2019-03-26 20:47:165908 // Keep track of whether this is a session history from a sandboxed iframe
5909 // with top level navigation disallowed.
5910 controller_.GoToOffsetInSandboxedFrame(offset,
5911 source->GetFrameTreeNodeId());
5912 } else {
5913 controller_.GoToOffset(offset);
5914 }
5915 }
[email protected]216813952011-05-19 22:21:265916}
5917
Dave Tapuska4c02911b2020-02-14 22:52:075918void WebContentsImpl::OnPageScaleFactorChanged(RenderFrameHostImpl* source,
nicka0ac8382016-12-15 23:59:235919 float page_scale_factor) {
Alexander Timin5fdeff22020-09-08 09:20:375920 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnPageScaleFactorChanged",
5921 "render_frame_host",
5922 base::trace_event::ToTracedValue(source),
5923 "page_scale_factor", page_scale_factor);
mcnee336ea2c2017-05-23 22:50:595924#if !defined(OS_ANDROID)
5925 // While page scale factor is used on mobile, this PageScaleFactorIsOne logic
5926 // is only needed on desktop.
mcnee432e47d2015-11-09 19:37:465927 bool is_one = page_scale_factor == 1.f;
5928 if (is_one != page_scale_factor_is_one_) {
5929 page_scale_factor_is_one_ = is_one;
5930
5931 HostZoomMapImpl* host_zoom_map =
5932 static_cast<HostZoomMapImpl*>(HostZoomMap::GetForWebContents(this));
5933
nicka0ac8382016-12-15 23:59:235934 if (host_zoom_map) {
mcnee432e47d2015-11-09 19:37:465935 host_zoom_map->SetPageScaleFactorIsOneForView(
Dave Tapuska4c02911b2020-02-14 22:52:075936 source->GetProcess()->GetID(),
5937 source->GetRenderViewHost()->GetRoutingID(),
mcnee432e47d2015-11-09 19:37:465938 page_scale_factor_is_one_);
5939 }
5940 }
mcnee336ea2c2017-05-23 22:50:595941#endif // !defined(OS_ANDROID)
mcnee432e47d2015-11-09 19:37:465942
Alexander Timin90c20c32020-08-12 15:28:325943 observers_.ForEachObserver([&](WebContentsObserver* observer) {
5944 observer->OnPageScaleFactorChanged(page_scale_factor);
5945 });
mcnee432e47d2015-11-09 19:37:465946}
5947
W. James MacLean62198672019-06-04 16:46:105948void WebContentsImpl::OnTextAutosizerPageInfoChanged(
Henrique Ferreiroba535472020-04-21 11:38:365949 RenderFrameHostImpl* source,
5950 blink::mojom::TextAutosizerPageInfoPtr page_info) {
Alexander Timin5fdeff22020-09-08 09:20:375951 OPTIONAL_TRACE_EVENT1(
5952 "content", "WebContentsImpl::OnTextAutosizerPageInfoChanged",
5953 "render_frame_host", base::trace_event::ToTracedValue(source));
W. James MacLean62198672019-06-04 16:46:105954 // Keep a copy of |page_info| in case we create a new RenderView before
5955 // the next update.
Henrique Ferreiroba535472020-04-21 11:38:365956 text_autosizer_page_info_.main_frame_width = page_info->main_frame_width;
5957 text_autosizer_page_info_.main_frame_layout_width =
5958 page_info->main_frame_layout_width;
5959 text_autosizer_page_info_.device_scale_adjustment =
5960 page_info->device_scale_adjustment;
Antonio Gomesda7e03d2020-08-05 15:03:085961
5962 auto remote_frames_broadcast_callback = base::BindRepeating(
5963 [](const blink::mojom::TextAutosizerPageInfo& page_info,
5964 RenderFrameProxyHost* proxy_host) {
5965 DCHECK(proxy_host);
5966 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
5967 page_info.Clone());
5968 },
5969 text_autosizer_page_info_);
5970
5971 frame_tree_.root()->render_manager()->ExecuteRemoteFramesBroadcastMethod(
5972 std::move(remote_frames_broadcast_callback), source->GetSiteInstance());
W. James MacLean62198672019-06-04 16:46:105973}
5974
Kent Tamura8c9e0562018-11-06 07:02:195975void WebContentsImpl::EnumerateDirectory(
5976 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:015977 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamura8c9e0562018-11-06 07:02:195978 const base::FilePath& directory_path) {
Alexander Timin5fdeff22020-09-08 09:20:375979 OPTIONAL_TRACE_EVENT2(
5980 "content", "WebContentsImpl::EnumerateDirectory", "render_frame_host",
5981 base::trace_event::ToTracedValue(render_frame_host), "directory_path",
5982 base::trace_event::ValueToString(directory_path));
Avi Drissman1a55a9d62020-03-10 18:56:455983 // Any explicit focusing of another window while this WebContents is in
5984 // fullscreen can be used to confuse the user, so drop fullscreen.
5985 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
5986 listener->SetFullscreenBlock(std::move(fullscreen_block));
5987
Kent Tamura8c9e0562018-11-06 07:02:195988 if (delegate_)
5989 delegate_->EnumerateDirectory(this, std::move(listener), directory_path);
5990 else
5991 listener->FileSelectionCanceled();
[email protected]3a29a6e2011-08-24 18:26:215992}
5993
Dave Tapuskaf9fc3122019-10-18 19:42:555994void WebContentsImpl::RegisterProtocolHandler(RenderFrameHostImpl* source,
5995 const std::string& protocol,
5996 const GURL& url,
5997 const base::string16& title,
5998 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:375999 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RegisterProtocolHandler",
6000 "render_frame_host",
6001 base::trace_event::ToTracedValue(source), "protocol",
6002 protocol);
nicka0ac8382016-12-15 23:59:236003 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]e5f2de02012-07-20 22:15:436004 if (!delegate_)
6005 return;
6006
Raymes Khoury58373df2019-08-06 06:29:206007 if (!AreValidRegisterProtocolHandlerArguments(
6008 protocol, url, source->GetLastCommittedOrigin())) {
6009 ReceivedBadMessage(source->GetProcess(),
6010 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]b9535422012-02-09 01:47:596011 return;
Raymes Khoury58373df2019-08-06 06:29:206012 }
[email protected]8f810632013-06-06 22:33:326013
Carlos Caballero8a6c6b72020-07-20 16:56:226014 delegate_->RegisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]7d189022011-08-25 22:54:206015}
6016
Dave Tapuskaf9fc3122019-10-18 19:42:556017void WebContentsImpl::UnregisterProtocolHandler(RenderFrameHostImpl* source,
6018 const std::string& protocol,
6019 const GURL& url,
6020 bool user_gesture) {
Alexander Timin5fdeff22020-09-08 09:20:376021 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UnregisterProtocolHandler",
6022 "render_frame_host",
6023 base::trace_event::ToTracedValue(source), "protocol",
6024 protocol);
nicka0ac8382016-12-15 23:59:236025 // TODO(nick): Do we need to apply FilterURL to |url|?
[email protected]f5273e52014-07-14 16:30:206026 if (!delegate_)
6027 return;
6028
Raymes Khoury58373df2019-08-06 06:29:206029 if (!AreValidRegisterProtocolHandlerArguments(
6030 protocol, url, source->GetLastCommittedOrigin())) {
6031 ReceivedBadMessage(source->GetProcess(),
6032 bad_message::REGISTER_PROTOCOL_HANDLER_INVALID_URL);
[email protected]f5273e52014-07-14 16:30:206033 return;
Raymes Khoury58373df2019-08-06 06:29:206034 }
[email protected]f5273e52014-07-14 16:30:206035
Carlos Caballero8a6c6b72020-07-20 16:56:226036 delegate_->UnregisterProtocolHandler(source, protocol, url, user_gesture);
[email protected]f5273e52014-07-14 16:30:206037}
6038
Marijn Kruisselbrink7f519672019-02-05 19:12:506039void WebContentsImpl::OnAppCacheAccessed(const GURL& manifest_url,
[email protected]b172aee2012-04-10 17:05:266040 bool blocked_by_policy) {
Alexander Timin5fdeff22020-09-08 09:20:376041 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnAppCacheAccessed");
nicka0ac8382016-12-15 23:59:236042 // TODO(nick): Should we consider |source| here? Should we call FilterURL on
6043 // |manifest_url|?
6044
[email protected]7fc4bbb2011-09-08 21:23:106045 // Notify observers about navigation.
Alexander Timin90c20c32020-08-12 15:28:326046 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6047 observer->AppCacheAccessed(manifest_url, blocked_by_policy);
6048 });
[email protected]7fc4bbb2011-09-08 21:23:106049}
6050
Gyuyoung Kimc5f4ac12020-05-08 10:59:396051void WebContentsImpl::DomOperationResponse(const std::string& json_string) {
Alexander Timin5fdeff22020-09-08 09:20:376052 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DomOperationResponse",
6053 "json_string", json_string);
6054
Gyuyoung Kimc5f4ac12020-05-08 10:59:396055 // TODO(lukasza): The notification below should probably indicate which
6056 // RenderFrameHostImpl the message is coming from. This can enable tests to
6057 // talk to 2 frames at the same time, without being confused which frame a
6058 // given response comes from. See also a corresponding TODO in the
6059 // ExecuteScriptHelper in //content/public/test/browser_test_utils.cc
6060 NotificationService::current()->Notify(
6061 NOTIFICATION_DOM_OPERATION_RESPONSE, Source<WebContents>(this),
6062 Details<const std::string>(&json_string));
6063}
6064
Gyuyoung Kim4c50517842020-06-04 17:50:446065void WebContentsImpl::SavableResourceLinksResponse(
6066 RenderFrameHostImpl* source,
6067 const std::vector<GURL>& resources_list,
6068 blink::mojom::ReferrerPtr referrer,
6069 const std::vector<blink::mojom::SavableSubframePtr>& subframes) {
Alexander Timin5fdeff22020-09-08 09:20:376070 OPTIONAL_TRACE_EVENT1(
6071 "content", "WebContentsImpl::SavableResourceLinksResponse",
6072 "render_frame_host", base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:446073 save_package_->SavableResourceLinksResponse(source, resources_list,
6074 std::move(referrer), subframes);
6075}
6076
6077void WebContentsImpl::SavableResourceLinksError(RenderFrameHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376078 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SavableResourceLinksError",
6079 "render_frame_host",
6080 base::trace_event::ToTracedValue(source));
Gyuyoung Kim4c50517842020-06-04 17:50:446081 save_package_->SavableResourceLinksError(source);
6082}
6083
Alexander Timin17edc742020-04-23 18:22:186084void WebContentsImpl::OnServiceWorkerAccessed(
6085 RenderFrameHost* render_frame_host,
6086 const GURL& scope,
6087 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:376088 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
6089 "render_frame_host",
6090 base::trace_event::ToTracedValue(render_frame_host),
6091 "scope", base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:326092 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6093 observer->OnServiceWorkerAccessed(render_frame_host, scope, allowed);
6094 });
Alexander Timin17edc742020-04-23 18:22:186095}
6096
6097void WebContentsImpl::OnServiceWorkerAccessed(
6098 NavigationHandle* navigation,
6099 const GURL& scope,
6100 AllowServiceWorkerResult allowed) {
Alexander Timin5fdeff22020-09-08 09:20:376101 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnServiceWorkerAccessed",
6102 "navigation_handle", navigation, "scope",
6103 base::trace_event::ValueToString(scope));
Alexander Timin90c20c32020-08-12 15:28:326104 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6105 observer->OnServiceWorkerAccessed(navigation, scope, allowed);
6106 });
Alexander Timin17edc742020-04-23 18:22:186107}
6108
Miyoung Shincb6475a2019-11-09 10:49:456109void WebContentsImpl::OnColorChooserFactoryReceiver(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206110 mojo::PendingReceiver<blink::mojom::ColorChooserFactory> receiver) {
Alexander Timin5fdeff22020-09-08 09:20:376111 OPTIONAL_TRACE_EVENT0("content",
6112 "WebContentsImpl::OnColorChooserFactoryReceiver");
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206113 color_chooser_factory_receivers_.Add(this, std::move(receiver));
Joel Hockey85b379d2017-12-11 10:42:136114}
6115
6116void WebContentsImpl::OpenColorChooser(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206117 mojo::PendingReceiver<blink::mojom::ColorChooser> chooser_receiver,
6118 mojo::PendingRemote<blink::mojom::ColorChooserClient> client,
[email protected]8ed16472014-04-11 19:02:486119 SkColor color,
Joel Hockey163835a2017-12-20 11:51:576120 std::vector<blink::mojom::ColorSuggestionPtr> suggestions) {
Alexander Timin5fdeff22020-09-08 09:20:376121 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OpenColorChooser");
Joel Hockey85b379d2017-12-11 10:42:136122 content::ColorChooser* new_color_chooser =
Ivan Kotenkov2c0d2bb32017-11-01 15:41:286123 delegate_ ? delegate_->OpenColorChooser(this, color, suggestions)
6124 : nullptr;
[email protected]820957a2014-01-14 14:56:306125 if (!new_color_chooser)
[email protected]cb805452013-05-22 15:16:216126 return;
[email protected]8ed16472014-04-11 19:02:486127
Joel Hockey85b379d2017-12-11 10:42:136128 color_chooser_.reset();
6129 color_chooser_ = std::make_unique<ColorChooser>(
Julie Jeongeun Kim8e2879e2019-08-06 23:55:206130 new_color_chooser, std::move(chooser_receiver), std::move(client));
[email protected]da8543762012-03-20 08:52:206131}
6132
brettw4b461082016-11-19 18:55:166133#if BUILDFLAG(ENABLE_PLUGINS)
nicka0ac8382016-12-15 23:59:236134void WebContentsImpl::OnPepperInstanceCreated(RenderFrameHostImpl* source,
6135 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376136 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceCreated",
6137 "render_frame_host",
6138 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326139 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6140 observer->PepperInstanceCreated();
6141 });
nicka0ac8382016-12-15 23:59:236142 pepper_playback_observer_->PepperInstanceCreated(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006143}
6144
nicka0ac8382016-12-15 23:59:236145void WebContentsImpl::OnPepperInstanceDeleted(RenderFrameHostImpl* source,
6146 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376147 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperInstanceDeleted",
6148 "render_frame_host",
6149 base::trace_event::ToTracedValue(source));
Alexander Timin90c20c32020-08-12 15:28:326150 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6151 observer->PepperInstanceDeleted();
6152 });
nicka0ac8382016-12-15 23:59:236153 pepper_playback_observer_->PepperInstanceDeleted(source, pp_instance);
emaxxe70f5e12015-05-29 11:26:006154}
6155
nicka0ac8382016-12-15 23:59:236156void WebContentsImpl::OnPepperPluginHung(RenderFrameHostImpl* source,
6157 int plugin_child_id,
tommyclie6633ca72014-10-31 00:40:426158 const base::FilePath& path,
6159 bool is_hung) {
Alexander Timin5fdeff22020-09-08 09:20:376160 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperPluginHung",
6161 "render_frame_host",
6162 base::trace_event::ToTracedValue(source));
Steven Holte95922222018-09-14 20:06:236163 UMA_HISTOGRAM_COUNTS_1M("Pepper.PluginHung", 1);
tommyclie6633ca72014-10-31 00:40:426164
Alexander Timin90c20c32020-08-12 15:28:326165 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6166 observer->PluginHungStatusChanged(plugin_child_id, path, is_hung);
6167 });
tommyclie6633ca72014-10-31 00:40:426168}
6169
nicka0ac8382016-12-15 23:59:236170void WebContentsImpl::OnPepperStartsPlayback(RenderFrameHostImpl* source,
6171 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376172 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStartsPlayback",
6173 "render_frame_host",
6174 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236175 pepper_playback_observer_->PepperStartsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176176}
6177
nicka0ac8382016-12-15 23:59:236178void WebContentsImpl::OnPepperStopsPlayback(RenderFrameHostImpl* source,
6179 int32_t pp_instance) {
Alexander Timin5fdeff22020-09-08 09:20:376180 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPepperStopsPlayback",
6181 "render_frame_host",
6182 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236183 pepper_playback_observer_->PepperStopsPlayback(source, pp_instance);
zqzhang181047e62016-07-01 13:37:176184}
6185
nicka0ac8382016-12-15 23:59:236186void WebContentsImpl::OnPluginCrashed(RenderFrameHostImpl* source,
6187 const base::FilePath& plugin_path,
tommyclie6633ca72014-10-31 00:40:426188 base::ProcessId plugin_pid) {
Alexander Timin5fdeff22020-09-08 09:20:376189 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnPluginCrashed",
6190 "render_frame_host",
6191 base::trace_event::ToTracedValue(source));
nicka0ac8382016-12-15 23:59:236192 // TODO(nick): Eliminate the |plugin_pid| parameter, which can't be trusted,
Gyuyoung Kim26c7bc92020-04-29 00:53:006193 // and is only used by WebTestControlHost.
Alexander Timin90c20c32020-08-12 15:28:326194 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6195 observer->PluginCrashed(plugin_path, plugin_pid);
6196 });
tommyclie6633ca72014-10-31 00:40:426197}
6198
[email protected]d8415ad92012-08-23 14:40:506199void WebContentsImpl::OnRequestPpapiBrokerPermission(
nicka0ac8382016-12-15 23:59:236200 RenderViewHostImpl* source,
6201 int ppb_broker_route_id,
[email protected]d8415ad92012-08-23 14:40:506202 const GURL& url,
[email protected]2dec8ec2013-02-07 19:20:346203 const base::FilePath& plugin_path) {
Alexander Timin5fdeff22020-09-08 09:20:376204 OPTIONAL_TRACE_EVENT1("content",
6205 "WebContentsImpl::OnRequestPpapiBrokerPermission",
6206 "render_view_host", source);
Avi Drissman0a2a967d2019-04-01 19:33:526207 base::OnceCallback<void(bool)> permission_result_callback = base::BindOnce(
nicka0ac8382016-12-15 23:59:236208 &WebContentsImpl::SendPpapiBrokerPermissionResult, base::Unretained(this),
6209 source->GetProcess()->GetID(), ppb_broker_route_id);
[email protected]8c8fc292012-11-23 18:57:166210 if (!delegate_) {
Tommy Nyquist4b749d02018-03-20 21:46:296211 std::move(permission_result_callback).Run(false);
[email protected]8c8fc292012-11-23 18:57:166212 return;
[email protected]d8415ad92012-08-23 14:40:506213 }
6214
Avi Drissman0a2a967d2019-04-01 19:33:526215 delegate_->RequestPpapiBrokerPermission(
6216 this, url, plugin_path, std::move(permission_result_callback));
[email protected]d8415ad92012-08-23 14:40:506217}
6218
nicka0ac8382016-12-15 23:59:236219void WebContentsImpl::SendPpapiBrokerPermissionResult(int process_id,
6220 int ppb_broker_route_id,
6221 bool result) {
Alexander Timin5fdeff22020-09-08 09:20:376222 OPTIONAL_TRACE_EVENT2(
6223 "content", "WebContentsImpl::SendPpapiBrokerPermissionResult",
6224 "process_id", process_id, "ppb_broker_route_id", ppb_broker_route_id);
nicka0ac8382016-12-15 23:59:236225 RenderProcessHost* rph = RenderProcessHost::FromID(process_id);
6226 if (rph) {
6227 // TODO(nick): Convert this from ViewMsg_ to a Ppapi msg, since it
6228 // is not routed to a RenderView.
6229 rph->Send(
6230 new ViewMsg_PpapiBrokerPermissionResult(ppb_broker_route_id, result));
6231 }
[email protected]d8415ad92012-08-23 14:40:506232}
brettw4b461082016-11-19 18:55:166233#endif // BUILDFLAG(ENABLE_PLUGINS)
[email protected]19be7a62012-10-01 23:03:376234
Miyoung Shin5709ab02020-02-19 06:50:416235void WebContentsImpl::UpdateFaviconURL(
6236 RenderFrameHost* source,
6237 std::vector<blink::mojom::FaviconURLPtr> candidates) {
Alexander Timin5fdeff22020-09-08 09:20:376238 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateFaviconURL",
6239 "render_frame_host",
6240 base::trace_event::ToTracedValue(source));
lukasza178ff092017-06-07 23:39:506241 // Ignore favicons for non-main frame.
6242 if (source->GetParent()) {
6243 NOTREACHED();
6244 return;
6245 }
6246
pkotwiczf9bc20592015-04-21 18:57:066247 // We get updated favicon URLs after the page stops loading. If a cross-site
6248 // navigation occurs while a page is still loading, the initial page
6249 // may stop loading and send us updated favicon URLs after the navigation
6250 // for the new page has committed.
lukasza178ff092017-06-07 23:39:506251 if (!source->IsCurrent())
pkotwiczf9bc20592015-04-21 18:57:066252 return;
6253
Miyoung Shin5709ab02020-02-19 06:50:416254 favicon_urls_ = std::move(candidates);
Mounir Lamouri7b4a1f232019-12-23 16:32:106255
Alexander Timin90c20c32020-08-12 15:28:326256 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6257 observer->DidUpdateFaviconURL(source, favicon_urls_);
6258 });
[email protected]795c28972012-12-06 06:13:396259}
6260
qinmin72e8bd02016-10-21 19:35:376261void WebContentsImpl::SetIsOverlayContent(bool is_overlay_content) {
Alexander Timin5fdeff22020-09-08 09:20:376262 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetIsOverlayContent",
6263 "is_overlay_content", is_overlay_content);
qinmin72e8bd02016-10-21 19:35:376264 is_overlay_content_ = is_overlay_content;
6265}
6266
Albert J. Wongfb64e142018-10-16 01:10:456267void WebContentsImpl::DidFirstVisuallyNonEmptyPaint(
6268 RenderViewHostImpl* source) {
Alexander Timin5fdeff22020-09-08 09:20:376269 OPTIONAL_TRACE_EVENT1("content",
6270 "WebContentsImpl::DidFirstVisuallyNonEmptyPaint",
6271 "render_view_host", source);
nicka0ac8382016-12-15 23:59:236272 // TODO(nick): When this is ported to FrameHostMsg_, we should only listen if
6273 // |source| is the main frame.
Alexander Timin90c20c32020-08-12 15:28:326274 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6275 observer->DidFirstVisuallyNonEmptyPaint();
6276 });
Carlos Caballero1215f882019-10-29 15:58:436277 if (source->theme_color() != last_sent_theme_color_) {
yusufod41c5f92015-03-06 00:14:286278 // Theme color should have updated by now if there was one.
Alexander Timin90c20c32020-08-12 15:28:326279 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6280 observer->DidChangeThemeColor();
6281 });
Carlos Caballero1215f882019-10-29 15:58:436282 last_sent_theme_color_ = source->theme_color();
yusufod41c5f92015-03-06 00:14:286283 }
Alan Cutterd73a15d92020-08-21 07:12:456284
6285 if (source->background_color() != last_sent_background_color_) {
6286 // Background color should have updated by now if there was one.
6287 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6288 observer->OnBackgroundColorChanged();
6289 });
6290 last_sent_background_color_ = source->background_color();
6291 }
[email protected]9f268072013-11-07 00:02:156292}
[email protected]d9030b82013-07-19 08:26:066293
Kevin McNee068c3eb2020-04-03 18:24:196294bool WebContentsImpl::IsPortal() {
Adithya Srinivasan46b8a792019-02-01 14:47:236295 return portal();
6296}
6297
Kevin McNee94ea52f52020-06-23 17:42:066298WebContentsImpl* WebContentsImpl::GetPortalHostWebContents() {
6299 return portal() ? portal()->GetPortalHostContents() : nullptr;
6300}
6301
[email protected]17e286e2013-03-01 23:29:396302void WebContentsImpl::NotifyBeforeFormRepostWarningShow() {
Alexander Timin5fdeff22020-09-08 09:20:376303 OPTIONAL_TRACE_EVENT0("content",
6304 "WebContentsImpl::NotifyBeforeFormRepostWarningShow");
Alexander Timin90c20c32020-08-12 15:28:326305 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6306 observer->BeforeFormRepostWarningShow();
6307 });
[email protected]17e286e2013-03-01 23:29:396308}
6309
[email protected]ec6c05f2013-10-23 18:41:576310void WebContentsImpl::ActivateAndShowRepostFormWarningDialog() {
Alexander Timin5fdeff22020-09-08 09:20:376311 OPTIONAL_TRACE_EVENT0(
6312 "content", "WebContentsImpl::ActivateAndShowRepostFormWarningDialog");
[email protected]ec6c05f2013-10-23 18:41:576313 Activate();
6314 if (delegate_)
6315 delegate_->ShowRepostFormWarningDialog(this);
6316}
6317
[email protected]b4c84012014-04-28 19:51:106318bool WebContentsImpl::HasAccessedInitialDocument() {
6319 return has_accessed_initial_document_;
6320}
6321
afakhry6f0c1ec22016-07-14 13:55:136322void WebContentsImpl::UpdateTitleForEntry(NavigationEntry* entry,
[email protected]fcf75d42013-12-03 20:11:266323 const base::string16& title) {
Alexander Timin5fdeff22020-09-08 09:20:376324 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateTitleForEntry",
6325 "title", base::trace_event::ValueToString(title));
[email protected]fcf75d42013-12-03 20:11:266326 base::string16 final_title;
Avi Drissman93002212017-09-27 03:20:526327 base::TrimWhitespace(title, base::TRIM_ALL, &final_title);
[email protected]420ae012009-04-24 05:16:326328
[email protected]987fc3a2011-05-26 14:18:096329 // If a page is created via window.open and never navigated,
6330 // there will be no navigation entry. In this situation,
[email protected]73eb2602012-02-09 19:50:556331 // |page_title_when_no_navigation_entry_| will be used for page title.
[email protected]987fc3a2011-05-26 14:18:096332 if (entry) {
[email protected]36fc0392011-12-25 03:59:516333 if (final_title == entry->GetTitle())
afakhry6f0c1ec22016-07-14 13:55:136334 return; // Nothing changed, don't bother.
[email protected]420ae012009-04-24 05:16:326335
[email protected]36fc0392011-12-25 03:59:516336 entry->SetTitle(final_title);
Avi Drissman93002212017-09-27 03:20:526337
6338 // The title for display may differ from the title just set; grab it.
6339 final_title = entry->GetTitleForDisplay();
[email protected]987fc3a2011-05-26 14:18:096340 } else {
6341 if (page_title_when_no_navigation_entry_ == final_title)
afakhry6f0c1ec22016-07-14 13:55:136342 return; // Nothing changed, don't bother.
[email protected]987fc3a2011-05-26 14:18:096343
6344 page_title_when_no_navigation_entry_ = final_title;
6345 }
[email protected]420ae012009-04-24 05:16:326346
[email protected]420ae012009-04-24 05:16:326347 // Lastly, set the title for the view.
[email protected]790e2fd2011-09-21 20:28:236348 view_->SetPageTitle(final_title);
[email protected]420ae012009-04-24 05:16:326349
Alexander Timin90c20c32020-08-12 15:28:326350 observers_.ForEachObserver(
6351 [&](WebContentsObserver* observer) { observer->TitleWasSet(entry); });
afakhry6f0c1ec22016-07-14 13:55:136352 // Broadcast notifications when the UI should be updated.
6353 if (entry == controller_.GetEntryAtOffset(0))
6354 NotifyNavigationStateChanged(INVALIDATE_TYPE_TITLE);
[email protected]420ae012009-04-24 05:16:326355}
6356
fdegansa696e5112015-04-17 01:57:596357void WebContentsImpl::SendChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:376358 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SendChangeLoadProgress",
6359 "load_progress", frame_tree_.load_progress());
[email protected]960b0372014-05-19 18:01:006360 loading_last_progress_update_ = base::TimeTicks::Now();
Alexander Timin90c20c32020-08-12 15:28:326361 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6362 observer->LoadProgressChanged(frame_tree_.load_progress());
6363 });
[email protected]960b0372014-05-19 18:01:006364}
6365
6366void WebContentsImpl::ResetLoadProgressState() {
Alexander Timin5fdeff22020-09-08 09:20:376367 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ResetLoadProgressState");
fdegans1d16355162015-03-26 11:58:346368 frame_tree_.ResetLoadProgress();
[email protected]960b0372014-05-19 18:01:006369 loading_weak_factory_.InvalidateWeakPtrs();
6370 loading_last_progress_update_ = base::TimeTicks();
6371}
6372
clamy44e84ce2016-02-22 15:38:256373// Notifies the RenderWidgetHost instance about the fact that the page is
6374// loading, or done loading.
6375void WebContentsImpl::LoadingStateChanged(bool to_different_document,
clamy44e84ce2016-02-22 15:38:256376 LoadNotificationDetails* details) {
Nate Chapin22ea6592019-03-05 22:29:026377 if (is_being_destroyed_)
6378 return;
clamy44e84ce2016-02-22 15:38:256379
6380 bool is_loading = IsLoading();
6381
Alexander Timin5fdeff22020-09-08 09:20:376382 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::LoadingStateChanged",
6383 "is_loading", is_loading);
6384
clamy44e84ce2016-02-22 15:38:256385 if (!is_loading) {
6386 load_state_ = net::LoadStateWithParam(net::LOAD_STATE_IDLE,
6387 base::string16());
6388 load_state_host_.clear();
6389 upload_size_ = 0;
6390 upload_position_ = 0;
6391 }
6392
6393 GetRenderManager()->SetIsLoading(is_loading);
6394
6395 waiting_for_response_ = is_loading;
6396 is_load_to_different_document_ = to_different_document;
6397
6398 if (delegate_)
6399 delegate_->LoadingStateChanged(this, to_different_document);
6400 NotifyNavigationStateChanged(INVALIDATE_TYPE_LOAD);
6401
6402 std::string url = (details ? details->url.possibly_invalid_spec() : "NULL");
6403 if (is_loading) {
6404 TRACE_EVENT_ASYNC_BEGIN2("browser,navigation", "WebContentsImpl Loading",
6405 this, "URL", url, "Main FrameTreeNode id",
6406 GetFrameTree()->root()->frame_tree_node_id());
Alexander Timin90c20c32020-08-12 15:28:326407 observers_.ForEachObserver(
6408 [&](WebContentsObserver* observer) { observer->DidStartLoading(); });
clamy44e84ce2016-02-22 15:38:256409 } else {
6410 TRACE_EVENT_ASYNC_END1("browser,navigation", "WebContentsImpl Loading",
6411 this, "URL", url);
Alexander Timin90c20c32020-08-12 15:28:326412 observers_.ForEachObserver(
6413 [&](WebContentsObserver* observer) { observer->DidStopLoading(); });
clamy44e84ce2016-02-22 15:38:256414 }
6415
6416 // TODO(avi): Remove. http://crbug.com/170921
6417 int type = is_loading ? NOTIFICATION_LOAD_START : NOTIFICATION_LOAD_STOP;
6418 NotificationDetails det = NotificationService::NoDetails();
6419 if (details)
6420 det = Details<LoadNotificationDetails>(details);
6421 NotificationService::current()->Notify(
6422 type, Source<NavigationController>(&controller_), det);
6423}
6424
danakja0bce4c952020-05-12 20:40:286425void WebContentsImpl::NotifyViewSwapped(RenderViewHost* old_view,
6426 RenderViewHost* new_view) {
Alexander Timin5fdeff22020-09-08 09:20:376427 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::NotifyViewSwapped",
6428 "old_view", old_view, "new_view", new_view);
danakja0bce4c952020-05-12 20:40:286429 DCHECK_NE(old_view, new_view);
[email protected]420ae012009-04-24 05:16:326430 // After sending out a swap notification, we need to send a disconnect
6431 // notification so that clients that pick up a pointer to |this| can NULL the
6432 // pointer. See Bug 1230284.
6433 notify_disconnection_ = true;
Alexander Timin90c20c32020-08-12 15:28:326434 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6435 observer->RenderViewHostChanged(old_view, new_view);
6436 });
danakja0bce4c952020-05-12 20:40:286437 view_->RenderViewHostChanged(old_view, new_view);
Jinsuk Kimdc5284c22018-07-11 02:22:066438
Lucas Furukawa Gadanif9ea4fc2018-08-03 23:57:136439 // If this is an inner WebContents that has swapped views, we need to reattach
6440 // it to its outer WebContents.
6441 if (node_.outer_web_contents())
6442 ReattachToOuterWebContentsFrame();
6443
[email protected]7a846df2012-09-20 19:17:396444 // Ensure that the associated embedder gets cleared after a RenderViewHost
6445 // gets swapped, so we don't reuse the same embedder next time a
6446 // RenderViewHost is attached to this WebContents.
6447 RemoveBrowserPluginEmbedder();
[email protected]420ae012009-04-24 05:16:326448}
6449
danakja0bce4c952020-05-12 20:40:286450void WebContentsImpl::NotifyFrameSwapped(RenderFrameHost* old_frame,
6451 RenderFrameHost* new_frame,
Jinsuk Kim895b2c52018-07-03 06:49:166452 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:376453 TRACE_EVENT2("content", "WebContentsImpl::NotifyFrameSwapped", "old_frame",
6454 base::trace_event::ToTracedValue(old_frame), "new_frame",
6455 base::trace_event::ToTracedValue(new_frame));
Bo Liu168c8642017-08-28 18:26:026456#if defined(OS_ANDROID)
danakja0bce4c952020-05-12 20:40:286457 // Copy importance from |old_frame| if |new_frame| is a main frame.
6458 if (old_frame && !new_frame->GetParent()) {
6459 RenderWidgetHostImpl* old_widget =
6460 static_cast<RenderFrameHostImpl*>(old_frame)->GetRenderWidgetHost();
6461 RenderWidgetHostImpl* new_widget =
6462 static_cast<RenderFrameHostImpl*>(new_frame)->GetRenderWidgetHost();
6463 new_widget->SetImportance(old_widget->importance());
Bo Liu7c6779e92017-08-16 02:02:286464 }
Bo Liu168c8642017-08-28 18:26:026465#endif
Alexander Timin90c20c32020-08-12 15:28:326466 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6467 observer->RenderFrameHostChanged(old_frame, new_frame);
6468 });
[email protected]02d7b6e2014-06-24 21:01:506469}
6470
[email protected]da7a7182013-09-06 08:11:116471// TODO(avi): Remove this entire function because this notification is already
6472// covered by two observer functions. http://crbug.com/170921
[email protected]b172aee2012-04-10 17:05:266473void WebContentsImpl::NotifyDisconnected() {
Alexander Timin5fdeff22020-09-08 09:20:376474 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyDisconnected");
[email protected]420ae012009-04-24 05:16:326475 if (!notify_disconnection_)
6476 return;
6477
6478 notify_disconnection_ = false;
[email protected]8ff00d72012-10-23 19:12:216479 NotificationService::current()->Notify(
6480 NOTIFICATION_WEB_CONTENTS_DISCONNECTED,
6481 Source<WebContents>(this),
6482 NotificationService::NoDetails());
[email protected]420ae012009-04-24 05:16:326483}
6484
[email protected]cbb1ef592013-06-05 19:49:466485void WebContentsImpl::NotifyNavigationEntryCommitted(
6486 const LoadCommittedDetails& load_details) {
Alexander Timin5fdeff22020-09-08 09:20:376487 OPTIONAL_TRACE_EVENT0("content",
6488 "WebContentsImpl::NotifyNavigationEntryCommitted");
Alexander Timin90c20c32020-08-12 15:28:326489 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6490 observer->NavigationEntryCommitted(load_details);
6491 });
[email protected]cbb1ef592013-06-05 19:49:466492}
6493
Sam McNally5c087a32017-08-25 01:46:146494void WebContentsImpl::NotifyNavigationEntryChanged(
6495 const EntryChangedDetails& change_details) {
Alexander Timin5fdeff22020-09-08 09:20:376496 OPTIONAL_TRACE_EVENT0("content",
6497 "WebContentsImpl::NotifyNavigationEntryChanged");
Alexander Timin90c20c32020-08-12 15:28:326498 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6499 observer->NavigationEntryChanged(change_details);
6500 });
Sam McNally5c087a32017-08-25 01:46:146501}
6502
6503void WebContentsImpl::NotifyNavigationListPruned(
6504 const PrunedDetails& pruned_details) {
Alexander Timin5fdeff22020-09-08 09:20:376505 OPTIONAL_TRACE_EVENT0("content",
6506 "WebContentsImpl::NotifyNavigationListPruned");
Alexander Timin90c20c32020-08-12 15:28:326507 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6508 observer->NavigationListPruned(pruned_details);
6509 });
Sam McNally5c087a32017-08-25 01:46:146510}
6511
Christian Dullweber1af31e62018-02-22 11:49:486512void WebContentsImpl::NotifyNavigationEntriesDeleted() {
Alexander Timin5fdeff22020-09-08 09:20:376513 OPTIONAL_TRACE_EVENT0("content",
6514 "WebContentsImpl::NotifyNavigationEntriesDeleted");
Alexander Timin90c20c32020-08-12 15:28:326515 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6516 observer->NavigationEntriesDeleted();
6517 });
Christian Dullweber1af31e62018-02-22 11:49:486518}
6519
rockotf62002a2016-09-15 00:08:596520void WebContentsImpl::OnAssociatedInterfaceRequest(
6521 RenderFrameHost* render_frame_host,
6522 const std::string& interface_name,
6523 mojo::ScopedInterfaceEndpointHandle handle) {
Alexander Timin5fdeff22020-09-08 09:20:376524 OPTIONAL_TRACE_EVENT2(
6525 "content", "WebContentsImpl::OnAssociatedInterfaceRequest",
6526 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
6527 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:256528 auto it = receiver_sets_.find(interface_name);
6529 if (it != receiver_sets_.end())
6530 it->second->OnReceiverForFrame(render_frame_host, std::move(handle));
rockotf62002a2016-09-15 00:08:596531}
6532
Ben Goodger9e24929e2017-07-21 03:13:406533void WebContentsImpl::OnInterfaceRequest(
6534 RenderFrameHost* render_frame_host,
6535 const std::string& interface_name,
6536 mojo::ScopedMessagePipeHandle* interface_pipe) {
Alexander Timin5fdeff22020-09-08 09:20:376537 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnInterfaceRequest",
6538 "render_frame_host",
6539 base::trace_event::ToTracedValue(render_frame_host),
6540 "interface_name", interface_name);
Alexander Timin90c20c32020-08-12 15:28:326541 for (auto& observer : observers_.observer_list()) {
Ben Goodger9e24929e2017-07-21 03:13:406542 observer.OnInterfaceRequestFromFrame(render_frame_host, interface_name,
6543 interface_pipe);
6544 if (!interface_pipe->is_valid())
6545 break;
6546 }
6547}
6548
Varun Khaneja5da94302019-06-25 04:48:106549void WebContentsImpl::OnDidBlockNavigation(
6550 const GURL& blocked_url,
6551 const GURL& initiator_url,
Abhijeet Kandalkarde7348e2020-01-13 06:06:546552 blink::mojom::NavigationBlockedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:376553 OPTIONAL_TRACE_EVENT1(
6554 "content", "WebContentsImpl::OnDidBlockNavigation", "details",
6555 base::trace_event::TracedValue::Build(
6556 {{"blocked_url", base::trace_event::ValueToString(blocked_url)},
6557 {"initiator_url", base::trace_event::ValueToString(initiator_url)},
6558 {"reason", base::trace_event::ValueToString(reason)}}));
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406559 if (delegate_)
Varun Khaneja5da94302019-06-25 04:48:106560 delegate_->OnDidBlockNavigation(this, blocked_url, initiator_url, reason);
Nicolas Dossou-gbetebcab2472017-09-09 12:28:406561}
6562
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416563const GURL& WebContentsImpl::GetMainFrameLastCommittedURL() {
[email protected]c31a84802014-04-03 15:55:496564 return GetLastCommittedURL();
6565}
6566
[email protected]b849847b2013-12-10 21:57:586567void WebContentsImpl::RenderFrameCreated(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376568 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameCreated",
6569 "render_frame_host", render_frame_host);
Alexander Timin90c20c32020-08-12 15:28:326570 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6571 observer->RenderFrameCreated(render_frame_host);
6572 });
dmazzonif8a31042016-12-03 00:52:136573 UpdateAccessibilityModeOnFrame(render_frame_host);
clamy91b7abf2016-03-24 15:17:456574
Becca Hughesd11d6502018-07-31 17:01:286575 if (display_cutout_host_impl_)
6576 display_cutout_host_impl_->RenderFrameCreated(render_frame_host);
6577
clamy91b7abf2016-03-24 15:17:456578 if (!render_frame_host->IsRenderFrameLive() || render_frame_host->GetParent())
6579 return;
6580
6581 NavigationEntry* entry = controller_.GetPendingEntry();
6582 if (entry && entry->IsViewSourceMode()) {
6583 // Put the renderer in view source mode.
Dave Tapuska3c05e1c2019-11-27 18:34:186584 static_cast<RenderFrameHostImpl*>(render_frame_host)
6585 ->GetAssociatedLocalFrame()
6586 ->EnableViewSourceMode();
clamy91b7abf2016-03-24 15:17:456587 }
[email protected]b849847b2013-12-10 21:57:586588}
6589
6590void WebContentsImpl::RenderFrameDeleted(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:376591 TRACE_EVENT1("content", "WebContentsImpl::RenderFrameDeleted",
6592 "render_frame_host",
6593 base::trace_event::ToTracedValue(render_frame_host));
yilkal172da772019-11-06 22:49:076594 if (IsBeingDestroyed() && !render_frame_host->GetParent() &&
6595 first_navigation_completed_ &&
Hajime Hoshibbc509c2020-04-06 08:55:086596 !render_frame_host->IsInBackForwardCache()) {
yilkal796e89e2019-10-02 23:58:286597 // Main frame has been deleted because WebContents is being destroyed.
Rakina Zata Amni74627df2019-10-15 02:03:176598 // Note that we aren't recording this here when the main frame is in the
6599 // back-forward cache because that means we've actually already navigated
6600 // away from it (and we got to this point because the WebContents is
yilkal172da772019-11-06 22:49:076601 // deleted), which means |max_loaded_frame_count_| is already overwritten.
6602 // The |max_loaded_frame_count_| value will instead be recorded from within
6603 // |WebContentsImpl::DidFinishNavigation()|.
6604 RecordMaxFrameCountUMA(max_loaded_frame_count_);
yilkal796e89e2019-10-02 23:58:286605 }
6606
Alexander Timin90c20c32020-08-12 15:28:326607 observers_.ForEachObserver([&](WebContentsObserver* observer) {
6608 observer->RenderFrameDeleted(render_frame_host);
6609 });
zqzhang7b6f4f02016-12-07 22:10:226610#if BUILDFLAG(ENABLE_PLUGINS)
6611 pepper_playback_observer_->RenderFrameDeleted(render_frame_host);
6612#endif
Becca Hughesfd5d8f892018-06-14 18:23:366613
Becca Hughesd11d6502018-07-31 17:01:286614 if (display_cutout_host_impl_)
6615 display_cutout_host_impl_->RenderFrameDeleted(render_frame_host);
6616
Becca Hughesfd5d8f892018-06-14 18:23:366617 // Remove any fullscreen state that the frame has stored.
6618 FullscreenStateChanged(render_frame_host, false /* is_fullscreen */);
[email protected]b849847b2013-12-10 21:57:586619}
6620
[email protected]a09d53ce2014-01-31 00:46:426621void WebContentsImpl::ShowContextMenu(RenderFrameHost* render_frame_host,
6622 const ContextMenuParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376623 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowContextMenu",
6624 "render_frame_host",
6625 base::trace_event::ToTracedValue(render_frame_host));
avie9fd8722017-04-10 16:17:586626 // If a renderer fires off a second command to show a context menu before the
6627 // first context menu is closed, just ignore it. https://crbug.com/707534
ekaramadf6750aa2017-06-06 18:29:426628 if (showing_context_menu_)
avie9fd8722017-04-10 16:17:586629 return;
6630
[email protected]077e704b2014-05-23 19:24:106631 ContextMenuParams context_menu_params(params);
[email protected]a09d53ce2014-01-31 00:46:426632 // Allow WebContentsDelegates to handle the context menu operation first.
Joel Klinghed0ea22ea2019-02-20 22:04:226633 if (delegate_ &&
6634 delegate_->HandleContextMenu(render_frame_host, context_menu_params))
[email protected]a09d53ce2014-01-31 00:46:426635 return;
6636
[email protected]077e704b2014-05-23 19:24:106637 render_view_host_delegate_view_->ShowContextMenu(render_frame_host,
6638 context_menu_params);
[email protected]a09d53ce2014-01-31 00:46:426639}
6640
Avi Drissman4891b852018-09-25 18:12:586641namespace {
6642// Normalizes the line endings: \r\n -> \n, lone \r -> \n.
6643base::string16 NormalizeLineBreaks(const base::string16& source) {
6644 static const base::NoDestructor<base::string16> kReturnNewline(
6645 base::ASCIIToUTF16("\r\n"));
6646 static const base::NoDestructor<base::string16> kReturn(
6647 base::ASCIIToUTF16("\r"));
6648 static const base::NoDestructor<base::string16> kNewline(
6649 base::ASCIIToUTF16("\n"));
6650
6651 std::vector<base::StringPiece16> pieces;
6652
6653 for (const auto& rn_line : base::SplitStringPieceUsingSubstr(
6654 source, *kReturnNewline, base::KEEP_WHITESPACE,
6655 base::SPLIT_WANT_ALL)) {
6656 auto r_lines = base::SplitStringPieceUsingSubstr(
6657 rn_line, *kReturn, base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
6658 std::move(std::begin(r_lines), std::end(r_lines),
6659 std::back_inserter(pieces));
6660 }
6661
6662 return base::JoinString(pieces, *kNewline);
6663}
6664} // namespace
6665
Dave Tapuskacdf545cc2020-01-23 18:38:526666void WebContentsImpl::RunJavaScriptDialog(
6667 RenderFrameHost* render_frame_host,
6668 const base::string16& message,
6669 const base::string16& default_prompt,
6670 JavaScriptDialogType dialog_type,
6671 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376672 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunJavaScriptDialog",
6673 "render_frame_host",
6674 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman2ccbb402018-03-20 21:11:366675 // Ensure that if showing a dialog is the first thing that a page does, that
6676 // the contents of the previous page aren't shown behind it. This is required
6677 // because showing a dialog freezes the renderer, so no frames will be coming
6678 // from it. https://crbug.com/823353
6679 auto* render_widget_host_impl =
6680 static_cast<RenderFrameHostImpl*>(render_frame_host)
6681 ->GetRenderWidgetHost();
6682 if (render_widget_host_impl)
6683 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6684
avi0720b02e2017-06-13 03:22:136685 // Running a dialog causes an exit to webpage-initiated fullscreen.
6686 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456687 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136688
Avi Drissman1a55a9d62020-03-10 18:56:456689 auto callback =
6690 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6691 render_frame_host->GetProcess()->GetID(),
6692 render_frame_host->GetRoutingID(),
6693 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166694
Pavel Feldman3c1842b2017-08-02 05:00:166695 std::vector<protocol::PageHandler*> page_handlers =
6696 protocol::PageHandler::EnabledForWebContents(this);
6697
Pavel Feldmanfab3cb62017-10-05 01:02:016698 if (delegate_)
6699 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6700
Charlie Reis96077362019-07-04 00:34:046701 // While a JS message dialog is showing, defer commits in this WebContents.
6702 javascript_dialog_navigation_deferrer_ =
6703 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6704
Carlos IL07f282f2020-05-15 22:58:296705 // Suppress JavaScript dialogs when requested.
6706 bool should_suppress = delegate_ && delegate_->ShouldSuppressDialogs(this);
Pavel Feldman1c587bc52018-04-04 21:16:056707 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6708 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016709 bool suppress_this_message = should_suppress || !has_handlers;
6710
6711 if (suppress_this_message) {
Avi Drissmane04d3992017-10-05 15:11:366712 std::move(callback).Run(true, false, base::string16());
Pavel Feldman3c1842b2017-08-02 05:00:166713 return;
6714 }
6715
6716 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366717 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166718
6719 is_showing_javascript_dialog_ = true;
6720
Avi Drissman4891b852018-09-25 18:12:586721 base::string16 normalized_message = NormalizeLineBreaks(message);
6722
Pavel Feldman3c1842b2017-08-02 05:00:166723 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366724 handler->DidRunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586725 render_frame_host->GetLastCommittedURL(), normalized_message,
6726 default_prompt, dialog_type, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366727 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166728 }
6729
6730 if (dialog_manager_) {
[email protected]87de04b02014-04-08 22:14:496731 dialog_manager_->RunJavaScriptDialog(
Avi Drissman4891b852018-09-25 18:12:586732 this, render_frame_host, dialog_type, normalized_message,
6733 default_prompt,
Avi Drissmane04d3992017-10-05 15:11:366734 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false),
6735 &suppress_this_message);
[email protected]87de04b02014-04-08 22:14:496736 }
6737
6738 if (suppress_this_message) {
6739 // If we are suppressing messages, just reply as if the user immediately
6740 // pressed "Cancel", passing true to |dialog_was_suppressed|.
Avi Drissmane04d3992017-10-05 15:11:366741 wrapper->Run(true, false, base::string16());
[email protected]87de04b02014-04-08 22:14:496742 }
[email protected]87de04b02014-04-08 22:14:496743}
6744
6745void WebContentsImpl::RunBeforeUnloadConfirm(
[email protected]39f2f9252014-05-03 00:54:016746 RenderFrameHost* render_frame_host,
[email protected]87de04b02014-04-08 22:14:496747 bool is_reload,
Dave Tapuskacdf545cc2020-01-23 18:38:526748 JavaScriptDialogCallback response_callback) {
Alexander Timin5fdeff22020-09-08 09:20:376749 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RunBeforeUnloadConfirm",
6750 "render_frame_host",
6751 base::trace_event::ToTracedValue(render_frame_host),
6752 "is_reload", is_reload);
Avi Drissman2ccbb402018-03-20 21:11:366753 // Ensure that if showing a dialog is the first thing that a page does, that
6754 // the contents of the previous page aren't shown behind it. This is required
6755 // because showing a dialog freezes the renderer, so no frames will be coming
6756 // from it. https://crbug.com/823353
6757 auto* render_widget_host_impl =
6758 static_cast<RenderFrameHostImpl*>(render_frame_host)
6759 ->GetRenderWidgetHost();
6760 if (render_widget_host_impl)
6761 render_widget_host_impl->ForceFirstFrameAfterNavigationTimeout();
6762
avi0720b02e2017-06-13 03:22:136763 // Running a dialog causes an exit to webpage-initiated fullscreen.
6764 // http://crbug.com/728276
Avi Drissman1a55a9d62020-03-10 18:56:456765 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
avi0720b02e2017-06-13 03:22:136766
[email protected]39f2f9252014-05-03 00:54:016767 RenderFrameHostImpl* rfhi =
6768 static_cast<RenderFrameHostImpl*>(render_frame_host);
[email protected]87de04b02014-04-08 22:14:496769 if (delegate_)
6770 delegate_->WillRunBeforeUnloadConfirm();
6771
Avi Drissman1a55a9d62020-03-10 18:56:456772 auto callback =
6773 base::BindOnce(&WebContentsImpl::OnDialogClosed, base::Unretained(this),
6774 render_frame_host->GetProcess()->GetID(),
6775 render_frame_host->GetRoutingID(),
6776 std::move(response_callback), std::move(fullscreen_block));
Pavel Feldman3c1842b2017-08-02 05:00:166777
Pavel Feldman3c1842b2017-08-02 05:00:166778 std::vector<protocol::PageHandler*> page_handlers =
6779 protocol::PageHandler::EnabledForWebContents(this);
6780
Pavel Feldmanfab3cb62017-10-05 01:02:016781 if (delegate_)
6782 dialog_manager_ = delegate_->GetJavaScriptDialogManager(this);
6783
Charlie Reis96077362019-07-04 00:34:046784 // While a JS beforeunload dialog is showing, defer commits in this
6785 // WebContents.
6786 javascript_dialog_navigation_deferrer_ =
6787 std::make_unique<JavaScriptDialogNavigationDeferrer>();
6788
Sreeja Kamishettyf352e302020-06-10 13:21:246789 bool should_suppress = !rfhi->IsCurrent() ||
Tarun Bansalc209b742019-12-24 06:53:256790 (delegate_ && delegate_->ShouldSuppressDialogs(this));
Pavel Feldman1c587bc52018-04-04 21:16:056791 bool has_non_devtools_handlers = delegate_ && dialog_manager_;
6792 bool has_handlers = page_handlers.size() || has_non_devtools_handlers;
Pavel Feldmanfab3cb62017-10-05 01:02:016793 if (should_suppress || !has_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366794 std::move(callback).Run(false, true, base::string16());
[email protected]87de04b02014-04-08 22:14:496795 return;
6796 }
6797
6798 is_showing_before_unload_dialog_ = true;
Pavel Feldman3c1842b2017-08-02 05:00:166799
6800 scoped_refptr<CloseDialogCallbackWrapper> wrapper =
Avi Drissmane04d3992017-10-05 15:11:366801 new CloseDialogCallbackWrapper(std::move(callback));
Pavel Feldman3c1842b2017-08-02 05:00:166802
6803 GURL frame_url = rfhi->GetLastCommittedURL();
6804 for (auto* handler : page_handlers) {
Avi Drissmane04d3992017-10-05 15:11:366805 handler->DidRunBeforeUnloadConfirm(
Pavel Feldman1c587bc52018-04-04 21:16:056806 frame_url, has_non_devtools_handlers,
Avi Drissmane04d3992017-10-05 15:11:366807 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166808 }
6809
6810 if (dialog_manager_) {
Avi Drissmane04d3992017-10-05 15:11:366811 dialog_manager_->RunBeforeUnloadDialog(
Avi Drissmanff9ed752017-11-28 21:18:126812 this, render_frame_host, is_reload,
Avi Drissmane04d3992017-10-05 15:11:366813 base::BindOnce(&CloseDialogCallbackWrapper::Run, wrapper, false));
Pavel Feldman3c1842b2017-08-02 05:00:166814 }
[email protected]87de04b02014-04-08 22:14:496815}
6816
Kent Tamurac260c9a2018-09-14 09:10:566817void WebContentsImpl::RunFileChooser(
6818 RenderFrameHost* render_frame_host,
Kent Tamura3abb32d2020-07-02 00:23:016819 scoped_refptr<FileChooserImpl::FileSelectListenerImpl> listener,
Kent Tamurac260c9a2018-09-14 09:10:566820 const blink::mojom::FileChooserParams& params) {
Alexander Timin5fdeff22020-09-08 09:20:376821 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RunFileChooser",
6822 "render_frame_host",
6823 base::trace_event::ToTracedValue(render_frame_host));
Avi Drissman3d41e7712018-08-27 21:18:086824 // Any explicit focusing of another window while this WebContents is in
6825 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:456826 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
6827 listener->SetFullscreenBlock(std::move(fullscreen_block));
Avi Drissman3d41e7712018-08-27 21:18:086828
naskoada75b22016-06-11 16:09:466829 if (delegate_)
Kent Tamura512a27e2018-10-04 00:49:326830 delegate_->RunFileChooser(render_frame_host, std::move(listener), params);
6831 else
6832 listener->FileSelectionCanceled();
naskoada75b22016-06-11 16:09:466833}
6834
[email protected]a86c0e962013-12-17 17:10:396835WebContents* WebContentsImpl::GetAsWebContents() {
6836 return this;
6837}
6838
mcnee336ea2c2017-05-23 22:50:596839#if !defined(OS_ANDROID)
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416840double WebContentsImpl::GetPendingPageZoomLevel() {
wjmaclean64951902016-04-29 20:59:126841 NavigationEntry* pending_entry = GetController().GetPendingEntry();
6842 if (!pending_entry)
6843 return HostZoomMap::GetZoomLevel(this);
6844
6845 GURL url = pending_entry->GetURL();
6846 return HostZoomMap::GetForWebContents(this)->GetZoomLevelForHostAndScheme(
6847 url.scheme(), net::GetHostOrSpecFromURL(url));
6848}
mcnee336ea2c2017-05-23 22:50:596849#endif // !defined(OS_ANDROID)
wjmaclean64951902016-04-29 20:59:126850
qinmin72e8bd02016-10-21 19:35:376851bool WebContentsImpl::HideDownloadUI() const {
6852 return is_overlay_content_;
6853}
6854
mlamouri5cd9ae82017-02-18 11:05:096855bool WebContentsImpl::HasPersistentVideo() const {
6856 return has_persistent_video_;
6857}
6858
Ian Vollick5d5c37f2019-06-19 22:50:576859bool WebContentsImpl::IsSpatialNavigationDisabled() const {
6860 return is_spatial_navigation_disabled_;
6861}
6862
Albert J. Wong65fe64d2019-09-20 02:48:146863RenderFrameHostImpl* WebContentsImpl::GetPendingMainFrame() {
clamy610c63b32017-12-22 15:05:186864 return GetRenderManager()->speculative_frame_host();
Alex Moshchuk27caae82017-09-11 23:11:186865}
6866
mlamourie52c1b542017-02-23 14:57:506867bool WebContentsImpl::HasActiveEffectivelyFullscreenVideo() const {
6868 return media_web_contents_observer_->HasActiveEffectivelyFullscreenVideo();
6869}
6870
François Beaufortad6c5232018-02-26 11:00:446871bool WebContentsImpl::IsPictureInPictureAllowedForFullscreenVideo() const {
6872 return media_web_contents_observer_
6873 ->IsPictureInPictureAllowedForFullscreenVideo();
6874}
6875
ekaramada110f642016-12-21 19:47:286876bool WebContentsImpl::IsFocusedElementEditable() {
6877 RenderFrameHostImpl* frame = GetFocusedFrame();
6878 return frame && frame->has_focused_editable_element();
6879}
6880
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416881bool WebContentsImpl::IsShowingContextMenu() {
ekaramadf6750aa2017-06-06 18:29:426882 return showing_context_menu_;
6883}
6884
6885void WebContentsImpl::SetShowingContextMenu(bool showing) {
Alexander Timin5fdeff22020-09-08 09:20:376886 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SetShowingContextMenu",
6887 "showing", showing);
6888
ekaramadf6750aa2017-06-06 18:29:426889 DCHECK_NE(showing_context_menu_, showing);
6890 showing_context_menu_ = showing;
6891
6892 if (auto* view = GetRenderWidgetHostView()) {
6893 // Notify the main frame's RWHV to run the platform-specific code, if any.
6894 static_cast<RenderWidgetHostViewBase*>(view)->SetShowingContextMenu(
6895 showing);
6896 }
6897}
6898
ekaramada110f642016-12-21 19:47:286899void WebContentsImpl::ClearFocusedElement() {
Alexander Timin5fdeff22020-09-08 09:20:376900 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearFocusedElement");
ekaramada110f642016-12-21 19:47:286901 if (auto* frame = GetFocusedFrame())
6902 frame->ClearFocusedElement();
6903}
6904
danakj77eb7e82020-01-09 19:38:466905bool WebContentsImpl::IsNeverComposited() {
[email protected]7912e822014-04-16 02:37:036906 if (!delegate_)
6907 return false;
danakj77eb7e82020-01-09 19:38:466908 return delegate_->IsNeverComposited(this);
[email protected]7912e822014-04-16 02:37:036909}
6910
[email protected]5a3bdf52012-05-24 15:12:576911RenderViewHostDelegateView* WebContentsImpl::GetDelegateView() {
6912 return render_view_host_delegate_view_;
[email protected]420ae012009-04-24 05:16:326913}
6914
Peter Marshall2dc74e92020-07-29 20:02:306915blink::mojom::RendererPreferences WebContentsImpl::GetRendererPrefs() const {
[email protected]840b1512009-07-21 16:53:466916 return renderer_preferences_;
[email protected]80d96fa2009-06-10 22:34:516917}
6918
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166919RenderFrameHostImpl* WebContentsImpl::GetOuterWebContentsFrame() {
6920 if (GetOuterDelegateFrameTreeNodeId() ==
6921 FrameTreeNode::kFrameTreeNodeInvalidId) {
6922 return nullptr;
6923 }
6924
6925 FrameTreeNode* outer_node =
6926 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6927 // The outer node should be in the outer WebContents.
6928 DCHECK_EQ(outer_node->frame_tree(), GetOuterWebContents()->GetFrameTree());
Alexander Timin381e7e182020-04-28 19:04:036929 return outer_node->parent();
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166930}
6931
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:416932WebContentsImpl* WebContentsImpl::GetOuterWebContents() {
Lucas Furukawa Gadani105de1e812018-05-31 19:38:396933 return node_.outer_web_contents();
avallee0206f782016-07-28 18:55:336934}
6935
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166936std::vector<WebContents*> WebContentsImpl::GetInnerWebContents() {
6937 std::vector<WebContents*> all_inner_contents;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:166938 const auto& inner_contents = node_.GetInnerWebContents();
6939 all_inner_contents.insert(all_inner_contents.end(), inner_contents.begin(),
6940 inner_contents.end());
6941 return all_inner_contents;
6942}
6943
Jeremy Roman7e70bf92020-01-07 23:23:586944WebContentsImpl* WebContentsImpl::GetResponsibleWebContents() {
6945 // Iteratively ask delegates which other contents is responsible until a fixed
6946 // point is found.
6947 WebContentsImpl* contents = this;
6948 while (WebContentsDelegate* delegate = contents->GetDelegate()) {
6949 auto* responsible_contents = static_cast<WebContentsImpl*>(
6950 delegate->GetResponsibleWebContents(contents));
6951 if (responsible_contents == contents)
6952 break;
6953 contents = responsible_contents;
6954 }
6955 return contents;
6956}
6957
avallee0206f782016-07-28 18:55:336958WebContentsImpl* WebContentsImpl::GetFocusedWebContents() {
lfg601233692017-03-06 22:45:446959 return GetOutermostWebContents()->node_.focused_web_contents();
avallee0206f782016-07-28 18:55:336960}
6961
avallee9993fca2016-11-17 06:16:506962bool WebContentsImpl::ContainsOrIsFocusedWebContents() {
6963 for (WebContentsImpl* focused_contents = GetFocusedWebContents();
6964 focused_contents;
6965 focused_contents = focused_contents->GetOuterWebContents()) {
6966 if (focused_contents == this)
6967 return true;
6968 }
6969
6970 return false;
6971}
6972
W. James MacLean9437b5bf2019-12-06 17:33:446973void WebContentsImpl::RemoveBrowserPluginEmbedder() {
Alexander Timin5fdeff22020-09-08 09:20:376974 OPTIONAL_TRACE_EVENT0("content",
6975 "WebContentsImpl::RemoveBrowserPluginEmbedder");
W. James MacLean9437b5bf2019-12-06 17:33:446976 browser_plugin_embedder_.reset();
6977}
6978
avallee0206f782016-07-28 18:55:336979WebContentsImpl* WebContentsImpl::GetOutermostWebContents() {
6980 WebContentsImpl* root = this;
6981 while (root->GetOuterWebContents())
6982 root = root->GetOuterWebContents();
6983 return root;
6984}
6985
avalleed68cdd12017-06-21 22:07:276986void WebContentsImpl::FocusOuterAttachmentFrameChain() {
Alexander Timin5fdeff22020-09-08 09:20:376987 OPTIONAL_TRACE_EVENT0("content",
6988 "WebContentsImpl::FocusOuterAttachmentFrameChain");
avalleed68cdd12017-06-21 22:07:276989 WebContentsImpl* outer_contents = GetOuterWebContents();
6990 if (!outer_contents)
6991 return;
6992
6993 FrameTreeNode* outer_node =
6994 FrameTreeNode::GloballyFindByID(GetOuterDelegateFrameTreeNodeId());
6995 outer_contents->frame_tree_.SetFocusedFrame(outer_node, nullptr);
6996
6997 // For a browser initiated focus change, let embedding renderer know of the
6998 // change. Otherwise, if the currently focused element is just across a
6999 // process boundary in focus order, it will not be possible to move across
7000 // that boundary. This is because the target element will already be focused
7001 // (that renderer was not notified) and drop the event.
7002 if (GetRenderManager()->GetProxyToOuterDelegate())
7003 GetRenderManager()->GetProxyToOuterDelegate()->SetFocusedFrame();
7004
7005 outer_contents->FocusOuterAttachmentFrameChain();
7006}
7007
Sean Toppingbbc4a2bd2019-01-30 02:16:147008void WebContentsImpl::InnerWebContentsCreated(WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377009 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Alexander Timin90c20c32020-08-12 15:28:327010 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7011 observer->InnerWebContentsCreated(inner_web_contents);
7012 });
Sean Toppingbbc4a2bd2019-01-30 02:16:147013}
7014
Jeremy Roman03ce13ce2020-05-29 22:16:577015void WebContentsImpl::InnerWebContentsAttached(
7016 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377017 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsDetached");
Jeremy Roman03ce13ce2020-05-29 22:16:577018 if (inner_web_contents->IsCurrentlyAudible())
7019 OnAudioStateChanged();
7020}
7021
7022void WebContentsImpl::InnerWebContentsDetached(
7023 WebContents* inner_web_contents) {
Alexander Timin5fdeff22020-09-08 09:20:377024 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::InnerWebContentsCreated");
Jeremy Roman03ce13ce2020-05-29 22:16:577025 if (!is_being_destroyed_)
7026 OnAudioStateChanged();
7027}
7028
[email protected]b172aee2012-04-10 17:05:267029void WebContentsImpl::RenderViewCreated(RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377030 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewCreated",
7031 "render_view_host", render_view_host);
[email protected]86f98a22013-03-20 14:35:007032 if (delegate_)
[email protected]e85165c642014-06-10 14:34:317033 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]a6b73c62013-02-11 23:05:087034
[email protected]8ff00d72012-10-23 19:12:217035 NotificationService::current()->Notify(
7036 NOTIFICATION_WEB_CONTENTS_RENDER_VIEW_HOST_CREATED,
7037 Source<WebContents>(this),
7038 Details<RenderViewHost>(render_view_host));
[email protected]420ae012009-04-24 05:16:327039
Alexander Timin90c20c32020-08-12 15:28:327040 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7041 observer->RenderViewCreated(render_view_host);
7042 });
Joel Einbinder848001c2017-09-19 21:39:317043 if (delegate_)
7044 RenderFrameDevToolsAgentHost::WebContentsCreated(this);
[email protected]420ae012009-04-24 05:16:327045}
7046
[email protected]b172aee2012-04-10 17:05:267047void WebContentsImpl::RenderViewReady(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377048 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewReady",
7049 "render_view_host", rvh);
[email protected]151a63d2011-12-20 22:32:527050 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:327051 // Don't notify the world, since this came from a renderer in the
7052 // background.
7053 return;
7054 }
7055
dmazzoni62111452017-04-28 23:46:557056 RenderWidgetHostViewBase* rwhv =
7057 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7058 if (rwhv)
7059 rwhv->SetMainFrameAXTreeID(GetMainFrame()->GetAXTreeID());
7060
[email protected]da7a7182013-09-06 08:11:117061 notify_disconnection_ = true;
[email protected]da7a7182013-09-06 08:11:117062
[email protected]be1f56ab2011-12-22 06:55:317063 bool was_crashed = IsCrashed();
[email protected]443b80e2010-12-14 00:42:237064 SetIsCrashed(base::TERMINATION_STATUS_STILL_RUNNING, 0);
[email protected]9d8a4642009-07-29 17:25:307065
7066 // Restore the focus to the tab (otherwise the focus will be on the top
7067 // window).
[email protected]484ae5912010-09-29 19:16:147068 if (was_crashed && !FocusLocationBarByDefault() &&
7069 (!delegate_ || delegate_->ShouldFocusPageAfterCrash())) {
[email protected]f3615f02013-02-26 06:09:067070 view_->Focus();
[email protected]484ae5912010-09-29 19:16:147071 }
[email protected]32ded2212011-11-10 18:51:437072
Alexander Timin90c20c32020-08-12 15:28:327073 observers_.ForEachObserver(
7074 [&](WebContentsObserver* observer) { observer->RenderViewReady(); });
Jinsuk Kim895b2c52018-07-03 06:49:167075 view_->RenderViewReady();
[email protected]420ae012009-04-24 05:16:327076}
7077
[email protected]ec6a7eb2013-04-22 17:34:227078void WebContentsImpl::RenderViewTerminated(RenderViewHost* rvh,
7079 base::TerminationStatus status,
7080 int error_code) {
Alexander Timin5fdeff22020-09-08 09:20:377081 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::RenderViewTerminated",
7082 "render_view_host", rvh, "status",
7083 static_cast<int>(status));
[email protected]151a63d2011-12-20 22:32:527084 if (rvh != GetRenderViewHost()) {
[email protected]420ae012009-04-24 05:16:327085 // The pending page's RenderViewHost is gone.
7086 return;
7087 }
[email protected]2fcdcc32014-03-05 02:14:077088 // Ensure fullscreen mode is exited in the |delegate_| since a crashed
7089 // renderer may not have made a clean exit.
Avi Drissman97aef042020-06-30 21:04:487090 if (IsFullscreen())
bokanece34a82016-01-28 19:49:467091 ExitFullscreenMode(false);
[email protected]2fcdcc32014-03-05 02:14:077092
Jennifer Apacibleb4b972a2018-06-07 04:41:027093 // Ensure any video in Picture-in-Picture is exited in the |delegate_| since
7094 // a crashed renderer may not have made a clean exit.
7095 if (HasPictureInPictureVideo())
7096 ExitPictureInPicture();
7097
[email protected]698191dc2014-02-25 01:06:137098 // Cancel any visible dialogs so they are not left dangling over the sad tab.
creis89a0f782015-05-27 16:13:177099 CancelActiveAndPendingDialogs();
[email protected]698191dc2014-02-25 01:06:137100
dalecurtis3d1e1302017-02-20 22:33:257101 audio_stream_monitor_.RenderProcessGone(rvh->GetProcess()->GetID());
7102
[email protected]960b0372014-05-19 18:01:007103 // Reset the loading progress. TODO(avi): What does it mean to have a
7104 // "renderer crash" when there is more than one renderer process serving a
7105 // webpage? Once this function is called at a more granular frame level, we
7106 // probably will need to more granularly reset the state here.
7107 ResetLoadProgressState();
clamy44e84ce2016-02-22 15:38:257108 NotifyDisconnected();
7109 SetIsCrashed(status, error_code);
[email protected]960b0372014-05-19 18:01:007110
Alexander Timin5fdeff22020-09-08 09:20:377111 TRACE_EVENT0("content",
7112 "Dispatching WebContentsObserver::RenderViewTerminated");
Alexander Timin90c20c32020-08-12 15:28:327113 // Some observers might destroy WebContents in RenderViewTerminated.
7114 base::WeakPtr<WebContentsImpl> weak_ptr = weak_factory_.GetWeakPtr();
7115 auto crashed_status = GetCrashedStatus();
7116 for (auto& observer : observers_.observer_list()) {
7117 observer.RenderProcessGone(crashed_status);
7118 if (!weak_ptr)
7119 return;
7120 }
7121
7122 // |this| might have been deleted. Do not add code here.
[email protected]420ae012009-04-24 05:16:327123}
7124
[email protected]b172aee2012-04-10 17:05:267125void WebContentsImpl::RenderViewDeleted(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377126 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderViewDeleted",
7127 "render_view_host", rvh);
Alexander Timin90c20c32020-08-12 15:28:327128 observers_.ForEachObserver(
7129 [&](WebContentsObserver* observer) { observer->RenderViewDeleted(rvh); });
[email protected]2e4633c2009-07-09 16:58:067130}
7131
Lukasz Anforowiczfd707142018-02-07 19:46:137132void WebContentsImpl::ClearTargetURL() {
Alexander Timin5fdeff22020-09-08 09:20:377133 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearTargetURL");
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087134 frame_that_set_last_target_url_ = nullptr;
Lukasz Anforowiczfd707142018-02-07 19:46:137135 if (delegate_)
7136 delegate_->UpdateTargetURL(this, GURL());
7137}
7138
[email protected]b172aee2012-04-10 17:05:267139void WebContentsImpl::Close(RenderViewHost* rvh) {
Alexander Timin5fdeff22020-09-08 09:20:377140 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::Close", "render_view_host",
7141 rvh);
Avi Drissman7c57be72020-07-29 20:09:467142#if defined(OS_MAC)
[email protected]07707302009-11-06 00:50:297143 // The UI may be in an event-tracking loop, such as between the
7144 // mouse-down and mouse-up in text selection or a button click.
7145 // Defer the close until after tracking is complete, so that we
7146 // don't free objects out from under the UI.
[email protected]07707302009-11-06 00:50:297147 // TODO(shess): This could get more fine-grained. For instance,
7148 // closing a tab in another window while selecting text in the
7149 // current window's Omnibox should be just fine.
Christopher Cameron9ae31e0d2019-03-01 20:01:197150 if (view_->CloseTabAfterEventTrackingIfNeeded())
[email protected]07707302009-11-06 00:50:297151 return;
[email protected]60780f412013-02-25 16:34:107152#endif
[email protected]07707302009-11-06 00:50:297153
[email protected]420ae012009-04-24 05:16:327154 // Ignore this if it comes from a RenderViewHost that we aren't showing.
[email protected]151a63d2011-12-20 22:32:527155 if (delegate_ && rvh == GetRenderViewHost())
[email protected]6934a702011-12-20 00:04:517156 delegate_->CloseContents(this);
[email protected]420ae012009-04-24 05:16:327157}
7158
Avi Drissman014dec72018-06-07 02:34:017159void WebContentsImpl::RequestSetBounds(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:377160 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestSetBounds");
Mike Wassermandabad612020-08-13 04:26:277161 if (!delegate_)
7162 return;
7163
7164 // Members of |new_bounds| may be 0 to indicate uninitialized values for newly
7165 // opened windows, even if the |GetContainerBounds()| inner rect is correct.
7166 // TODO(crbug.com/897300): Plumb values as specified; fallback on outer rect.
7167 auto bounds = new_bounds;
7168 if (bounds.IsEmpty())
7169 bounds.set_size(GetContainerBounds().size());
7170
7171 // Only requests from the main frame, not subframes, should reach this code.
Mike Wassermanb6bc0152020-08-25 22:46:207172 int64_t display_id = AdjustRequestedWindowBounds(&bounds, GetMainFrame());
7173
7174 // Drop fullscreen when placing a WebContents to prohibit deceptive behavior.
7175 // Only drop fullscreen on the specific destination display, which is known.
7176 // This supports sites using cross-screen window placement capabilities to
7177 // retain fullscreen and place a window on another screen.
7178 ForSecurityDropFullscreen(display_id).RunAndReset();
7179
Mike Wassermandabad612020-08-13 04:26:277180 delegate_->SetContentsBounds(this, bounds);
[email protected]420ae012009-04-24 05:16:327181}
7182
fdegansa696e5112015-04-17 01:57:597183void WebContentsImpl::DidStartLoading(FrameTreeNode* frame_tree_node,
[email protected]e3b10d12014-03-28 16:06:097184 bool to_different_document) {
Alexander Timin5fdeff22020-09-08 09:20:377185 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidStartLoading",
7186 "frame_tree_node", frame_tree_node);
Evan Stadec3b26022017-07-14 19:50:247187 LoadingStateChanged(frame_tree_node->IsMainFrame() && to_different_document,
Carlos IL07f282f2020-05-15 22:58:297188 nullptr);
dmazzonibf8cec42015-02-08 08:28:087189
Xiyuan Xia2a66b112018-12-06 15:52:167190 // Reset the focus state from DidStartNavigation to false if a new load starts
7191 // afterward, in case loading logic triggers a FocusLocationBarByDefault call.
7192 should_focus_location_bar_by_default_ = false;
Ian Prestcdd843d2020-01-28 18:59:587193
7194 // Notify accessibility that the user is navigating away from the
7195 // current document.
7196 // TODO(domfarolino, dmazzoni): Do this using WebContentsObserver. See
7197 // https://crbug.com/981271.
7198 BrowserAccessibilityManager* manager =
7199 frame_tree_node->current_frame_host()->browser_accessibility_manager();
7200 if (manager)
7201 manager->UserIsNavigatingAway();
[email protected]420ae012009-04-24 05:16:327202}
7203
fdegansc73eec22015-03-19 14:47:547204void WebContentsImpl::DidStopLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377205 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidStopLoading");
dcheng59716272016-04-09 05:19:087206 std::unique_ptr<LoadNotificationDetails> details;
[email protected]420ae012009-04-24 05:16:327207
[email protected]9595fd82013-04-19 21:28:497208 // Use the last committed entry rather than the active one, in case a
7209 // pending entry has been created.
7210 NavigationEntry* entry = controller_.GetLastCommittedEntry();
7211
[email protected]420ae012009-04-24 05:16:327212 // An entry may not exist for a stop when loading an initial blank page or
7213 // if an iframe injected by script into a blank page finishes loading.
7214 if (entry) {
[email protected]420ae012009-04-24 05:16:327215 details.reset(new LoadNotificationDetails(
[email protected]36fc0392011-12-25 03:59:517216 entry->GetVirtualURL(),
[email protected]420ae012009-04-24 05:16:327217 &controller_,
7218 controller_.GetCurrentEntryIndex()));
7219 }
7220
Carlos IL07f282f2020-05-15 22:58:297221 LoadingStateChanged(true, details.get());
[email protected]420ae012009-04-24 05:16:327222}
7223
fdegansa696e5112015-04-17 01:57:597224void WebContentsImpl::DidChangeLoadProgress() {
Alexander Timin5fdeff22020-09-08 09:20:377225 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidChangeLoadProgress");
Nate Chapin22ea6592019-03-05 22:29:027226 if (is_being_destroyed_)
7227 return;
fdegansa696e5112015-04-17 01:57:597228 double load_progress = frame_tree_.load_progress();
7229
7230 // The delegate is notified immediately for the first and last updates. Also,
7231 // since the message loop may be pretty busy when a page is loaded, it might
7232 // not execute a posted task in a timely manner so the progress report is sent
7233 // immediately if enough time has passed.
7234 base::TimeDelta min_delay =
7235 base::TimeDelta::FromMilliseconds(kMinimumDelayBetweenLoadingUpdatesMS);
7236 bool delay_elapsed = loading_last_progress_update_.is_null() ||
7237 base::TimeTicks::Now() - loading_last_progress_update_ > min_delay;
7238
7239 if (load_progress == 0.0 || load_progress == 1.0 || delay_elapsed) {
7240 // If there is a pending task to send progress, it is now obsolete.
7241 loading_weak_factory_.InvalidateWeakPtrs();
7242
7243 // Notify the load progress change.
7244 SendChangeLoadProgress();
7245
7246 // Clean-up the states if needed.
7247 if (load_progress == 1.0)
7248 ResetLoadProgressState();
7249 return;
7250 }
7251
7252 if (loading_weak_factory_.HasWeakPtrs())
7253 return;
7254
skyostil95082a62015-06-05 19:53:077255 base::ThreadTaskRunnerHandle::Get()->PostDelayedTask(
tzike2aca992017-09-05 08:50:547256 FROM_HERE,
7257 base::BindOnce(&WebContentsImpl::SendChangeLoadProgress,
7258 loading_weak_factory_.GetWeakPtr()),
fdegansa696e5112015-04-17 01:57:597259 min_delay);
7260}
7261
avid6d88b912017-01-13 00:16:007262std::vector<std::unique_ptr<NavigationThrottle>>
7263WebContentsImpl::CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357264 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377265 OPTIONAL_TRACE_EVENT1("content",
7266 "WebContentsImpl::CreateThrottlesForNavigation",
7267 "navigation", navigation_handle);
Charlie Reis96077362019-07-04 00:34:047268 auto throttles = GetContentClient()->browser()->CreateThrottlesForNavigation(
clamycbf524d42016-09-27 12:48:357269 navigation_handle);
Charlie Reis96077362019-07-04 00:34:047270
7271 // This is not a normal place to be adding a throttle. However, in the case
7272 // javascript dialogs, related logic is present in the web_contents/ layer,
7273 // and the purpose of the throttle is to ensure that navigation commits are
7274 // deferred for the entire WebContents. Most throttles are either added by
7275 // the embederrer outside of content/, or are per-frame and added by
7276 // NavigationThrottleRunner.
7277 std::unique_ptr<content::NavigationThrottle> dialog_throttle =
7278 JavaScriptDialogNavigationThrottle::MaybeCreateThrottleFor(
7279 navigation_handle);
7280 if (dialog_throttle)
7281 throttles.push_back(std::move(dialog_throttle));
7282
7283 return throttles;
clamycbf524d42016-09-27 12:48:357284}
7285
clamy1e5574e2016-09-29 16:48:447286std::unique_ptr<NavigationUIData> WebContentsImpl::GetNavigationUIData(
7287 NavigationHandle* navigation_handle) {
Alexander Timin5fdeff22020-09-08 09:20:377288 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::GetNavigationUIData");
clamy1e5574e2016-09-29 16:48:447289 return GetContentClient()->browser()->GetNavigationUIData(navigation_handle);
7290}
7291
W. James MacLean1c40862c2020-04-27 21:05:577292void WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation(
W. James MacLeanb70fab82020-05-01 18:51:147293 const url::Origin& origin,
7294 NavigationRequest* navigation_request_to_exclude) {
Alexander Timin5fdeff22020-09-08 09:20:377295 OPTIONAL_TRACE_EVENT2(
7296 "content",
7297 "WebContentsImpl::RegisterExistingOriginToPreventOptInIsolation",
7298 "origin", base::trace_event::ValueToString(origin),
7299 "navigation_request_to_exclude", navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577300 // Note: This function can be made static if we ever need call it without
7301 // a WebContentsImpl instance, in which case we can use a wrapper to
7302 // implement the override from NavigatorDelegate.
7303 for (WebContentsImpl* web_contents : GetAllWebContents()) {
7304 web_contents->controller_.RegisterExistingOriginToPreventOptInIsolation(
7305 origin);
W. James MacLeanb70fab82020-05-01 18:51:147306 // Walk the frame tree to pick up any frames without FrameNavigationEntries.
7307 // * Some frames won't have FrameNavigationEntries (Issues 524208, 608402).
7308 // * Some pending navigations won't have NavigationEntries.
7309 web_contents->GetFrameTree()->RegisterExistingOriginToPreventOptInIsolation(
7310 origin, navigation_request_to_exclude);
W. James MacLean1c40862c2020-04-27 21:05:577311 }
7312}
7313
pdr15f5b5b2017-06-20 00:58:007314void WebContentsImpl::DidCancelLoading() {
Alexander Timin5fdeff22020-09-08 09:20:377315 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCancelLoading");
pdr15f5b5b2017-06-20 00:58:007316 controller_.DiscardNonCommittedEntries();
7317
7318 // Update the URL display.
7319 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
7320}
7321
[email protected]59167c22013-06-03 18:07:327322void WebContentsImpl::DidAccessInitialDocument() {
Alexander Timin5fdeff22020-09-08 09:20:377323 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidAccessInitialDocument");
[email protected]b4c84012014-04-28 19:51:107324 has_accessed_initial_document_ = true;
7325
[email protected]d1371bf8e2014-04-19 03:26:247326 // We may have left a failed browser-initiated navigation in the address bar
7327 // to let the user edit it and try again. Clear it now that content might
7328 // show up underneath it.
7329 if (!IsLoading() && controller_.GetPendingEntry())
avi45a72532015-04-07 21:01:457330 controller_.DiscardPendingEntry(false);
[email protected]d1371bf8e2014-04-19 03:26:247331
[email protected]59167c22013-06-03 18:07:327332 // Update the URL display.
thestigc4cac8f2014-09-04 21:17:507333 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
[email protected]59167c22013-06-03 18:07:327334}
7335
alexmosbe2f4c32015-03-10 02:30:237336void WebContentsImpl::DidChangeName(RenderFrameHost* render_frame_host,
7337 const std::string& name) {
Alexander Timin5fdeff22020-09-08 09:20:377338 OPTIONAL_TRACE_EVENT2(
7339 "content", "WebContentsImpl::DidChangeName", "render_frame_host",
7340 base::trace_event::ToTracedValue(render_frame_host), "name", name);
Alexander Timin90c20c32020-08-12 15:28:327341 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7342 observer->FrameNameChanged(render_frame_host, name);
7343 });
alexmosbe2f4c32015-03-10 02:30:237344}
7345
John Delaneyedd8d6c2019-01-25 00:23:577346void WebContentsImpl::DidReceiveFirstUserActivation(
7347 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377348 OPTIONAL_TRACE_EVENT1(
7349 "content", "WebContentsImpl::DidReceiveFirstUserActivation",
7350 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327351 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7352 observer->FrameReceivedFirstUserActivation(render_frame_host);
7353 });
John Delaneyedd8d6c2019-01-25 00:23:577354}
7355
John Delaney0146a742019-01-25 19:25:287356void WebContentsImpl::DidChangeDisplayState(RenderFrameHost* render_frame_host,
7357 bool is_display_none) {
Alexander Timin5fdeff22020-09-08 09:20:377358 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::DidChangeDisplayState",
7359 "render_frame_host",
7360 base::trace_event::ToTracedValue(render_frame_host),
7361 "is_display_none", is_display_none);
Alexander Timin90c20c32020-08-12 15:28:327362 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7363 observer->FrameDisplayStateChanged(render_frame_host, is_display_none);
7364 });
John Delaney0146a742019-01-25 19:25:287365}
7366
7367void WebContentsImpl::FrameSizeChanged(RenderFrameHost* render_frame_host,
7368 const gfx::Size& frame_size) {
Alexander Timin5fdeff22020-09-08 09:20:377369 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FrameSizeChanged",
7370 "render_frame_host",
7371 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:327372 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7373 observer->FrameSizeChanged(render_frame_host, frame_size);
7374 });
John Delaney0146a742019-01-25 19:25:287375}
7376
[email protected]39f2f9252014-05-03 00:54:017377void WebContentsImpl::DocumentOnLoadCompleted(
[email protected]50279492014-05-05 23:24:297378 RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:377379 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DocumentOnLoadCompleted",
7380 "render_frame_host",
7381 base::trace_event::ToTracedValue(render_frame_host));
falken52a56e32016-12-08 05:02:407382 ShowInsecureLocalhostWarningIfNeeded();
7383
Alexander Timindd0fa0c52019-11-06 13:03:377384 GetRenderViewHost()->DocumentOnLoadCompletedInMainFrame();
7385
Alexander Timin90c20c32020-08-12 15:28:327386 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7387 observer->DocumentOnLoadCompletedInMainFrame();
7388 });
[email protected]6578fef2013-10-14 02:35:097389
7390 // TODO(avi): Remove. http://crbug.com/170921
[email protected]8ff00d72012-10-23 19:12:217391 NotificationService::current()->Notify(
7392 NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
7393 Source<WebContents>(this),
[email protected]50279492014-05-05 23:24:297394 NotificationService::NoDetails());
[email protected]25497492010-09-11 15:15:087395}
7396
creis8eb8ef22015-11-04 22:51:387397void WebContentsImpl::UpdateStateForFrame(RenderFrameHost* render_frame_host,
7398 const PageState& page_state) {
Alexander Timin5fdeff22020-09-08 09:20:377399 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::UpdateStateForFrame",
7400 "render_frame_host",
7401 base::trace_event::ToTracedValue(render_frame_host));
creis8eb8ef22015-11-04 22:51:387402 // The state update affects the last NavigationEntry associated with the given
7403 // |render_frame_host|. This may not be the last committed NavigationEntry (as
7404 // in the case of an UpdateState from a frame being swapped out). We track
7405 // which entry this is in the RenderFrameHost's nav_entry_id.
7406 RenderFrameHostImpl* rfhi =
7407 static_cast<RenderFrameHostImpl*>(render_frame_host);
7408 NavigationEntryImpl* entry =
7409 controller_.GetEntryWithUniqueID(rfhi->nav_entry_id());
7410 if (!entry)
7411 return;
7412
7413 FrameNavigationEntry* frame_entry =
7414 entry->GetFrameEntry(rfhi->frame_tree_node());
7415 if (!frame_entry)
7416 return;
7417
creisd06a9422015-11-11 03:08:457418 // The SiteInstance might not match if we do a cross-process navigation with
7419 // replacement (e.g., auto-subframe), in which case the swap out of the old
7420 // RenderFrameHost runs in the background after the old FrameNavigationEntry
7421 // has already been replaced and destroyed.
7422 if (frame_entry->site_instance() != rfhi->GetSiteInstance())
7423 return;
7424
creis8eb8ef22015-11-04 22:51:387425 if (page_state == frame_entry->page_state())
7426 return; // Nothing to update.
7427
creis0cade2e2017-02-28 06:37:477428 DCHECK(page_state.IsValid()) << "Shouldn't set an empty PageState.";
nasko34634672016-07-29 18:46:067429
7430 // The document_sequence_number and item_sequence_number recorded in the
7431 // FrameNavigationEntry should not differ from the one coming with the update,
7432 // since it must come from the same document. Do not update it if a difference
7433 // is detected, as this indicates that |frame_entry| is not the correct one.
7434 ExplodedPageState exploded_state;
7435 if (!DecodePageState(page_state.ToEncodedData(), &exploded_state))
7436 return;
7437
7438 if (exploded_state.top.document_sequence_number !=
7439 frame_entry->document_sequence_number() ||
7440 exploded_state.top.item_sequence_number !=
7441 frame_entry->item_sequence_number()) {
7442 return;
7443 }
7444
nasko04a322f25a2016-09-01 00:00:347445 frame_entry->SetPageState(page_state);
creis8eb8ef22015-11-04 22:51:387446 controller_.NotifyEntryChanged(entry);
7447}
7448
[email protected]ef3adfc2014-05-11 00:04:547449void WebContentsImpl::UpdateTitle(RenderFrameHost* render_frame_host,
[email protected]ef3adfc2014-05-11 00:04:547450 const base::string16& title,
7451 base::i18n::TextDirection title_direction) {
Alexander Timin5fdeff22020-09-08 09:20:377452 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTitle",
7453 "render_frame_host",
7454 base::trace_event::ToTracedValue(render_frame_host),
7455 "title", base::trace_event::ValueToString(title));
[email protected]ef3adfc2014-05-11 00:04:547456 // Try to find the navigation entry, which might not be the current one.
avi286019ce2015-07-29 01:26:587457 // For example, it might be from a recently swapped out RFH.
avi1edc8552016-10-13 21:37:167458 NavigationEntryImpl* entry = controller_.GetEntryWithUniqueID(
creisad8c31a2016-05-24 17:07:047459 static_cast<RenderFrameHostImpl*>(render_frame_host)->nav_entry_id());
[email protected]ef3adfc2014-05-11 00:04:547460
7461 // We can handle title updates when we don't have an entry in
7462 // UpdateTitleForEntry, but only if the update is from the current RVH.
7463 // TODO(avi): Change to make decisions based on the RenderFrameHost.
avi286019ce2015-07-29 01:26:587464 if (!entry && render_frame_host != GetMainFrame())
[email protected]ef3adfc2014-05-11 00:04:547465 return;
7466
7467 // TODO(evan): make use of title_direction.
7468 // http://code.google.com/p/chromium/issues/detail?id=27094
afakhry6f0c1ec22016-07-14 13:55:137469 UpdateTitleForEntry(entry, title);
[email protected]ef3adfc2014-05-11 00:04:547470}
7471
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087472void WebContentsImpl::UpdateTargetURL(RenderFrameHost* render_frame_host,
7473 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:377474 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::UpdateTargetURL",
7475 "render_frame_host",
7476 base::trace_event::ToTracedValue(render_frame_host),
7477 "url", base::trace_event::ValueToString(url));
Mario Sanchez Pradadffbe66e2020-09-07 12:01:087478 if (fullscreen_widget_routing_id_ != MSG_ROUTING_NONE) {
7479 // If we're in flash fullscreen (i.e. Pepper plugin fullscreen) only update
7480 // the url if it's from the fullscreen renderer.
7481 RenderWidgetHostView* fs = GetFullscreenRenderWidgetHostView();
7482 RenderViewHost* render_view_host = render_frame_host->GetRenderViewHost();
7483 if (fs && fs->GetRenderWidgetHost() != render_view_host->GetWidget())
7484 return;
7485 }
7486
7487 // In case of racey updates from multiple RenderViewHosts, the last URL should
7488 // be shown - see also some discussion in https://crbug.com/807776.
7489 if (!url.is_valid() && render_frame_host != frame_that_set_last_target_url_)
7490 return;
7491 frame_that_set_last_target_url_ =
7492 url.is_valid() ? render_frame_host : nullptr;
7493
7494 if (delegate_)
7495 delegate_->UpdateTargetURL(this, url);
7496}
7497
alexmose7da5a12015-04-09 02:22:167498bool WebContentsImpl::ShouldRouteMessageEvent(
7499 RenderFrameHost* target_rfh,
7500 SiteInstance* source_site_instance) const {
Alexander Timin5fdeff22020-09-08 09:20:377501 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::ShouldRouteMessageEvent",
7502 "render_frame_host",
7503 base::trace_event::ToTracedValue(target_rfh),
7504 "source_site_instance", source_site_instance);
alexmose7da5a12015-04-09 02:22:167505 // Allow the message if this WebContents is dedicated to a browser plugin
7506 // guest.
[email protected]0eba810b2012-10-18 03:19:367507 // Note: This check means that an embedder could theoretically receive a
7508 // postMessage from anyone (not just its own guests). However, this is
7509 // probably not a risk for apps since other pages won't have references
7510 // to App windows.
alexmose7da5a12015-04-09 02:22:167511 return GetBrowserPluginGuest() || GetBrowserPluginEmbedder();
7512}
[email protected]f546640b2012-05-15 00:03:497513
alexmos58729042015-06-18 23:20:007514void WebContentsImpl::EnsureOpenerProxiesExist(RenderFrameHost* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377515 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::EnsureOpenerProxiesExist",
7516 "render_frame_host",
7517 base::trace_event::ToTracedValue(source_rfh));
alexmose7da5a12015-04-09 02:22:167518 WebContentsImpl* source_web_contents = static_cast<WebContentsImpl*>(
7519 WebContents::FromRenderFrameHost(source_rfh));
[email protected]f546640b2012-05-15 00:03:497520
alexmose7da5a12015-04-09 02:22:167521 if (source_web_contents) {
lazyboy6ec48b2a2015-06-29 15:18:147522 // If this message is going to outer WebContents from inner WebContents,
7523 // then we should not create a RenderView. AttachToOuterWebContentsFrame()
7524 // already created a RenderFrameProxyHost for that purpose.
7525 if (GetBrowserPluginEmbedder() &&
W. James MacLean2539adb32019-12-13 00:40:447526 source_web_contents->browser_plugin_guest_) {
lazyboy6ec48b2a2015-06-29 15:18:147527 return;
W. James MacLean2539adb32019-12-13 00:40:447528 }
lazyboy6ec48b2a2015-06-29 15:18:147529
lfg812874d2016-02-09 22:26:137530 if (this != source_web_contents && GetBrowserPluginGuest()) {
naskob3041b98a42016-03-12 04:43:067531 // We create a RenderFrameProxyHost for the embedder in the guest's render
7532 // process but we intentionally do not expose the embedder's opener chain
7533 // to it.
7534 source_web_contents->GetRenderManager()->CreateRenderFrameProxy(
7535 GetSiteInstance());
[email protected]f546640b2012-05-15 00:03:497536 } else {
alexmos58729042015-06-18 23:20:007537 RenderFrameHostImpl* source_rfhi =
7538 static_cast<RenderFrameHostImpl*>(source_rfh);
7539 source_rfhi->frame_tree_node()->render_manager()->CreateOpenerProxies(
alexmos90325cf2015-09-02 17:18:397540 GetSiteInstance(), nullptr);
[email protected]f546640b2012-05-15 00:03:497541 }
7542 }
[email protected]f546640b2012-05-15 00:03:497543}
7544
avallee9993fca2016-11-17 06:16:507545void WebContentsImpl::SetAsFocusedWebContentsIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:377546 OPTIONAL_TRACE_EVENT0("content",
7547 "WebContentsImpl::SetAsFocusedWebContentsIfNecessary");
Adithya Srinivasan11af2c52019-12-16 22:52:557548 DCHECK(!portal());
avallee9993fca2016-11-17 06:16:507549 // Only change focus if we are not currently focused.
7550 WebContentsImpl* old_contents = GetFocusedWebContents();
7551 if (old_contents == this)
7552 return;
7553
paulmeyerfeafc2d2017-04-25 21:46:407554 GetOutermostWebContents()->node_.SetFocusedWebContents(this);
7555
avallee9993fca2016-11-17 06:16:507556 // Send a page level blur to the old contents so that it displays inactive UI
7557 // and focus this contents to activate it.
7558 if (old_contents)
7559 old_contents->GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(false);
avalleec2ff1ef2017-01-21 00:12:307560
7561 // Make sure the outer web contents knows our frame is focused. Otherwise, the
7562 // outer renderer could have the element before or after the frame element
7563 // focused which would return early without actually advancing focus.
avalleed68cdd12017-06-21 22:07:277564 FocusOuterAttachmentFrameChain();
avalleec2ff1ef2017-01-21 00:12:307565
Carlos ILd51e7702020-05-07 18:51:397566 GetMainFrame()->GetRenderWidgetHost()->SetPageFocus(true);
avallee9993fca2016-11-17 06:16:507567}
7568
avallee0206f782016-07-28 18:55:337569void WebContentsImpl::SetFocusedFrame(FrameTreeNode* node,
7570 SiteInstance* source) {
Alexander Timin5fdeff22020-09-08 09:20:377571 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetFocusedFrame",
7572 "frame_tree_node", node, "source_site_instance",
7573 source);
Adithya Srinivasan11af2c52019-12-16 22:52:557574 DCHECK(!portal());
avallee0206f782016-07-28 18:55:337575 frame_tree_.SetFocusedFrame(node, source);
avalleed68cdd12017-06-21 22:07:277576
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577577 if (auto* inner_contents = node_.GetInnerWebContentsInFrame(node)) {
7578 // |this| is an outer WebContents and |node| represents an inner
7579 // WebContents. Transfer the focus to the inner contents if |this| is
7580 // focused.
7581 if (GetFocusedWebContents() == this)
7582 inner_contents->SetAsFocusedWebContentsIfNecessary();
7583 } else if (node_.OuterContentsFrameTreeNode() &&
7584 node_.OuterContentsFrameTreeNode()
7585 ->current_frame_host()
7586 ->GetSiteInstance() == source) {
7587 // |this| is an inner WebContents, |node| is its main FrameTreeNode and
7588 // the outer WebContents FrameTreeNode is at |source|'s SiteInstance.
7589 // Transfer the focus to the inner WebContents if the outer WebContents is
7590 // focused. This branch is used when an inner WebContents is focused through
Lowell Mannersa9530382019-08-01 09:46:577591 // its RenderFrameProxyHost (via FrameFocused mojo call, used to
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577592 // implement the window.focus() API).
7593 if (GetFocusedWebContents() == GetOuterWebContents())
7594 SetAsFocusedWebContentsIfNecessary();
7595 } else if (!GetOuterWebContents()) {
7596 // This is an outermost WebContents.
7597 SetAsFocusedWebContentsIfNecessary();
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577598 }
avalleed68cdd12017-06-21 22:07:277599}
7600
Avi Drissman36f801f2018-02-01 20:06:047601void WebContentsImpl::DidCallFocus() {
Alexander Timin5fdeff22020-09-08 09:20:377602 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::DidCallFocus");
Avi Drissman36f801f2018-02-01 20:06:047603 // Any explicit focusing of another window while this WebContents is in
7604 // fullscreen can be used to confuse the user, so drop fullscreen.
Avi Drissman1a55a9d62020-03-10 18:56:457605 base::ScopedClosureRunner fullscreen_block = ForSecurityDropFullscreen();
7606 // The other contents is independent of this contents, so release the
7607 // fullscreen block.
7608 fullscreen_block.RunAndReset();
Avi Drissman36f801f2018-02-01 20:06:047609}
7610
avalleed68cdd12017-06-21 22:07:277611RenderFrameHost* WebContentsImpl::GetFocusedFrameIncludingInnerWebContents() {
Alexander Timin5fdeff22020-09-08 09:20:377612 OPTIONAL_TRACE_EVENT0(
7613 "content", "WebContentsImpl::GetFocusedFrameIncludingInnerWebContents");
avalleed68cdd12017-06-21 22:07:277614 WebContentsImpl* contents = this;
7615 FrameTreeNode* focused_node = contents->frame_tree_.GetFocusedFrame();
7616
7617 // If there is no focused frame in the outer WebContents, we need to return
7618 // null.
7619 if (!focused_node)
7620 return nullptr;
7621
7622 // If the focused frame is embedding an inner WebContents, we must descend
7623 // into that contents. If the current WebContents does not have a focused
7624 // frame, return the main frame of this contents instead of the focused empty
7625 // frame embedding this contents.
7626 while (true) {
7627 contents = contents->node_.GetInnerWebContentsInFrame(focused_node);
7628 if (!contents)
7629 return focused_node->current_frame_host();
7630
7631 focused_node = contents->frame_tree_.GetFocusedFrame();
7632 if (!focused_node)
7633 return contents->GetMainFrame();
7634 }
avallee0206f782016-07-28 18:55:337635}
7636
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577637void WebContentsImpl::OnAdvanceFocus(RenderFrameHostImpl* source_rfh) {
Alexander Timin5fdeff22020-09-08 09:20:377638 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnAdvanceFocus",
7639 "render_frame_host",
7640 base::trace_event::ToTracedValue(source_rfh));
Lucas Furukawa Gadaniabbfa342017-08-29 19:37:577641 // When a RenderFrame needs to advance focus to a RenderFrameProxy (by hitting
7642 // TAB), the RenderFrameProxy sends an IPC to RenderFrameProxyHost. When this
7643 // RenderFrameProxyHost represents an inner WebContents, the outer WebContents
7644 // needs to focus the inner WebContents.
7645 if (GetOuterWebContents() &&
7646 GetOuterWebContents() == source_rfh->delegate()->GetAsWebContents() &&
7647 GetFocusedWebContents() == GetOuterWebContents()) {
7648 SetAsFocusedWebContentsIfNecessary();
7649 }
7650}
7651
ekaramada110f642016-12-21 19:47:287652void WebContentsImpl::OnFocusedElementChangedInFrame(
7653 RenderFrameHostImpl* frame,
Emily Stark023dbacc2020-08-27 22:31:407654 const gfx::Rect& bounds_in_root_view,
7655 blink::mojom::FocusType focus_type) {
Alexander Timin5fdeff22020-09-08 09:20:377656 OPTIONAL_TRACE_EVENT1(
7657 "content", "WebContentsImpl::OnFocusedElementChangedInFrame",
7658 "render_frame_host", base::trace_event::ToTracedValue(frame));
ekaramada110f642016-12-21 19:47:287659 RenderWidgetHostViewBase* root_view =
7660 static_cast<RenderWidgetHostViewBase*>(GetRenderWidgetHostView());
7661 if (!root_view || !frame->GetView())
7662 return;
Katie De0131372020-07-09 23:03:107663 // Convert to screen coordinates from window coordinates by adding the
7664 // window's origin.
ekaramada110f642016-12-21 19:47:287665 gfx::Point origin = bounds_in_root_view.origin();
7666 origin += root_view->GetViewBounds().OffsetFromOrigin();
7667 gfx::Rect bounds_in_screen(origin, bounds_in_root_view.size());
7668
7669 root_view->FocusedNodeChanged(frame->has_focused_editable_element(),
7670 bounds_in_screen);
7671
7672 FocusedNodeDetails details = {frame->has_focused_editable_element(),
Emily Stark023dbacc2020-08-27 22:31:407673 bounds_in_screen, focus_type};
ekaramada110f642016-12-21 19:47:287674
7675 // TODO(ekaramad): We should replace this with an observer notification
7676 // (https://crbug.com/675975).
7677 NotificationService::current()->Notify(
7678 NOTIFICATION_FOCUS_CHANGED_IN_PAGE,
7679 Source<RenderViewHost>(GetRenderViewHost()),
7680 Details<FocusedNodeDetails>(&details));
Jeff Fisher709b4c52019-07-29 20:07:347681
Alexander Timin90c20c32020-08-12 15:28:327682 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7683 observer->OnFocusChangedInPage(&details);
7684 });
ekaramada110f642016-12-21 19:47:287685}
7686
Lowell Manners1de5242e2019-04-25 10:18:467687bool WebContentsImpl::DidAddMessageToConsole(
7688 blink::mojom::ConsoleMessageLevel log_level,
7689 const base::string16& message,
7690 int32_t line_no,
7691 const base::string16& source_id) {
Alexander Timin5fdeff22020-09-08 09:20:377692 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidAddMessageToConsole",
7693 "message", base::trace_event::ValueToString(message));
7694
Alexander Timin90c20c32020-08-12 15:28:327695 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7696 observer->OnDidAddMessageToConsole(log_level, message, line_no, source_id);
7697 });
Alexander Timin5fdeff22020-09-08 09:20:377698
[email protected]a796f202012-05-30 14:14:257699 if (!delegate_)
7700 return false;
Lowell Manners1de5242e2019-04-25 10:18:467701 return delegate_->DidAddMessageToConsole(this, log_level, message, line_no,
avia90ae4e2016-11-11 20:49:337702 source_id);
[email protected]a796f202012-05-30 14:14:257703}
7704
Daniel Cheng90196c82018-04-25 21:49:147705void WebContentsImpl::DidReceiveInputEvent(
dominickn9c7ceaa32016-02-27 01:52:537706 RenderWidgetHostImpl* render_widget_host,
Emily Starkc7bd40c42020-07-21 19:12:557707 const blink::WebInputEvent& event) {
Alexander Timin5fdeff22020-09-08 09:20:377708 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::DidReceiveInputEvent",
7709 "render_widget_host", render_widget_host);
7710
Emily Starkc7bd40c42020-07-21 19:12:557711 if (!IsUserInteractionInputType(event.GetType()))
Daniel Cheng90196c82018-04-25 21:49:147712 return;
7713
kenrb19221852016-04-29 17:21:407714 // Ignore unless the widget is currently in the frame tree.
7715 if (!HasMatchingWidgetHost(&frame_tree_, render_widget_host))
avic3aa8422015-11-09 20:57:227716 return;
7717
Emily Starkc7bd40c42020-07-21 19:12:557718 if (event.GetType() != blink::WebInputEvent::Type::kGestureScrollBegin)
Daniel Cheng90196c82018-04-25 21:49:147719 last_interactive_input_event_time_ = ui::EventTimeForNow();
dominickn9c7ceaa32016-02-27 01:52:537720
Alexander Timin90c20c32020-08-12 15:28:327721 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7722 observer->DidGetUserInteraction(event);
7723 });
dominickn2dd142dd2015-10-29 05:30:507724}
7725
Avi Drissman738ea192018-08-29 20:24:167726bool WebContentsImpl::ShouldIgnoreInputEvents() {
7727 WebContentsImpl* web_contents = this;
7728 while (web_contents) {
7729 if (web_contents->ignore_input_events_)
7730 return true;
7731 web_contents = web_contents->GetOuterWebContents();
7732 }
7733
7734 return false;
7735}
7736
avallee9993fca2016-11-17 06:16:507737void WebContentsImpl::FocusOwningWebContents(
7738 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377739 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::FocusOwningWebContents",
7740 "render_widget_host", render_widget_host);
Alex Moshchukc4f0a722019-11-19 22:41:287741 RenderWidgetHostImpl* main_frame_widget_host =
7742 GetMainFrame()->GetRenderWidgetHost();
avallee9993fca2016-11-17 06:16:507743 RenderWidgetHostImpl* focused_widget =
Alex Moshchukc4f0a722019-11-19 22:41:287744 GetFocusedRenderWidgetHost(main_frame_widget_host);
avallee9993fca2016-11-17 06:16:507745
7746 if (focused_widget != render_widget_host &&
avallee8e881592016-11-19 00:39:307747 (!focused_widget ||
7748 focused_widget->delegate() != render_widget_host->delegate())) {
avallee9993fca2016-11-17 06:16:507749 SetAsFocusedWebContentsIfNecessary();
7750 }
7751}
7752
[email protected]b172aee2012-04-10 17:05:267753void WebContentsImpl::OnIgnoredUIEvent() {
Alexander Timin5fdeff22020-09-08 09:20:377754 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnIgnoredUIEvent");
[email protected]31145092011-09-30 01:49:447755 // Notify observers.
Alexander Timin90c20c32020-08-12 15:28:327756 observers_.ForEachObserver(
7757 [&](WebContentsObserver* observer) { observer->DidGetIgnoredUIEvent(); });
[email protected]fa1cf0b82010-01-15 21:49:447758}
7759
avic3aa8422015-11-09 20:57:227760void WebContentsImpl::RendererUnresponsive(
Lukasz Anforowicz52b93722018-06-20 16:11:397761 RenderWidgetHostImpl* render_widget_host,
7762 base::RepeatingClosure hang_monitor_restarter) {
Alexander Timin5fdeff22020-09-08 09:20:377763 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RendererUnresponsive",
7764 "render_widget_host", render_widget_host);
avic031d392017-03-03 03:09:427765 if (ShouldIgnoreUnresponsiveRenderer())
[email protected]e5fc1632011-08-08 07:51:537766 return;
7767
Lukasz Anforowicz4f0593d2018-09-21 18:33:547768 // Do not report hangs (to task manager, to hang renderer dialog, etc.) for
7769 // invisible tabs (like extension background page, background tabs). See
7770 // https://crbug.com/881812 for rationale and for choosing the visibility
7771 // (rather than process priority) as the signal here.
7772 if (GetVisibility() != Visibility::VISIBLE)
7773 return;
7774
Avi Drissman8920def2018-01-31 19:53:367775 if (!render_widget_host->renderer_initialized())
[email protected]55452902011-06-01 21:57:477776 return;
7777
Alexander Timin90c20c32020-08-12 15:28:327778 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7779 observer->OnRendererUnresponsive(render_widget_host->GetProcess());
7780 });
Dave Tapuskac6146c52017-12-20 22:48:157781 if (delegate_)
Lukasz Anforowicz52b93722018-06-20 16:11:397782 delegate_->RendererUnresponsive(this, render_widget_host,
7783 std::move(hang_monitor_restarter));
[email protected]420ae012009-04-24 05:16:327784}
7785
avic3aa8422015-11-09 20:57:227786void WebContentsImpl::RendererResponsive(
7787 RenderWidgetHostImpl* render_widget_host) {
Alexander Timin5fdeff22020-09-08 09:20:377788 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RenderResponsive",
7789 "render_widget_host", render_widget_host);
Alexander Timin90c20c32020-08-12 15:28:327790 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7791 observer->OnRendererResponsive(render_widget_host->GetProcess());
7792 });
Alexander Timin5fdeff22020-09-08 09:20:377793
[email protected]6934a702011-12-20 00:04:517794 if (delegate_)
Avi Drissman1572e8c3c2018-02-02 19:06:367795 delegate_->RendererResponsive(this, render_widget_host);
[email protected]420ae012009-04-24 05:16:327796}
7797
Alex Moshchuk7b4f0652019-05-30 18:54:417798void WebContentsImpl::SubframeCrashed(
7799 blink::mojom::FrameVisibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:377800 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::SubframeCrashed",
7801 "visibility",
7802 base::trace_event::ValueToString(visibility));
Alex Moshchuk7b4f0652019-05-30 18:54:417803 // If a subframe crashed on a hidden tab, mark the tab for reload to avoid
7804 // showing a sad frame to the user if they ever switch back to that tab. Do
7805 // this for subframes that are either visible in viewport or visible but
7806 // scrolled out of view, but skip subframes that are not rendered (e.g., via
7807 // "display:none"), since in that case the user wouldn't see a sad frame
7808 // anyway.
7809 bool did_mark_for_reload = false;
7810 if (IsHidden() && visibility != blink::mojom::FrameVisibility::kNotRendered &&
7811 base::FeatureList::IsEnabled(
7812 features::kReloadHiddenTabsWithCrashedSubframes)) {
7813 controller_.SetNeedsReload(
7814 NavigationControllerImpl::NeedsReloadType::kCrashedSubframe);
7815 did_mark_for_reload = true;
7816 UMA_HISTOGRAM_ENUMERATION(
7817 "Stability.ChildFrameCrash.TabMarkedForReload.Visibility", visibility);
7818 }
7819
7820 UMA_HISTOGRAM_BOOLEAN("Stability.ChildFrameCrash.TabMarkedForReload",
7821 did_mark_for_reload);
7822}
7823
[email protected]b172aee2012-04-10 17:05:267824void WebContentsImpl::BeforeUnloadFiredFromRenderManager(
[email protected]feaded02012-09-25 19:12:557825 bool proceed, const base::TimeTicks& proceed_time,
[email protected]420ae012009-04-24 05:16:327826 bool* proceed_to_fire_unload) {
Alexander Timin5fdeff22020-09-08 09:20:377827 OPTIONAL_TRACE_EVENT0("content",
7828 "WebContentsImpl::BeforeUnloadFiredFromRenderManager");
Alexander Timin90c20c32020-08-12 15:28:327829 observers_.ForEachObserver([&](WebContentsObserver* observer) {
7830 observer->BeforeUnloadFired(proceed, proceed_time);
7831 });
[email protected]6934a702011-12-20 00:04:517832 if (delegate_)
7833 delegate_->BeforeUnloadFired(this, proceed, proceed_to_fire_unload);
[email protected]e80af492013-06-24 21:52:097834 // Note: |this| might be deleted at this point.
[email protected]420ae012009-04-24 05:16:327835}
7836
[email protected]58d5cfe2013-07-10 02:40:527837void WebContentsImpl::RenderProcessGoneFromRenderManager(
[email protected]3a3d47472010-07-15 21:03:547838 RenderViewHost* render_view_host) {
[email protected]443b80e2010-12-14 00:42:237839 DCHECK(crashed_status_ != base::TERMINATION_STATUS_STILL_RUNNING);
[email protected]ec6a7eb2013-04-22 17:34:227840 RenderViewTerminated(render_view_host, crashed_status_, crashed_error_code_);
[email protected]3a3d47472010-07-15 21:03:547841}
7842
[email protected]af905902013-10-01 21:38:517843void WebContentsImpl::CancelModalDialogsForRenderManager() {
Alexander Timin5fdeff22020-09-08 09:20:377844 OPTIONAL_TRACE_EVENT0("content",
7845 "WebContentsImpl::CancelModalDialogsForRenderManager");
[email protected]af905902013-10-01 21:38:517846 // We need to cancel modal dialogs when doing a process swap, since the load
avi2460c762015-04-17 15:21:547847 // deferrer would prevent us from swapping out. We also clear the state
7848 // because this is a cross-process navigation, which means that it's a new
7849 // site that should not have to pay for the sins of its predecessor.
creis89a0f782015-05-27 16:13:177850 //
Lei Zhang6410ec1a2019-01-31 21:38:587851 // Note that we don't bother telling |browser_plugin_embedder_| because the
creis89a0f782015-05-27 16:13:177852 // cross-process navigation will either destroy the browser plugins or not
7853 // require their dialogs to close.
avi5d3b8692016-10-12 22:00:467854 if (dialog_manager_) {
avi6879fcf2017-01-21 05:27:537855 dialog_manager_->CancelDialogs(this, /*reset_state=*/true);
avi5d3b8692016-10-12 22:00:467856 }
[email protected]af905902013-10-01 21:38:517857}
7858
danakja0bce4c952020-05-12 20:40:287859void WebContentsImpl::NotifySwappedFromRenderManager(RenderFrameHost* old_frame,
7860 RenderFrameHost* new_frame,
[email protected]02d7b6e2014-06-24 21:01:507861 bool is_main_frame) {
Alexander Timin5fdeff22020-09-08 09:20:377862 TRACE_EVENT2(
7863 "content", "WebContentsImpl::NotifySwappedFromRenderManager",
7864 "old_render_frame_host", base::trace_event::ToTracedValue(old_frame),
7865 "new_render_frame_host", base::trace_event::ToTracedValue(new_frame));
[email protected]02d7b6e2014-06-24 21:01:507866 if (is_main_frame) {
danakja0bce4c952020-05-12 20:40:287867 // The |new_frame| and its various compadres are already swapped into place
7868 // for the WebContentsImpl when this method is called.
7869 DCHECK(GetMainFrame() == new_frame);
7870 DCHECK(GetRenderViewHost() == new_frame->GetRenderViewHost());
7871 DCHECK(GetRenderWidgetHostView() == new_frame->GetView());
7872
Fergal Daly6767b2e2020-02-04 03:15:167873 RenderViewHost* old_rvh =
danakja0bce4c952020-05-12 20:40:287874 old_frame ? old_frame->GetRenderViewHost() : nullptr;
7875 RenderViewHost* new_rvh = new_frame->GetRenderViewHost();
Fergal Daly6767b2e2020-02-04 03:15:167876 // |old_rvh| and |new_rvh| might be equal when navigating from a crashed
7877 // RenderFrameHost to a new same-site one. With RenderDocument, this will
7878 // happen for every same-site navigation.
7879 if (old_rvh != new_rvh)
7880 NotifyViewSwapped(old_rvh, new_rvh);
[email protected]a6b73c62013-02-11 23:05:087881
[email protected]02d7b6e2014-06-24 21:01:507882 // Make sure the visible RVH reflects the new delegate's preferences.
7883 if (delegate_)
7884 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
[email protected]d56a49e2013-02-23 00:47:397885
danakja0bce4c952020-05-12 20:40:287886 auto* rwhv = static_cast<RenderWidgetHostViewBase*>(new_frame->GetView());
7887 if (rwhv) {
7888 rwhv->SetMainFrameAXTreeID(new_frame->GetAXTreeID());
7889
7890 // The RenderWidgetHostView for the speculative RenderFrameHost is not
7891 // resized with the current RenderFrameHost while a navigation is
7892 // pending. So when we swap in the main frame, we need to update the
7893 // RenderWidgetHostView's size.
7894 //
7895 // Historically, this was done to fix b/1079768 for interstitials.
7896 rwhv->SetSize(GetSizeForMainFrame());
7897 }
[email protected]02d7b6e2014-06-24 21:01:507898 }
7899
danakja0bce4c952020-05-12 20:40:287900 NotifyFrameSwapped(old_frame, new_frame, is_main_frame);
[email protected]3a3d47472010-07-15 21:03:547901}
7902
naskof5940b9f2015-03-02 23:04:057903void WebContentsImpl::NotifyMainFrameSwappedFromRenderManager(
danakja0bce4c952020-05-12 20:40:287904 RenderFrameHost* old_frame,
7905 RenderFrameHost* new_frame) {
7906 NotifyViewSwapped(old_frame ? old_frame->GetRenderViewHost() : nullptr,
7907 new_frame->GetRenderViewHost());
naskof5940b9f2015-03-02 23:04:057908}
7909
[email protected]b172aee2012-04-10 17:05:267910NavigationControllerImpl& WebContentsImpl::GetControllerForRenderManager() {
[email protected]d1198fd2012-08-13 22:50:197911 return GetController();
[email protected]3a3d47472010-07-15 21:03:547912}
7913
dcheng59716272016-04-09 05:19:087914std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUIForRenderFrameHost(
Miyoung Shin072d4052020-07-13 07:52:447915 RenderFrameHost* frame_host,
Denis Kuznetsov [CET]2c6f0159f2020-05-18 14:18:167916 const GURL& url) {
Miyoung Shin072d4052020-07-13 07:52:447917 return CreateWebUI(frame_host, url);
[email protected]420ae012009-04-24 05:16:327918}
7919
lfgbede6392015-09-11 21:54:067920void WebContentsImpl::CreateRenderWidgetHostViewForRenderManager(
7921 RenderViewHost* render_view_host) {
Alexander Timin5fdeff22020-09-08 09:20:377922 OPTIONAL_TRACE_EVENT1(
7923 "content", "WebContentsImpl::CreateRenderWidgetHostViewForRenderManager",
7924 "render_view_host", render_view_host);
lfgc740d4b22016-04-15 16:45:337925 RenderWidgetHostViewBase* rwh_view =
W. James MacLean13d834d2019-12-04 16:06:457926 view_->CreateViewForWidget(render_view_host->GetWidget());
danakja0bce4c952020-05-12 20:40:287927 rwh_view->SetSize(GetSizeForMainFrame());
lfgbede6392015-09-11 21:54:067928}
7929
7930bool WebContentsImpl::CreateRenderViewForRenderManager(
7931 RenderViewHost* render_view_host,
Antonio Gomesb3dd5fc2020-05-25 22:53:277932 const base::Optional<base::UnguessableToken>& opener_frame_token,
Daniel Chengabfdb002020-06-04 06:02:307933 int proxy_routing_id) {
Alexander Timin5fdeff22020-09-08 09:20:377934 TRACE_EVENT1("browser,navigation",
7935 "WebContentsImpl::CreateRenderViewForRenderManager",
7936 "render_view_host", render_view_host);
lfgbede6392015-09-11 21:54:067937
piman00cf9402017-04-03 17:09:207938 if (proxy_routing_id == MSG_ROUTING_NONE)
lfg9431efd2016-12-14 14:45:267939 CreateRenderWidgetHostViewForRenderManager(render_view_host);
lfg9431efd2016-12-14 14:45:267940
piman00cf9402017-04-03 17:09:207941 if (!static_cast<RenderViewHostImpl*>(render_view_host)
Daniel Chengabfdb002020-06-04 06:02:307942 ->CreateRenderView(opener_frame_token, proxy_routing_id,
Antonio Gomesb3dd5fc2020-05-25 22:53:277943 created_with_opener_)) {
[email protected]a4127722011-04-27 23:13:527944 return false;
[email protected]14392a52012-05-02 20:28:447945 }
W. James MacLean62198672019-06-04 16:46:107946 // Set the TextAutosizer state from the main frame's renderer on the new view,
7947 // but only if it's not for the main frame. Main frame renderers should create
7948 // this state themselves from up-to-date values, so we shouldn't override it
7949 // with the cached values.
7950 if (!render_view_host->GetMainFrame()) {
Antonio Gomesda7e03d2020-08-05 15:03:087951 auto* proxy_host = GetRenderManager()->GetRenderFrameProxyHost(
7952 render_view_host->GetSiteInstance());
7953 proxy_host->GetAssociatedRemoteMainFrame()->UpdateTextAutosizerPageInfo(
7954 text_autosizer_page_info_.Clone());
W. James MacLean62198672019-06-04 16:46:107955 }
[email protected]a4127722011-04-27 23:13:527956
Lucas Furukawa Gadaniaed1fed2017-10-13 17:34:147957 if (proxy_routing_id == MSG_ROUTING_NONE && node_.outer_web_contents())
7958 ReattachToOuterWebContentsFrame();
7959
avi2b177592014-12-10 02:08:027960 SetHistoryOffsetAndLengthForView(render_view_host,
7961 controller_.GetLastCommittedEntryIndex(),
7962 controller_.GetEntryCount());
7963
Avi Drissman7c57be72020-07-29 20:09:467964#if defined(OS_POSIX) && !defined(OS_MAC) && !defined(OS_ANDROID)
[email protected]f8233cc2011-05-31 20:24:507965 // Force a ViewMsg_Resize to be sent, needed to make plugins show up on
7966 // linux. See crbug.com/83941.
avif9ab5d942015-10-15 14:05:447967 RenderWidgetHostView* rwh_view = render_view_host->GetWidget()->GetView();
[email protected]245f7d52011-11-28 15:36:447968 if (rwh_view) {
7969 if (RenderWidgetHost* render_widget_host = rwh_view->GetRenderWidgetHost())
Fady Samuel0b911822018-04-25 13:22:167970 render_widget_host->SynchronizeVisualProperties();
[email protected]245f7d52011-11-28 15:36:447971 }
[email protected]f8233cc2011-05-31 20:24:507972#endif
7973
[email protected]420ae012009-04-24 05:16:327974 return true;
7975}
7976
[email protected]82307f6b2014-08-07 03:30:127977bool WebContentsImpl::CreateRenderFrameForRenderManager(
7978 RenderFrameHost* render_frame_host,
arthursonzogni1efc7b962019-03-14 09:36:337979 int previous_routing_id,
Antonio Gomes9d150542020-05-25 18:32:117980 const base::Optional<base::UnguessableToken>& opener_frame_token,
japhete6adf142014-10-31 00:01:497981 int parent_routing_id,
alexmosa181efc2015-09-03 00:39:047982 int previous_sibling_routing_id) {
Alexander Timin5fdeff22020-09-08 09:20:377983 TRACE_EVENT2(
7984 "browser,navigation",
7985 "WebContentsImpl::CreateRenderFrameForRenderManager", "render_frame_host",
7986 base::trace_event::ToTracedValue(render_frame_host), "params",
7987 base::trace_event::TracedValue::Build(
7988 {{"previous_routing_id", previous_routing_id},
7989 {"parent_routing_id", parent_routing_id},
7990 {"previous_sibling_routing_id", previous_sibling_routing_id}}));
[email protected]82307f6b2014-08-07 03:30:127991
7992 RenderFrameHostImpl* rfh =
7993 static_cast<RenderFrameHostImpl*>(render_frame_host);
Antonio Gomes9d150542020-05-25 18:32:117994 if (!rfh->CreateRenderFrame(previous_routing_id, opener_frame_token,
7995 parent_routing_id, previous_sibling_routing_id)) {
[email protected]82307f6b2014-08-07 03:30:127996 return false;
Antonio Gomes9d150542020-05-25 18:32:117997 }
[email protected]82307f6b2014-08-07 03:30:127998
7999 // TODO(nasko): When RenderWidgetHost is owned by RenderFrameHost, the passed
8000 // RenderFrameHost will have to be associated with the appropriate
8001 // RenderWidgetHostView or a new one should be created here.
8002
8003 return true;
8004}
8005
mfomitchev2b8b066a2016-01-28 19:23:158006#if defined(OS_ANDROID)
[email protected]fc2b46b2014-05-03 16:33:458007
[email protected]155c7f22013-12-09 17:07:188008base::android::ScopedJavaLocalRef<jobject>
8009WebContentsImpl::GetJavaWebContents() {
mostynb042582e2015-03-16 22:13:408010 DCHECK_CURRENTLY_ON(BrowserThread::UI);
[email protected]0e813a52014-08-13 10:34:568011 return GetWebContentsAndroid()->GetJavaObject();
8012}
[email protected]155c7f22013-12-09 17:07:188013
[email protected]0e813a52014-08-13 10:34:568014WebContentsAndroid* WebContentsImpl::GetWebContentsAndroid() {
Kevin McNee576bb5d82019-05-29 16:47:518015 if (!web_contents_android_) {
8016 web_contents_android_ = std::make_unique<WebContentsAndroid>(this);
[email protected]155c7f22013-12-09 17:07:188017 }
Kevin McNee576bb5d82019-05-29 16:47:518018 return web_contents_android_.get();
8019}
8020
8021void WebContentsImpl::ClearWebContentsAndroid() {
8022 DCHECK_CURRENTLY_ON(BrowserThread::UI);
8023 web_contents_android_.reset();
[email protected]155c7f22013-12-09 17:07:188024}
8025
paulmeyerc0b762b2016-04-13 11:55:178026void WebContentsImpl::ActivateNearestFindResult(float x,
8027 float y) {
Alexander Timin5fdeff22020-09-08 09:20:378028 OPTIONAL_TRACE_EVENT0("content",
8029 "WebContentsImpl::ActivateNearestFindResult");
paulmeyerc0b762b2016-04-13 11:55:178030 GetOrCreateFindRequestManager()->ActivateNearestFindResult(x, y);
8031}
8032
8033void WebContentsImpl::RequestFindMatchRects(int current_version) {
Alexander Timin5fdeff22020-09-08 09:20:378034 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::RequestFindMatchRects");
paulmeyerc0b762b2016-04-13 11:55:178035 GetOrCreateFindRequestManager()->RequestFindMatchRects(current_version);
8036}
8037
rockot400ea35b2016-10-15 19:15:328038service_manager::InterfaceProvider* WebContentsImpl::GetJavaInterfaces() {
sammcf5f1b0f2016-09-20 23:05:118039 if (!java_interfaces_) {
Gyuyoung Kim6c9ce9022019-11-26 05:40:088040 mojo::PendingRemote<service_manager::mojom::InterfaceProvider> provider;
8041 BindInterfaceRegistryForWebContents(
8042 provider.InitWithNewPipeAndPassReceiver(), this);
rockot400ea35b2016-10-15 19:15:328043 java_interfaces_.reset(new service_manager::InterfaceProvider);
sammcf5f1b0f2016-09-20 23:05:118044 java_interfaces_->Bind(std::move(provider));
8045 }
8046 return java_interfaces_.get();
8047}
8048
Francois Doray6c26f3342018-08-24 17:17:228049#endif
8050
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418051bool WebContentsImpl::CompletedFirstVisuallyNonEmptyPaint() {
Carlos Caballero91fffb22019-10-29 15:24:308052 return GetRenderViewHost()->did_first_visually_non_empty_paint();
spqchane72c3cb2017-06-30 23:02:108053}
8054
pkotwicz75ca8ffd2016-02-16 23:10:198055void WebContentsImpl::OnDidDownloadImage(
Avi Drissmana5a52dd2018-03-27 03:39:028056 ImageDownloadCallback callback,
pkotwicz75ca8ffd2016-02-16 23:10:198057 int id,
8058 const GURL& image_url,
leon.hancbc4bc3c2016-02-26 07:08:528059 int32_t http_status_code,
leon.hanc2228532016-08-16 05:59:188060 const std::vector<SkBitmap>& images,
8061 const std::vector<gfx::Size>& original_image_sizes) {
Alexander Timin5fdeff22020-09-08 09:20:378062 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDidDownloadImage",
8063 "image_url",
8064 base::trace_event::ValueToString(image_url));
Avi Drissmana5a52dd2018-03-27 03:39:028065 std::move(callback).Run(id, http_status_code, image_url, images,
8066 original_image_sizes);
pkotwicz75ca8ffd2016-02-16 23:10:198067}
8068
[email protected]6fba26d2014-04-29 09:38:288069void WebContentsImpl::OnDialogClosed(int render_process_id,
8070 int render_frame_id,
Dave Tapuskacdf545cc2020-01-23 18:38:528071 JavaScriptDialogCallback response_callback,
Avi Drissman1a55a9d62020-03-10 18:56:458072 base::ScopedClosureRunner fullscreen_block,
[email protected]87de04b02014-04-08 22:14:498073 bool dialog_was_suppressed,
[email protected]b172aee2012-04-10 17:05:268074 bool success,
[email protected]fcf75d42013-12-03 20:11:268075 const base::string16& user_input) {
[email protected]6fba26d2014-04-29 09:38:288076 RenderFrameHostImpl* rfh = RenderFrameHostImpl::FromID(render_process_id,
8077 render_frame_id);
Alexander Timin5fdeff22020-09-08 09:20:378078 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnDialogClosed",
8079 "render_frame_host",
8080 base::trace_event::ToTracedValue(rfh));
[email protected]87de04b02014-04-08 22:14:498081 last_dialog_suppressed_ = dialog_was_suppressed;
Avi Drissman1a55a9d62020-03-10 18:56:458082 fullscreen_block.RunAndReset();
[email protected]87de04b02014-04-08 22:14:498083
Charlie Reis96077362019-07-04 00:34:048084 javascript_dialog_navigation_deferrer_.reset();
8085
[email protected]beb440c2009-11-06 04:08:548086 if (is_showing_before_unload_dialog_ && !success) {
clamybc6f4152016-04-01 20:14:238087 // It is possible for the current RenderFrameHost to have changed in the
8088 // meantime. Do not reset the navigation state in that case.
8089 if (rfh && rfh == rfh->frame_tree_node()->current_frame_host()) {
clamy44e84ce2016-02-22 15:38:258090 rfh->frame_tree_node()->BeforeUnloadCanceled();
clamybc6f4152016-04-01 20:14:238091 controller_.DiscardNonCommittedEntries();
8092 }
[email protected]ec8e8b02013-06-19 04:57:108093
Charles Reis15d60b132017-11-03 17:43:478094 // Update the URL display either way, to avoid showing a stale URL.
8095 NotifyNavigationStateChanged(INVALIDATE_TYPE_URL);
8096
Alexander Timin90c20c32020-08-12 15:28:328097 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8098 observer->BeforeUnloadDialogCancelled();
8099 });
[email protected]beb440c2009-11-06 04:08:548100 }
[email protected]87de04b02014-04-08 22:14:498101
Dave Tapuskacdf545cc2020-01-23 18:38:528102 std::move(response_callback).Run(success, user_input);
Pavel Feldman3c1842b2017-08-02 05:00:168103
Dave Tapuskacdf545cc2020-01-23 18:38:528104 std::vector<protocol::PageHandler*> page_handlers =
8105 protocol::PageHandler::EnabledForWebContents(this);
8106 for (auto* handler : page_handlers)
8107 handler->DidCloseJavaScriptDialog(success, user_input);
avi1c51fb62017-02-27 20:43:038108
8109 is_showing_javascript_dialog_ = false;
8110 is_showing_before_unload_dialog_ = false;
[email protected]beb440c2009-11-06 04:08:548111}
8112
[email protected]1ac10dca2013-08-20 20:47:048113bool WebContentsImpl::IsHidden() {
Francois Doraye6161152018-03-27 22:05:378114 return !IsBeingCaptured() && visibility_ != Visibility::VISIBLE;
[email protected]1ac10dca2013-08-20 20:47:048115}
8116
rob97250742015-12-10 17:45:158117int WebContentsImpl::GetOuterDelegateFrameTreeNodeId() {
lfg601233692017-03-06 22:45:448118 return node_.outer_contents_frame_tree_node_id();
lazyboy6ec48b2a2015-06-29 15:18:148119}
8120
ekaramadaeb3c5c2016-11-09 03:22:358121RenderWidgetHostImpl* WebContentsImpl::GetFullscreenRenderWidgetHost() const {
8122 return RenderWidgetHostImpl::FromID(fullscreen_widget_process_id_,
8123 fullscreen_widget_routing_id_);
8124}
8125
[email protected]b0936d22013-11-28 06:47:368126RenderFrameHostManager* WebContentsImpl::GetRenderManager() const {
[email protected]fa944cb82013-11-15 17:51:218127 return frame_tree_.root()->render_manager();
8128}
8129
[email protected]f8497342013-02-05 22:15:028130BrowserPluginGuest* WebContentsImpl::GetBrowserPluginGuest() const {
[email protected]7a846df2012-09-20 19:17:398131 return browser_plugin_guest_.get();
8132}
8133
Albert J. Wongc55cc64d2018-10-12 02:50:048134void WebContentsImpl::SetBrowserPluginGuest(
8135 std::unique_ptr<BrowserPluginGuest> guest) {
Alexander Timin5fdeff22020-09-08 09:20:378136 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetBrowserPluginGuest");
Albert J. Wongc55cc64d2018-10-12 02:50:048137 DCHECK(!browser_plugin_guest_);
8138 DCHECK(guest);
8139 browser_plugin_guest_ = std::move(guest);
[email protected]738f57a2013-06-29 21:06:548140}
8141
Aidan Wolter52bcc12a2018-11-14 03:27:298142base::UnguessableToken WebContentsImpl::GetAudioGroupId() {
Aidan Wolter52bcc12a2018-11-14 03:27:298143 return GetAudioStreamFactory()->group_id();
8144}
8145
Miyoung Shin5709ab02020-02-19 06:50:418146const std::vector<blink::mojom::FaviconURLPtr>&
8147WebContentsImpl::GetFaviconURLs() {
Mounir Lamouri7b4a1f232019-12-23 16:32:108148 return favicon_urls_;
8149}
8150
Mugdha Lakhani0a0d7862020-07-29 09:58:458151// The Mac implementation of the next two methods is in
8152// web_contents_impl_mac.mm
Avi Drissmand4d79f72020-07-30 18:35:188153#if !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:458154
8155void WebContentsImpl::Resize(const gfx::Rect& new_bounds) {
Alexander Timin5fdeff22020-09-08 09:20:378156 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::Resize");
Mugdha Lakhani0a0d7862020-07-29 09:58:458157#if defined(USE_AURA)
8158 aura::Window* window = GetNativeView();
8159 window->SetBounds(gfx::Rect(window->bounds().origin(), new_bounds.size()));
8160#elif defined(OS_ANDROID)
8161 content::RenderWidgetHostView* view = GetRenderWidgetHostView();
8162 if (view)
8163 view->SetBounds(new_bounds);
8164#endif
8165}
8166
8167gfx::Size WebContentsImpl::GetSize() {
8168#if defined(USE_AURA)
8169 aura::Window* window = GetNativeView();
8170 return window->bounds().size();
8171#elif defined(OS_ANDROID)
8172 ui::ViewAndroid* view_android = GetNativeView();
8173 return view_android->bounds().size();
8174#endif
8175}
8176
Avi Drissmand4d79f72020-07-30 18:35:188177#endif // !defined(OS_MAC)
Mugdha Lakhani0a0d7862020-07-29 09:58:458178
[email protected]f8497342013-02-05 22:15:028179BrowserPluginEmbedder* WebContentsImpl::GetBrowserPluginEmbedder() const {
[email protected]7a846df2012-09-20 19:17:398180 return browser_plugin_embedder_.get();
8181}
[email protected]8ff00d72012-10-23 19:12:218182
fsamuel60b42282015-03-10 03:29:148183void WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary() {
Alexander Timin5fdeff22020-09-08 09:20:378184 OPTIONAL_TRACE_EVENT0(
8185 "content", "WebContentsImpl::CreateBrowserPluginEmbedderIfNecessary");
fsamuel60b42282015-03-10 03:29:148186 if (browser_plugin_embedder_)
8187 return;
8188 browser_plugin_embedder_.reset(BrowserPluginEmbedder::Create(this));
8189}
8190
danakja0bce4c952020-05-12 20:40:288191gfx::Size WebContentsImpl::GetSizeForMainFrame() {
8192 if (delegate_) {
8193 // The delegate has a chance to specify a size independent of the UI.
8194 gfx::Size delegate_size = delegate_->GetSizeForNewRenderView(this);
8195 if (!delegate_size.IsEmpty())
8196 return delegate_size;
8197 }
8198
8199 // Device emulation, when enabled, can specify a size independent of the UI.
8200 if (!device_emulation_size_.IsEmpty())
8201 return device_emulation_size_;
8202
8203 return GetContainerBounds().size();
[email protected]dc0fd432013-08-27 15:29:218204}
8205
[email protected]ae7eeda2014-07-04 01:53:268206void WebContentsImpl::OnFrameRemoved(RenderFrameHost* render_frame_host) {
Alexander Timin5fdeff22020-09-08 09:20:378207 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::OnFrameRemoved",
8208 "render_frame_host",
8209 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328210 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8211 observer->FrameDeleted(render_frame_host);
8212 });
[email protected]9b159a52013-10-03 17:24:558213}
8214
[email protected]222f5822014-02-05 23:40:498215void WebContentsImpl::OnPreferredSizeChanged(const gfx::Size& old_size) {
Alexander Timin5fdeff22020-09-08 09:20:378216 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnPreferredSizeChanged");
[email protected]222f5822014-02-05 23:40:498217 if (!delegate_)
8218 return;
8219 const gfx::Size new_size = GetPreferredSize();
8220 if (new_size != old_size)
8221 delegate_->UpdatePreferredSize(this, new_size);
8222}
8223
Miyoung Shin072d4052020-07-13 07:52:448224std::unique_ptr<WebUIImpl> WebContentsImpl::CreateWebUI(
8225 RenderFrameHost* frame_host,
8226 const GURL& url) {
Alexander Timin5fdeff22020-09-08 09:20:378227 TRACE_EVENT2("content", "WebContentsImpl::CreateWebUI", "frame_host",
8228 base::trace_event::ToTracedValue(frame_host), "url",
8229 base::trace_event::ValueToString(url));
Miyoung Shin072d4052020-07-13 07:52:448230 std::unique_ptr<WebUIImpl> web_ui =
8231 std::make_unique<WebUIImpl>(this, frame_host);
Lei Zhangee3b63ad2018-06-06 23:25:318232 std::unique_ptr<WebUIController> controller(
avie865b1d2016-10-24 19:42:598233 WebUIControllerFactoryRegistry::GetInstance()
Lei Zhangee3b63ad2018-06-06 23:25:318234 ->CreateWebUIControllerForURL(web_ui.get(), url));
dbeama1b926a2015-08-31 23:17:518235 if (controller) {
Lei Zhangee3b63ad2018-06-06 23:25:318236 web_ui->SetController(std::move(controller));
dbeama1b926a2015-08-31 23:17:518237 return web_ui;
8238 }
8239
avie865b1d2016-10-24 19:42:598240 return nullptr;
dbeama1b926a2015-08-31 23:17:518241}
8242
Lucas Furukawa Gadanie1c5dfda2018-11-29 17:57:418243FindRequestManager* WebContentsImpl::GetFindRequestManager() {
8244 for (auto* contents = this; contents;
paulmeyerfeafc2d2017-04-25 21:46:408245 contents = contents->GetOuterWebContents()) {
8246 if (contents->find_request_manager_)
8247 return contents->find_request_manager_.get();
8248 }
8249
8250 return nullptr;
8251}
8252
paulmeyerc0b762b2016-04-13 11:55:178253FindRequestManager* WebContentsImpl::GetOrCreateFindRequestManager() {
paulmeyerfeafc2d2017-04-25 21:46:408254 if (FindRequestManager* manager = GetFindRequestManager())
8255 return manager;
8256
Ehsan Karamad6beb2ea2018-11-25 18:15:138257 DCHECK(!browser_plugin_guest_ || GetOuterWebContents());
8258
paulmeyerfeafc2d2017-04-25 21:46:408259 // No existing FindRequestManager found, so one must be created.
8260 find_request_manager_.reset(new FindRequestManager(this));
8261
8262 // Concurrent find sessions must not overlap, so destroy any existing
8263 // FindRequestManagers in any inner WebContentses.
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168264 for (WebContents* contents : GetWebContentsAndAllInner()) {
8265 auto* web_contents_impl = static_cast<WebContentsImpl*>(contents);
8266 if (web_contents_impl == this)
paulmeyerfeafc2d2017-04-25 21:46:408267 continue;
Lucas Furukawa Gadani2ec00c82018-12-14 15:53:168268 if (web_contents_impl->find_request_manager_) {
8269 web_contents_impl->find_request_manager_->StopFinding(
8270 STOP_FIND_ACTION_CLEAR_SELECTION);
8271 web_contents_impl->find_request_manager_.release();
paulmeyerfeafc2d2017-04-25 21:46:408272 }
8273 }
paulmeyerc0b762b2016-04-13 11:55:178274
8275 return find_request_manager_.get();
8276}
8277
8278void WebContentsImpl::NotifyFindReply(int request_id,
8279 int number_of_matches,
8280 const gfx::Rect& selection_rect,
8281 int active_match_ordinal,
8282 bool final_update) {
Alexander Timin5fdeff22020-09-08 09:20:378283 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::NotifyFindReply");
Sebastien Marchandcf97ed52017-07-24 23:50:348284 if (delegate_ && !is_being_destroyed_ &&
Lukasz Anforowicze9ae3722017-09-29 17:37:388285 !GetMainFrame()->GetProcess()->FastShutdownStarted()) {
paulmeyerc0b762b2016-04-13 11:55:178286 delegate_->FindReply(this, request_id, number_of_matches, selection_rect,
8287 active_match_ordinal, final_update);
8288 }
8289}
8290
ortuno467e5792016-06-10 04:32:398291void WebContentsImpl::IncrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378292 OPTIONAL_TRACE_EVENT0(
8293 "content", "WebContentsImpl::IncrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398294 // Trying to invalidate the tab state while being destroyed could result in a
8295 // use after free.
8296 if (IsBeingDestroyed()) {
8297 return;
8298 }
8299 // Notify for UI updates if the state changes.
8300 bluetooth_connected_device_count_++;
8301 if (bluetooth_connected_device_count_ == 1) {
Francois Doray66766a572019-12-17 20:56:498302 OnIsConnectedToBluetoothDeviceChanged(true);
ortuno467e5792016-06-10 04:32:398303 }
8304}
8305
8306void WebContentsImpl::DecrementBluetoothConnectedDeviceCount() {
Alexander Timin5fdeff22020-09-08 09:20:378307 OPTIONAL_TRACE_EVENT0(
8308 "content", "WebContentsImpl::DecrementBluetoothConnectedDeviceCount");
ortuno467e5792016-06-10 04:32:398309 // Trying to invalidate the tab state while being destroyed could result in a
8310 // use after free.
8311 if (IsBeingDestroyed()) {
8312 return;
8313 }
8314 // Notify for UI updates if the state changes.
Lukasz Anforowicze9ae3722017-09-29 17:37:388315 DCHECK_NE(bluetooth_connected_device_count_, 0u);
ortuno467e5792016-06-10 04:32:398316 bluetooth_connected_device_count_--;
8317 if (bluetooth_connected_device_count_ == 0) {
Francois Doray66766a572019-12-17 20:56:498318 OnIsConnectedToBluetoothDeviceChanged(false);
8319 }
8320}
8321
8322void WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged(
8323 bool is_connected_to_bluetooth_device) {
Alexander Timin5fdeff22020-09-08 09:20:378324 OPTIONAL_TRACE_EVENT0(
8325 "content", "WebContentsImpl::OnIsConnectedToBluetoothDeviceChanged");
Francois Doray66766a572019-12-17 20:56:498326 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
Alexander Timin90c20c32020-08-12 15:28:328327 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8328 observer->OnIsConnectedToBluetoothDeviceChanged(
Francois Doray66766a572019-12-17 20:56:498329 is_connected_to_bluetooth_device);
Alexander Timin90c20c32020-08-12 15:28:328330 });
ortuno467e5792016-06-10 04:32:398331}
8332
Ovidio Henriquez76696f62020-07-08 03:06:598333void WebContentsImpl::IncrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378334 OPTIONAL_TRACE_EVENT0(
8335 "content", "WebContentsImpl::IncrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598336 // Trying to invalidate the tab state while being destroyed could result in a
8337 // use after free.
8338 if (IsBeingDestroyed())
8339 return;
8340
8341 // Notify for UI updates if the state changes.
8342 bluetooth_scanning_sessions_count_++;
8343 if (bluetooth_scanning_sessions_count_ == 1)
8344 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8345}
8346
8347void WebContentsImpl::DecrementBluetoothScanningSessionsCount() {
Alexander Timin5fdeff22020-09-08 09:20:378348 OPTIONAL_TRACE_EVENT0(
8349 "content", "WebContentsImpl::DecrementBluetoothScanningSessionsCount");
Ovidio Henriquez76696f62020-07-08 03:06:598350 // Trying to invalidate the tab state while being destroyed could result in a
8351 // use after free.
8352 if (IsBeingDestroyed())
8353 return;
8354
8355 DCHECK_NE(0u, bluetooth_scanning_sessions_count_);
8356 bluetooth_scanning_sessions_count_--;
8357 if (bluetooth_scanning_sessions_count_ == 0)
8358 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8359}
8360
Reilly Grant5e7c79b22019-04-09 17:26:208361void WebContentsImpl::IncrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378362 OPTIONAL_TRACE_EVENT0("content",
8363 "WebContentsImpl::IncrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208364 // Trying to invalidate the tab state while being destroyed could result in a
8365 // use after free.
8366 if (IsBeingDestroyed())
8367 return;
8368
8369 // Notify for UI updates if the state changes.
8370 serial_active_frame_count_++;
8371 if (serial_active_frame_count_ == 1)
8372 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8373}
8374
8375void WebContentsImpl::DecrementSerialActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378376 OPTIONAL_TRACE_EVENT0("content",
8377 "WebContentsImpl::DecrementSerialActiveFrameCount");
Reilly Grant5e7c79b22019-04-09 17:26:208378 // Trying to invalidate the tab state while being destroyed could result in a
8379 // use after free.
8380 if (IsBeingDestroyed())
8381 return;
8382
8383 // Notify for UI updates if the state changes.
8384 DCHECK_NE(0u, serial_active_frame_count_);
8385 serial_active_frame_count_--;
8386 if (serial_active_frame_count_ == 0)
8387 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8388}
8389
Matt Reynoldse8c6c1f2019-11-02 09:53:538390void WebContentsImpl::IncrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378391 OPTIONAL_TRACE_EVENT0("content",
8392 "WebContentsImpl::IncrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538393 // Trying to invalidate the tab state while being destroyed could result in a
8394 // use after free.
8395 if (IsBeingDestroyed())
8396 return;
8397
8398 // Notify for UI updates if the active frame count transitions from zero to
8399 // non-zero.
8400 hid_active_frame_count_++;
8401 if (hid_active_frame_count_ == 1)
8402 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8403}
8404
8405void WebContentsImpl::DecrementHidActiveFrameCount() {
Alexander Timin5fdeff22020-09-08 09:20:378406 OPTIONAL_TRACE_EVENT0("content",
8407 "WebContentsImpl::DecrementHidActiveFrameCount");
Matt Reynoldse8c6c1f2019-11-02 09:53:538408 // Trying to invalidate the tab state while being destroyed could result in a
8409 // use after free.
8410 if (IsBeingDestroyed())
8411 return;
8412
8413 // Notify for UI updates if the active frame count transitions from non-zero
8414 // to zero.
8415 DCHECK_NE(0u, hid_active_frame_count_);
8416 hid_active_frame_count_--;
8417 if (hid_active_frame_count_ == 0)
8418 NotifyNavigationStateChanged(INVALIDATE_TYPE_TAB);
8419}
8420
Marijn Kruisselbrink29051042019-08-06 22:56:558421void WebContentsImpl::IncrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378422 OPTIONAL_TRACE_EVENT0(
8423 "content", "WebContentsImpl::IncrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558424 // Trying to invalidate the tab state while being destroyed could result in a
8425 // use after free.
8426 if (IsBeingDestroyed())
8427 return;
8428
8429 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8430 // to update both the tab-level usage indicator and the usage indicator in the
8431 // omnibox.
8432 native_file_system_handle_count_++;
8433 if (native_file_system_handle_count_ == 1) {
8434 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8435 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8436 }
8437}
8438
8439void WebContentsImpl::DecrementNativeFileSystemHandleCount() {
Alexander Timin5fdeff22020-09-08 09:20:378440 OPTIONAL_TRACE_EVENT0(
8441 "content", "WebContentsImpl::DecrementNativeFileSystemHandleCount");
Marijn Kruisselbrink29051042019-08-06 22:56:558442 // Trying to invalidate the tab state while being destroyed could result in a
8443 // use after free.
8444 if (IsBeingDestroyed())
8445 return;
8446
8447 // Notify for UI updates if the state changes. Need both TYPE_TAB and TYPE_URL
8448 // to update both the tab-level usage indicator and the usage indicator in the
8449 // omnibox.
8450 DCHECK_NE(0u, native_file_system_handle_count_);
8451 native_file_system_handle_count_--;
8452 if (native_file_system_handle_count_ == 0) {
8453 NotifyNavigationStateChanged(static_cast<content::InvalidateTypes>(
8454 INVALIDATE_TYPE_TAB | INVALIDATE_TYPE_URL));
8455 }
8456}
8457
zqzhang8ac49002017-03-16 21:51:358458void WebContentsImpl::SetHasPersistentVideo(bool has_persistent_video) {
Alexander Timin5fdeff22020-09-08 09:20:378459 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::SetHasPersistentVideo",
8460 "has_persistent_video", has_persistent_video,
8461 "had_persistent_value", has_persistent_video_);
zqzhang8ac49002017-03-16 21:51:358462 if (has_persistent_video_ == has_persistent_video)
mlamouri5cd9ae82017-02-18 11:05:098463 return;
8464
zqzhang8ac49002017-03-16 21:51:358465 has_persistent_video_ = has_persistent_video;
mlamouri5cd9ae82017-02-18 11:05:098466 NotifyPreferencesChanged();
zqzhang8ac49002017-03-16 21:51:358467 media_web_contents_observer()->RequestPersistentVideo(has_persistent_video);
mlamouri5cd9ae82017-02-18 11:05:098468}
8469
Ian Vollick5d5c37f2019-06-19 22:50:578470void WebContentsImpl::SetSpatialNavigationDisabled(bool disabled) {
Alexander Timin5fdeff22020-09-08 09:20:378471 OPTIONAL_TRACE_EVENT2(
8472 "content", "WebContentsImpl::SetSpatialNavigationDisabled", "disabled",
8473 disabled, "was_disabled", is_spatial_navigation_disabled_);
Ian Vollick5d5c37f2019-06-19 22:50:578474 if (is_spatial_navigation_disabled_ == disabled)
8475 return;
8476
8477 is_spatial_navigation_disabled_ = disabled;
8478 NotifyPreferencesChanged();
8479}
8480
paulmeyerfeafc2d2017-04-25 21:46:408481void WebContentsImpl::BrowserPluginGuestWillDetach() {
Alexander Timin5fdeff22020-09-08 09:20:378482 OPTIONAL_TRACE_EVENT0("content",
8483 "WebContentsImpl::BrowserPluginGuestWillDetach");
paulmeyerfeafc2d2017-04-25 21:46:408484 WebContentsImpl* outermost = GetOutermostWebContents();
8485 if (this != outermost && ContainsOrIsFocusedWebContents())
8486 outermost->SetAsFocusedWebContentsIfNecessary();
8487}
8488
Becca Hughes112832e2019-06-11 17:19:028489PictureInPictureResult WebContentsImpl::EnterPictureInPicture(
Mounir Lamouri11e9ef42018-05-22 03:10:168490 const viz::SurfaceId& surface_id,
8491 const gfx::Size& natural_size) {
Alexander Timin5fdeff22020-09-08 09:20:378492 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::EnterPictureInPicture");
François Beaufortf09e4462019-01-18 14:34:518493 return delegate_
8494 ? delegate_->EnterPictureInPicture(this, surface_id, natural_size)
Becca Hughes112832e2019-06-11 17:19:028495 : PictureInPictureResult::kNotSupported;
Mounir Lamouri11e9ef42018-05-22 03:10:168496}
8497
Mounir Lamouri6d759e12018-05-16 20:01:308498void WebContentsImpl::ExitPictureInPicture() {
Alexander Timin5fdeff22020-09-08 09:20:378499 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ExitPictureInPicture");
Mounir Lamouri6d759e12018-05-16 20:01:308500 if (delegate_)
8501 delegate_->ExitPictureInPicture();
8502}
8503
paulmeyerc0b762b2016-04-13 11:55:178504#if defined(OS_ANDROID)
8505void WebContentsImpl::NotifyFindMatchRectsReply(
8506 int version,
8507 const std::vector<gfx::RectF>& rects,
8508 const gfx::RectF& active_rect) {
Alexander Timin5fdeff22020-09-08 09:20:378509 OPTIONAL_TRACE_EVENT0("content",
8510 "WebContentsImpl::NotifyFindMatchRectsReply");
paulmeyerc0b762b2016-04-13 11:55:178511 if (delegate_)
8512 delegate_->FindMatchRectsReply(this, version, rects, active_rect);
8513}
8514#endif
8515
[email protected]34ff1cfc2014-08-20 06:16:058516void WebContentsImpl::SetForceDisableOverscrollContent(bool force_disable) {
Alexander Timin5fdeff22020-09-08 09:20:378517 OPTIONAL_TRACE_EVENT1("content",
8518 "WebContentsImpl::SetForceDisableOverscrollContent",
8519 "force_disable", force_disable);
[email protected]34ff1cfc2014-08-20 06:16:058520 force_disable_overscroll_content_ = force_disable;
8521 if (view_)
8522 view_->SetOverscrollControllerEnabled(CanOverscrollContent());
8523}
8524
Jianzhou Fengd8720c72018-01-18 03:06:308525bool WebContentsImpl::SetDeviceEmulationSize(const gfx::Size& new_size) {
Alexander Timin5fdeff22020-09-08 09:20:378526 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308527 device_emulation_size_ = new_size;
8528 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8529
8530 const gfx::Size current_size = rwhv->GetViewBounds().size();
8531 if (view_size_before_emulation_.IsEmpty())
8532 view_size_before_emulation_ = current_size;
8533
8534 if (current_size != new_size)
8535 rwhv->SetSize(new_size);
8536
8537 return current_size != new_size;
8538}
8539
8540void WebContentsImpl::ClearDeviceEmulationSize() {
Alexander Timin5fdeff22020-09-08 09:20:378541 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::ClearDeviceEmulationSize");
Jianzhou Fengd8720c72018-01-18 03:06:308542 RenderWidgetHostView* rwhv = GetMainFrame()->GetView();
8543 // WebContentsView could get resized during emulation, which also resizes
8544 // RWHV. If it happens, assume user would like to keep using the size after
8545 // emulation.
8546 // TODO(jzfeng): Prohibit resizing RWHV through any other means (at least when
8547 // WebContentsView size changes).
Dmitry Gozmanc63707182018-03-06 00:09:398548 if (!view_size_before_emulation_.IsEmpty() && rwhv &&
8549 rwhv->GetViewBounds().size() == device_emulation_size_) {
Jianzhou Fengd8720c72018-01-18 03:06:308550 rwhv->SetSize(view_size_before_emulation_);
Dmitry Gozmanc63707182018-03-06 00:09:398551 }
Jianzhou Fengd8720c72018-01-18 03:06:308552 device_emulation_size_ = gfx::Size();
8553 view_size_before_emulation_ = gfx::Size();
8554}
8555
Max Morin5bc74f52018-05-09 07:00:218556ForwardingAudioStreamFactory* WebContentsImpl::GetAudioStreamFactory() {
8557 if (!audio_stream_factory_) {
8558 audio_stream_factory_.emplace(
8559 this,
Max Morinddebb972018-09-20 10:04:148560 // BrowserMainLoop::GetInstance() may be null in unit tests.
8561 BrowserMainLoop::GetInstance()
8562 ? static_cast<media::UserInputMonitorBase*>(
8563 BrowserMainLoop::GetInstance()->user_input_monitor())
8564 : nullptr,
Ken Rockot72964402019-12-06 10:40:518565 AudioStreamBrokerFactory::CreateImpl());
Max Morin5bc74f52018-05-09 07:00:218566 }
8567
8568 return &*audio_stream_factory_;
8569}
8570
dalecurtis88c240072015-12-09 02:11:188571void WebContentsImpl::MediaStartedPlaying(
billorr21c005d2016-11-17 03:57:048572 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358573 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378574 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStartedPlaying");
billorr21c005d2016-11-17 03:57:048575 if (media_info.has_video)
8576 currently_playing_video_count_++;
8577
Alexander Timin90c20c32020-08-12 15:28:328578 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8579 observer->MediaStartedPlaying(media_info, id);
8580 });
dalecurtis88c240072015-12-09 02:11:188581}
8582
8583void WebContentsImpl::MediaStoppedPlaying(
billorr21c005d2016-11-17 03:57:048584 const WebContentsObserver::MediaPlayerInfo& media_info,
Mounir Lamouri0f5bdf52019-04-04 16:32:358585 const MediaPlayerId& id,
Becca Hughes220bfc102017-11-14 18:24:078586 WebContentsObserver::MediaStoppedReason reason) {
Alexander Timin5fdeff22020-09-08 09:20:378587 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaStoppedPlaying");
billorr21c005d2016-11-17 03:57:048588 if (media_info.has_video)
8589 currently_playing_video_count_--;
8590
Alexander Timin90c20c32020-08-12 15:28:328591 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8592 observer->MediaStoppedPlaying(media_info, id, reason);
8593 });
billorr21c005d2016-11-17 03:57:048594}
8595
Mounir Lamouri0f5bdf52019-04-04 16:32:358596void WebContentsImpl::MediaResized(const gfx::Size& size,
8597 const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378598 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaResized");
peconn257951522017-06-09 18:24:598599 cached_video_sizes_[id] = size;
8600
Alexander Timin90c20c32020-08-12 15:28:328601 observers_.ForEachObserver(
8602 [&](WebContentsObserver* observer) { observer->MediaResized(size, id); });
peconn257951522017-06-09 18:24:598603}
8604
Michael Crousee75c7a42020-07-31 21:11:558605void WebContentsImpl::MediaBufferUnderflow(const MediaPlayerId& id) {
Alexander Timin5fdeff22020-09-08 09:20:378606 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::MediaBufferUnderflow");
Alexander Timin90c20c32020-08-12 15:28:328607 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8608 observer->MediaBufferUnderflow(id);
8609 });
Michael Crousee75c7a42020-07-31 21:11:558610}
8611
Peter E Conneccb34c22017-09-08 09:37:588612void WebContentsImpl::MediaEffectivelyFullscreenChanged(bool is_fullscreen) {
Alexander Timin5fdeff22020-09-08 09:20:378613 OPTIONAL_TRACE_EVENT1("content",
8614 "WebContentsImpl::MediaEffectivelyFullscreenChanged",
8615 "is_fullscreen", is_fullscreen);
Alexander Timin90c20c32020-08-12 15:28:328616 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8617 observer->MediaEffectivelyFullscreenChanged(is_fullscreen);
8618 });
Peter E Conneccb34c22017-09-08 09:37:588619}
8620
Peter Conn31c726a2017-08-17 11:07:348621base::Optional<gfx::Size> WebContentsImpl::GetFullscreenVideoSize() {
Mounir Lamouri0f5bdf52019-04-04 16:32:358622 base::Optional<MediaPlayerId> id =
Peter Conn31c726a2017-08-17 11:07:348623 media_web_contents_observer_->GetFullscreenVideoMediaPlayerId();
Jan Wilken Dörrie531be7ca2019-06-07 10:05:578624 if (id && base::Contains(cached_video_sizes_, id.value()))
Peter Conn31c726a2017-08-17 11:07:348625 return base::Optional<gfx::Size>(cached_video_sizes_[id.value()]);
Lei Zhang6410ec1a2019-01-31 21:38:588626 return base::nullopt;
peconn257951522017-06-09 18:24:598627}
8628
billorr21c005d2016-11-17 03:57:048629int WebContentsImpl::GetCurrentlyPlayingVideoCount() {
8630 return currently_playing_video_count_;
dalecurtis88c240072015-12-09 02:11:188631}
8632
Raymond Toye413650c2018-08-31 00:12:478633void WebContentsImpl::AudioContextPlaybackStarted(RenderFrameHost* host,
8634 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378635 OPTIONAL_TRACE_EVENT1(
8636 "content", "WebContentsImpl::AudioContextPlaybackStarted",
8637 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478638 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328639 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8640 observer->AudioContextPlaybackStarted(audio_context_id);
8641 });
Raymond Toye413650c2018-08-31 00:12:478642}
8643
8644void WebContentsImpl::AudioContextPlaybackStopped(RenderFrameHost* host,
8645 int context_id) {
Alexander Timin5fdeff22020-09-08 09:20:378646 OPTIONAL_TRACE_EVENT1(
8647 "content", "WebContentsImpl::AudioContextPlaybackStopped",
8648 "render_frame_host", base::trace_event::ToTracedValue(host));
Raymond Toye413650c2018-08-31 00:12:478649 WebContentsObserver::AudioContextId audio_context_id(host, context_id);
Alexander Timin90c20c32020-08-12 15:28:328650 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8651 observer->AudioContextPlaybackStopped(audio_context_id);
8652 });
Raymond Toye413650c2018-08-31 00:12:478653}
8654
Chris Hamilton16ca64a2020-05-14 23:13:178655void WebContentsImpl::OnFrameAudioStateChanged(RenderFrameHost* host,
8656 bool is_audible) {
Alexander Timin5fdeff22020-09-08 09:20:378657 OPTIONAL_TRACE_EVENT2("content", "WebContentsImpl::OnFrameAudioStateChanged",
8658 "render_frame_host",
8659 base::trace_event::ToTracedValue(host), "is_audible",
8660 is_audible);
Alexander Timin90c20c32020-08-12 15:28:328661 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8662 observer->OnFrameAudioStateChanged(host, is_audible);
8663 });
Chris Hamilton16ca64a2020-05-14 23:13:178664}
8665
evliu7f736f02019-11-07 17:43:508666media::MediaMetricsProvider::RecordAggregateWatchTimeCallback
8667WebContentsImpl::GetRecordAggregateWatchTimeCallback() {
Alexander Timin5fdeff22020-09-08 09:20:378668 OPTIONAL_TRACE_EVENT0("content",
8669 "WebContentsImpl::RecordAggregateWatchTimeCallback");
Becca Hughes53652442020-03-17 15:35:428670 if (!delegate_ || !delegate_->GetDelegateWeakPtr())
8671 return base::DoNothing();
8672
evliu7f736f02019-11-07 17:43:508673 return base::BindRepeating(
Becca Hughes53652442020-03-17 15:35:428674 [](base::WeakPtr<WebContentsDelegate> delegate, GURL last_committed_url,
8675 base::TimeDelta total_watch_time, base::TimeDelta time_stamp,
8676 bool has_video, bool has_audio) {
evliua283c9e2019-11-08 22:57:228677 content::MediaPlayerWatchTime watch_time(
8678 last_committed_url, last_committed_url.GetOrigin(),
8679 total_watch_time, time_stamp, has_video, has_audio);
evliu7f736f02019-11-07 17:43:508680
8681 // Save the watch time if the delegate is still alive.
8682 if (delegate)
8683 delegate->MediaWatchTimeChanged(watch_time);
8684 },
Becca Hughes53652442020-03-17 15:35:428685 delegate_->GetDelegateWeakPtr(), GetMainFrameLastCommittedURL());
evliu7f736f02019-11-07 17:43:508686}
8687
Ehsan Karamad1c631762019-05-13 23:04:018688RenderFrameHostImpl* WebContentsImpl::GetMainFrameForInnerDelegate(
8689 FrameTreeNode* frame_tree_node) {
8690 if (auto* web_contents = node_.GetInnerWebContentsInFrame(frame_tree_node))
8691 return web_contents->GetMainFrame();
8692 return nullptr;
8693}
8694
John Budorickee1c9512019-10-17 15:32:198695bool WebContentsImpl::IsFrameLowPriority(
8696 const RenderFrameHost* render_frame_host) {
8697 if (!delegate_)
8698 return false;
8699 return delegate_->IsFrameLowPriority(this, render_frame_host);
8700}
8701
Roger Tawa03ffdbd2020-01-16 18:12:548702void WebContentsImpl::IsClipboardPasteAllowed(
8703 const GURL& url,
8704 const ui::ClipboardFormatType& data_type,
8705 const std::string& data,
8706 IsClipboardPasteAllowedCallback callback) {
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008707 ++suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548708 GetContentClient()->browser()->IsClipboardPasteAllowed(
Dominique Fauteux-Chapleau99244382020-07-08 20:37:008709 this, url, data_type, data,
8710 base::BindOnce(&WebContentsImpl::IsClipboardPasteAllowedWrapperCallback,
8711 weak_factory_.GetWeakPtr(), std::move(callback)));
8712}
8713
8714void WebContentsImpl::IsClipboardPasteAllowedWrapperCallback(
8715 IsClipboardPasteAllowedCallback callback,
8716 ClipboardPasteAllowed allowed) {
8717 std::move(callback).Run(allowed);
8718 --suppress_unresponsive_renderer_count_;
Roger Tawa03ffdbd2020-01-16 18:12:548719}
8720
Lan Weif81c6e7c2020-02-12 16:46:098721bool WebContentsImpl::HasSeenRecentScreenOrientationChange() {
8722 static constexpr base::TimeDelta kMaxInterval =
8723 base::TimeDelta::FromSeconds(1);
8724 base::TimeDelta delta =
8725 ui::EventTimeForNow() - last_screen_orientation_change_time_;
8726 // Return whether there is a screen orientation change happened in the recent
8727 // 1 second.
8728 return delta <= kMaxInterval;
8729}
8730
8731void WebContentsImpl::DidChangeScreenOrientation() {
8732 last_screen_orientation_change_time_ = ui::EventTimeForNow();
8733}
8734
Miyoung Shin8f2e1832020-04-27 09:00:028735bool WebContentsImpl::ShowPopupMenu(
Miyoung Shin4d947d22020-04-24 04:48:338736 RenderFrameHostImpl* render_frame_host,
Miyoung Shin8f2e1832020-04-27 09:00:028737 mojo::PendingRemote<blink::mojom::PopupMenuClient>* popup_client,
Miyoung Shin4d947d22020-04-24 04:48:338738 const gfx::Rect& bounds,
8739 int32_t item_height,
8740 double font_size,
8741 int32_t selected_item,
8742 std::vector<blink::mojom::MenuItemPtr>* menu_items,
8743 bool right_aligned,
8744 bool allow_multiple_selection) {
Alexander Timin5fdeff22020-09-08 09:20:378745 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ShowPopupMenu",
8746 "render_frame_host",
8747 base::trace_event::ToTracedValue(render_frame_host));
Alexander Timin90c20c32020-08-12 15:28:328748 for (auto& observer : observers_.observer_list()) {
Miyoung Shin8f2e1832020-04-27 09:00:028749 if (observer.ShowPopupMenu(render_frame_host, popup_client, bounds,
8750 item_height, font_size, selected_item,
8751 menu_items, right_aligned,
8752 allow_multiple_selection)) {
Miyoung Shin4d947d22020-04-24 04:48:338753 return true;
8754 }
8755 }
8756 return false;
8757}
8758
Francois Doraye6161152018-03-27 22:05:378759void WebContentsImpl::UpdateWebContentsVisibility(Visibility visibility) {
Alexander Timin5fdeff22020-09-08 09:20:378760 OPTIONAL_TRACE_EVENT1("content",
8761 "WebContentsImpl::UpdateWebContentsVisibility",
8762 "visibility", visibility);
Francois Doray3f2afbd2018-04-06 19:18:188763 // Occlusion is disabled when |features::kWebContentsOcclusion| is disabled
8764 // (for power and speed impact assessment) or when
8765 // |switches::kDisableBackgroundingOccludedWindowsForTesting| is specified on
8766 // the command line (to avoid flakiness in browser tests).
8767 const bool occlusion_is_disabled =
8768 !base::FeatureList::IsEnabled(features::kWebContentsOcclusion) ||
Francois Doraye6161152018-03-27 22:05:378769 base::CommandLine::ForCurrentProcess()->HasSwitch(
8770 switches::kDisableBackgroundingOccludedWindowsForTesting);
8771 if (occlusion_is_disabled && visibility == Visibility::OCCLUDED)
8772 visibility = Visibility::VISIBLE;
8773
tapted65ff2ea72016-03-01 23:39:008774 if (!did_first_set_visible_) {
Francois Doraye6161152018-03-27 22:05:378775 if (visibility == Visibility::VISIBLE) {
8776 // A WebContents created with CreateParams::initially_hidden = false
8777 // starts with GetVisibility() == Visibility::VISIBLE even though it is
8778 // not really visible. Call WasShown() when it becomes visible for real as
8779 // the page load mechanism and some WebContentsObserver rely on that.
tapted65ff2ea72016-03-01 23:39:008780 WasShown();
Francois Dorayfe4a1772018-02-17 04:17:098781 did_first_set_visible_ = true;
tapted65ff2ea72016-03-01 23:39:008782 }
Francois Doraye6161152018-03-27 22:05:378783
8784 // Trust the initial visibility of the WebContents and do not switch it to
8785 // HIDDEN or OCCLUDED before it becomes VISIBLE for real. Doing so would
8786 // result in destroying resources that would immediately be recreated (e.g.
8787 // UpdateWebContents(HIDDEN) can be called when a WebContents is added to a
8788 // hidden window that is about to be shown).
8789
tapted65ff2ea72016-03-01 23:39:008790 return;
8791 }
Francois Doraye6161152018-03-27 22:05:378792
8793 if (visibility == visibility_)
tapted65ff2ea72016-03-01 23:39:008794 return;
8795
Collin Baker989e0882019-11-01 01:27:178796 UpdateVisibilityAndNotifyPageAndView(visibility);
tapted65ff2ea72016-03-01 23:39:008797}
8798
aelias5252baa2016-04-10 01:18:028799void WebContentsImpl::UpdateOverridingUserAgent() {
Alexander Timin5fdeff22020-09-08 09:20:378800 OPTIONAL_TRACE_EVENT0("content",
8801 "WebContentsImpl::UpdateOverridingUserAgent");
mlamouri5cd9ae82017-02-18 11:05:098802 NotifyPreferencesChanged();
aelias5252baa2016-04-10 01:18:028803}
8804
avid53461d2016-02-25 17:15:048805void WebContentsImpl::SetJavaScriptDialogManagerForTesting(
8806 JavaScriptDialogManager* dialog_manager) {
Alexander Timin5fdeff22020-09-08 09:20:378807 OPTIONAL_TRACE_EVENT0(
8808 "content", "WebContentsImpl::SetJavaScriptDialogManagerForTesting");
avid53461d2016-02-25 17:15:048809 dialog_manager_ = dialog_manager;
8810}
8811
Julie Jeongeun Kim7d0986172019-12-04 03:17:258812void WebContentsImpl::RemoveReceiverSet(const std::string& interface_name) {
Alexander Timin5fdeff22020-09-08 09:20:378813 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::RemoveReceiverSet",
8814 "interface_name", interface_name);
Julie Jeongeun Kim7d0986172019-12-04 03:17:258815 auto it = receiver_sets_.find(interface_name);
8816 if (it != receiver_sets_.end())
8817 receiver_sets_.erase(it);
rockotf62002a2016-09-15 00:08:598818}
8819
nzolghadrd87a308d2016-12-07 15:45:568820bool WebContentsImpl::AddDomainInfoToRapporSample(rappor::Sample* sample) {
Alexander Timin5fdeff22020-09-08 09:20:378821 OPTIONAL_TRACE_EVENT0("content",
8822 "WebContentsImpl::AddDomainInfoToRapporSample");
nzolghadrbbffc6c2017-05-25 17:56:398823 // Here we associate this metric to the main frame URL regardless of what
8824 // caused it.
nzolghadrd87a308d2016-12-07 15:45:568825 sample->SetStringField("Domain", ::rappor::GetDomainAndRegistrySampleFromGURL(
8826 GetLastCommittedURL()));
nzolghadrd87a308d2016-12-07 15:45:568827 return true;
8828}
8829
falken52a56e32016-12-08 05:02:408830void WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded() {
Alexander Timin5fdeff22020-09-08 09:20:378831 OPTIONAL_TRACE_EVENT0(
8832 "content", "WebContentsImpl::ShowInsecureLocalhostWarningIfNeeded");
falken52a56e32016-12-08 05:02:408833 bool allow_localhost = base::CommandLine::ForCurrentProcess()->HasSwitch(
8834 switches::kAllowInsecureLocalhost);
8835 if (!allow_localhost)
8836 return;
8837
8838 content::NavigationEntry* entry = GetController().GetLastCommittedEntry();
Rob Wuf79b3ba2018-01-14 01:54:318839 if (!entry || !net::IsLocalhost(entry->GetURL()))
falken52a56e32016-12-08 05:02:408840 return;
8841
8842 content::SSLStatus ssl_status = entry->GetSSL();
Matt Mueller936511442019-09-03 18:15:128843 if (!net::IsCertStatusError(ssl_status.cert_status))
falken52a56e32016-12-08 05:02:408844 return;
8845
8846 GetMainFrame()->AddMessageToConsole(
Abhijeet Kandalkara5928a0a2019-03-13 05:04:428847 blink::mojom::ConsoleMessageLevel::kWarning,
falken52a56e32016-12-08 05:02:408848 base::StringPrintf("This site does not have a valid SSL "
8849 "certificate! Without SSL, your site's and "
8850 "visitors' data is vulnerable to theft and "
8851 "tampering. Get a valid SSL certificate before"
8852 " releasing your website to the public."));
8853}
8854
ekaramadf6750aa2017-06-06 18:29:428855bool WebContentsImpl::IsShowingContextMenuOnPage() const {
8856 return showing_context_menu_;
8857}
8858
Min Qina904f3302018-02-13 23:33:348859download::DownloadUrlParameters::RequestHeadersType
8860WebContentsImpl::ParseDownloadHeaders(const std::string& headers) {
Alexander Timin5fdeff22020-09-08 09:20:378861 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::ParseDownloadHeaders",
8862 "headers", headers);
Min Qina904f3302018-02-13 23:33:348863 download::DownloadUrlParameters::RequestHeadersType request_headers;
Megan Jablonski2f6a4c52017-07-10 23:01:258864 for (const base::StringPiece& key_value : base::SplitStringPiece(
8865 headers, "\r\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_NONEMPTY)) {
8866 std::vector<std::string> pair = base::SplitString(
8867 key_value, ":", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
8868 if (2ul == pair.size())
8869 request_headers.push_back(make_pair(pair[0], pair[1]));
8870 }
8871 return request_headers;
8872}
8873
lukasza6f8ac622017-06-06 03:10:208874void WebContentsImpl::SetOpenerForNewContents(FrameTreeNode* opener,
8875 bool opener_suppressed) {
Alexander Timin5fdeff22020-09-08 09:20:378876 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::SetOpenerForNewContents");
lukasza6f8ac622017-06-06 03:10:208877 if (opener) {
8878 FrameTreeNode* new_root = GetFrameTree()->root();
8879
8880 // For the "original opener", track the opener's main frame instead, because
8881 // if the opener is a subframe, the opener tracking could be easily bypassed
8882 // by spawning from a subframe and deleting the subframe.
8883 // https://crbug.com/705316
8884 new_root->SetOriginalOpener(opener->frame_tree()->root());
8885
8886 if (!opener_suppressed) {
8887 new_root->SetOpener(opener);
8888 created_with_opener_ = true;
8889 }
8890 }
8891}
8892
Mounir Lamouri0f5bdf52019-04-04 16:32:358893void WebContentsImpl::MediaMutedStatusChanged(const MediaPlayerId& id,
8894 bool muted) {
Alexander Timin5fdeff22020-09-08 09:20:378895 OPTIONAL_TRACE_EVENT1("content", "WebContentsImpl::MediaMutedStatusChanged",
8896 "muted", muted);
Alexander Timin90c20c32020-08-12 15:28:328897 observers_.ForEachObserver([&](WebContentsObserver* observer) {
8898 observer->MediaMutedStatusChanged(id, muted);
8899 });
Becca Hughes9f6fd4b82017-06-15 10:01:408900}
8901
EhsanK2075c7e2017-08-21 02:42:398902void WebContentsImpl::SetVisibilityForChildViews(bool visible) {
Alexander Timin5fdeff22020-09-08 09:20:378903 OPTIONAL_TRACE_EVENT1("content",
8904 "WebContentsImpl::SetVisibilityForChildViews",
8905 "visible", visible);
EhsanK2075c7e2017-08-21 02:42:398906 GetMainFrame()->SetVisibilityForChildViews(visible);
8907}
8908
Alison Maher7f366dc62020-03-03 19:46:008909void WebContentsImpl::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) {
Alexander Timin5fdeff22020-09-08 09:20:378910 OPTIONAL_TRACE_EVENT0("content", "WebContentsImpl::OnNativeThemeUpdated");
Alison Maher7f366dc62020-03-03 19:46:008911 DCHECK(native_theme_observer_.IsObserving(observed_theme));
8912
8913 bool using_dark_colors = observed_theme->ShouldUseDarkColors();
8914 ui::NativeTheme::PreferredColorScheme preferred_color_scheme =
8915 observed_theme->GetPreferredColorScheme();
8916 bool preferences_changed = false;
8917
8918 if (using_dark_colors_ != using_dark_colors) {
8919 using_dark_colors_ = using_dark_colors;
8920 preferences_changed = true;
8921 }
8922 if (preferred_color_scheme_ != preferred_color_scheme) {
8923 preferred_color_scheme_ = preferred_color_scheme;
8924 preferences_changed = true;
8925 }
8926
8927 if (preferences_changed)
8928 NotifyPreferencesChanged();
8929}
8930
Dave Tapuska58a099e2020-06-08 21:48:408931blink::mojom::FrameWidgetInputHandler*
8932WebContentsImpl::GetFocusedFrameWidgetInputHandler() {
8933 auto* focused_render_widget_host =
8934 GetFocusedRenderWidgetHost(GetMainFrame()->GetRenderWidgetHost());
8935 if (!focused_render_widget_host)
Dave Tapuskae782bea2019-07-09 16:21:518936 return nullptr;
Dave Tapuska58a099e2020-06-08 21:48:408937 return focused_render_widget_host->GetFrameWidgetInputHandler();
Dave Tapuskae782bea2019-07-09 16:21:518938}
8939
Alexander Timine3ec4192020-04-20 16:39:408940ukm::SourceId WebContentsImpl::GetCurrentPageUkmSourceId() {
8941 return GetMainFrame()->GetPageUkmSourceId();
8942}
8943
Yuzu Saijo232076f2020-05-29 07:14:028944std::set<RenderViewHostImpl*>
8945WebContentsImpl::GetRenderViewHostsIncludingBackForwardCached() {
8946 std::set<RenderViewHostImpl*> render_view_hosts;
8947
8948 // Add RenderViewHostImpls outside of BackForwardCache.
8949 for (auto& render_view_host : frame_tree_.render_view_hosts()) {
8950 render_view_hosts.insert(render_view_host.second);
8951 }
8952
8953 // Add RenderViewHostImpls in BackForwardCache.
8954 const auto& entries = GetController().GetBackForwardCache().GetEntries();
8955 for (const auto& entry : entries) {
8956 std::set<RenderViewHostImpl*> bfcached_hosts = entry->render_view_hosts;
8957 render_view_hosts.insert(bfcached_hosts.begin(), bfcached_hosts.end());
8958 }
8959
8960 return render_view_hosts;
8961}
8962
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508963void WebContentsImpl::RenderFrameHostStateChanged(
8964 RenderFrameHost* render_frame_host,
8965 LifecycleState old_state,
8966 LifecycleState new_state) {
Alexander Timin5fdeff22020-09-08 09:20:378967 OPTIONAL_TRACE_EVENT2(
8968 "content", "WebContentsImpl::RenderFrameHostStateChanged",
8969 "render_frame_host", base::trace_event::ToTracedValue(render_frame_host),
8970 "states",
8971 base::trace_event::TracedValue::Build(
8972 {{"old", base::trace_event::ValueToString(old_state)},
8973 {"new", base::trace_event::ValueToString(new_state)}}));
Sreeja Kamishettybe0ccd6b2020-06-09 11:52:508974 if (render_frame_host->GetParent())
8975 return;
8976
8977 if (old_state == LifecycleState::kActive &&
8978 new_state != LifecycleState::kActive) {
8979 // TODO(sreejakshetty): Remove this reset when ColorChooser becomes
8980 // per-frame.
8981 // Close the color chooser popup when RenderFrameHost changes state from
8982 // kActive.
8983 color_chooser_.reset();
8984 }
8985}
8986
[email protected]8ff00d72012-10-23 19:12:218987} // namespace content